Using the DISTINCT keyword causes this error: not a SELECTed expression

SqlOracleHibernateOracle11g

Sql Problem Overview


I have a query that looks something like this:

SELECT DISTINCT share.rooms
FROM Shares share
  left join share.rooms.buildingAdditions.buildings.buildingInfoses as bi
... //where clause omitted
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent

Which results in the following exception:

Caused by: org.hibernate.exception.SQLGrammarException: ORA-01791: not a SELECTed expression

If I remove the DISTINCT keyword, the query runs without issue. If I remove the order by clause, the query runs without issue. Unfortunately, I can't seem to get the ordered result set without duplicates.

Sql Solutions


Solution 1 - Sql

You are trying to order your result with columns that are not being calculated. This wouldn't be a problem if you didn't have the DISTINCT there, but since your query is basically grouping only by share.rooms column, how can it order that result set with other columns that can have multiple values for the same share.rooms one?

Solution 2 - Sql

This post is a little old but one thing I did to get around this error is wrap the query and just apply the order by on the outside like so.

SELECT COL
FROM (
   SELECT DISTINCT COL, ORDER_BY_COL
   FROM TABLE
   // ADD JOINS, WHERE CLAUSES, ETC.
) 
ORDER BY ORDER_BY_COL;

Hope this helps :)

Solution 3 - Sql

When using DISTINCT in a query that has an ORDER BY you must select all the columns you've used in the ORDER BY statement:

SELECT DISTINCT share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
...
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKenView Question on Stackoverflow
Solution 1 - SqlLamakView Answer on Stackoverflow
Solution 2 - SqlMatthew ZackschewskiView Answer on Stackoverflow
Solution 3 - SqlBoško BezikView Answer on Stackoverflow