Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 671
Ken Avatar asked Mar 07 '13 15:03

Ken


People also ask

What does the distinct keyword do?

The DISTINCT keyword in the SELECT clause is used to eliminate duplicate rows and display a unique list of values. In other words, the DISTINCT keyword retrieves unique values from a table.

Can I use distinct * in SQL?

The SQL SELECT DISTINCT StatementThe SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

What could happen if the keyword distinct is omitted in this query?

If you omit DISTINCT, this query returns both Smith records. If the SELECT clause contains more than one field, the combination of values from all fields must be unique for a given record to be included in the results.

What is the use of distinct keyword with example?

The distinct keyword is used in conjunction with select keyword. It is helpful when there is a need of avoiding duplicate values present in any specific columns/table. When we use distinct keyword only the unique values are fetched. column1, column2 : Names of the fields of the table.


2 Answers

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?

like image 125
Lamak Avatar answered Oct 16 '22 13:10

Lamak


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 :)

like image 31
Matthew Zackschewski Avatar answered Oct 16 '22 14:10

Matthew Zackschewski