How do extended sort key columns
The logical order of operations in SQL for your first query, is (simplified):
FROM abc_test
SELECT n_num, k_str
i.e. add a so called extended sort key column
ORDER BY k_str DESC
SELECT n_num
i.e. remove the extended sort key column again from the result.
Thanks to the SQL standard extended sort key column feature, it is possible to order by something that is not in the SELECT
clause, because it is being temporarily added to it behind the scenes prior to ordering, and then removed again after ordering.
So, why doesn't this work with DISTINCT
?
If we add the DISTINCT
operation, it would need to be added between SELECT
and ORDER BY
:
FROM abc_test
SELECT n_num, k_str
i.e. add a so called extended sort key column
DISTINCT
ORDER BY k_str DESC
SELECT n_num
i.e. remove the extended sort key column again from the result.
But now, with the extended sort key column k_str
, the semantics of the DISTINCT
operation has been changed, so the result will no longer be the same. This is not what we want, so both the SQL standard, and all reasonable databases forbid this usage.
Workarounds
PostgreSQL has the DISTINCT ON
syntax, which can be used here for precisely this job:
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're 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 simply (in this case)
SELECT n_num, MIN(k_str) AS k_str
FROM abc_test
GROUP BY n_num
ORDER BY k_str
I have blogged about SQL DISTINCT and ORDER BY more in detail here.
ORA-01791: not a SELECTed expression
as thek_str
column is not being selected. Is this the actual query you ran? (It may be acceptable in 9i, but I can't be sure.) – Suzisuzie