Search

Thursday 15 October 2015

ORA-01791: not a SELECTed expression - Oracle Error

This Error message might show up when you are trying to use DISTINCT with ORDER BY clause. Let us try and understand when this error message comes and what is causing it. Take the following simple SQL for example:

  SELECT    DISTINCT a, b
    FROM      mytable
ORDER BY c

When we try to run the above SQL we will get the error message: "ORA-01791: not a SELECTed expression".
The reason for this is simple, once you have applied DISTINCT to the result set the only columns that are available are the ones written (calculated) in the SELECT query.
So if you try to run the below query then it will run without any issues:

   SELECT   DISTINCT a, b, c
    FROM      mytable
ORDER BY c

If this guide was helpful to you, do not forget to leave a Thanks message.