Using the DISTINCT keyword causes this error: not a SELECTed expression
Seeing a "not a SELECTed expression" error with DISTINCT? Ensure that each column in your SELECT statement not listed in the DISTINCT, is part of an aggregate function if a GROUP BY is present. Proper aggregate functions to include are MAX(), MIN(), SUM(), or COUNT(). Here is your quick fix:
This query returns a distinct customer_id and the latest_order_date. So, no more errors!
Deep dive into DISTINCT and ORDER BY
When you use DISTINCT, SQL returns only unique rows from your result set. However, combining DISTINCT with ORDER BY can be like herding cats - SQL struggles to ensure the rows are both unique and sorted! This is an issue especially when your ORDER BY includes columns calculated or derived from various joins.
When there's an attempt to order by a column that isn’t in the SELECT DISTINCT list of a query, you're likely to run into an ORA-01791: not a SELECTED expression error. You wouldn't want SQL to feel left out, would you?
The trick is to ensure that every column in your ORDER BY is also present in your SELECT DISTINCT clause. Here's the correct way to use ORDER BY:
Here, order_date is aggregated, so it has a unique value per group that gives ORDER BY the green light.
Subqueries: Your SQL lifesavers
When dealing with complex queries using DISTINCT and ORDER BY, SQL's subqueries come to the rescue like superheroes. Structure your query so the subquery handles the DISTINCT operation, and the outer query applies the ORDER BY.
This makes SQL happy by sorting the subquery's DISTINCT column1, which is then ordered by the outer query.
Best practices with DISTINCT and ORDER BY
Here are ninja tricks to avoid pitfalls and ensure efficient SQL performance when working with DISTINCT and ORDER BY:
Aggregate Functions: Harness the power of aggregate functions likeMAX(),MIN(), etc., for columns not part of theSELECT DISTINCT.Similar Column Clause: Ensure theSELECT DISTINCTandORDER BYclauses share the same columns. No confusion, no errors.Subquery Superpower: Use subqueries to separateDISTINCT, thus achieving a cleaner and error-free code structure.
The story of a DISTINCT photography contest
Picturing a photography competition where each contestant (👤) submits a unique photo:
Ah, the DISTINCT life:
The Error: But when contestants' names are attached, "not a SELECTed expression" error occurs:
Think of it as SQL ensuring that each distinct photo is appropriately paired with its contestant!
Useful references
- SQL SELECT DISTINCT Statement — Master the
DISTINCTkeyword with SQL basics. - SELECT — Oracle's official word on the
DISTINCT clause. - SQL DISTINCT | Intermediate SQL - Mode — Gain deeper understanding with
SQL DISTINCT examples. - SQL | GROUP BY - GeeksforGeeks — Learn how
GROUP BYandDISTINCTplay differently. - Handling SQL DISTINCT Correctly in Complex Queries — Hone your skills with complex
DISTINCT queries.
Was this article helpful?