Moonglade

Modern Markdown blogging with AI-powered localization and search.

Tag: Deterministic Order


Issue with Non-Deterministic Ordering of Identical Values in PostgreSQL

PostgreSQL and SQL Server exhibit significant differences in the stability of data sorting. SQL Server stores data physically by primary key, ensuring a fixed order when sort values are identical. In contrast, PostgreSQL uses a heap table structure where the physical location of data changes dynamically with updates, resulting in an unpredictable row order when the `ORDER BY` column contains duplicate values. The solution is to always include a unique column (such as the primary key) as a secondary sorting condition in the `ORDER BY` clause. For example, using `ORDER BY create_time DESC, id DESC` ensures a stable query result order. It is recommended to develop the habit of including a unique column as a fallback in all sorting queries to avoid relying on the database engine's implicit behavior.

Views 198
.NET Data Sorting Deterministic Order ORDER BY PostgreSQL SQL Server