Ora-01791: not a SELECTed expression
To fix ORA-01791: include all ORDER BY
fields in the SELECT DISTINCT
query. To keep the order by fields that you didn't SELECT DISTINCT
, wrap your query as follows:
An amended query:
Or, retain the original order without choosing id
:
Causes of ORA-01791 error and how to fix it
The turning point: the ORA-01791 error will knock on your door when you try to ORDER BY
a column that has not been invited to the SELECT DISTINCT
party. The fix? Either invite everyone to the party or change the guest list!
Understanding ORA-01791: Examples & Solutions
Scenario 1: Mixing COUNT
with DISTINCT
is like pineapple on pizza - it's a matter of taste. However, if the grouping isn't correct, you may get the ORA-01791 error served on your plate.
Scenario 2: Columns not prettied up with an aggregate function must dress up with the GROUP BY
clause for the SELECT DISTINCT
party.
Essential Tips for writing SELECT DISTINCT Queries to Avoid ORA-01791
Consistency between SELECT and ORDER BY
Keep SELECT
and ORDER BY
on the same page. An aligned understanding between them is the key to prevent errors.
Revising the STRUCTURE of your SQL Query
Sometimes it's not about just correcting errors - it's about rethinking your query's logic.
How to Handle ALIASES and JOINS
When using aliases, ensure that they don't blur the bond between SELECT
and ORDER BY
.
When dealing with joins, it's crucial that aggregated columns are not wrongly referenced from different tables.
Was this article helpful?