How to do advanced sorting of key columns
The logical order of operations in SQL for your first query (simplified):
FROM abc_testSELECT n_num, k_str i.e. add the so-called extended sort key columnORDER BY k_str DESCSELECT n_num i.e. SELECT n_num remove the extended sort key column from the result.
Thanks to the standard function of the extended SQL collation key column, you can sort something that is not in the SELECT because it is temporarily added to it behind the scenes before ordering, and then deleted again after ordering.
So why does this not work with DISTINCT ?
If we add the DISTINCT operation, it will need to be added between SELECT and ORDER BY :
FROM abc_testSELECT n_num, k_str i.e. add the so-called extended sort key columnDISTINCTORDER BY k_str DESCSELECT n_num i.e. SELECT n_num remove the extended sort key column from the result.
But now, with the extended sort key column k_str , the semantics of the DISTINCT operation have been changed, so the result will no longer be the same. This is not what we want, so the SQL standard and all reasonable databases prohibit this use.
workarounds
PostgreSQL has the DISTINCT ON , which can be used here just for this work:
SELECT DISTINCT ON (k_str) n_num FROM abc_test ORDER BY k_str DESC
It can be emulated with standard syntax as follows if you are not using PostgreSQL
SELECT n_num FROM ( SELECT n_num, MIN(k_str) AS k_str FROM abc_test GROUP BY n_num ) t ORDER BY k_str
Or just (in this case)
SELECT n_num, MIN(k_str) AS k_str FROM abc_test GROUP BY n_num ORDER BY k_str
I wrote more about SQL DISTINCT and ORDER BY here .
source share