0
0
PostgreSQLquery~5 mins

DISTINCT ON for unique per group in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does DISTINCT ON do in PostgreSQL?

DISTINCT ON returns the first row of each unique group based on specified columns.

It helps to get one unique row per group.

Click to reveal answer
beginner
How do you specify which row to keep when using DISTINCT ON?

You use ORDER BY to control which row appears first in each group.

The first row in the order is kept.

Click to reveal answer
intermediate
Write a simple query to get one unique row per category from a products table using DISTINCT ON.
SELECT DISTINCT ON (category) *
FROM products
ORDER BY category, price DESC;

This returns the most expensive product per category.

Click to reveal answer
intermediate
Why is ORDER BY important with DISTINCT ON?

Because DISTINCT ON keeps the first row of each group, ORDER BY decides which row is first.

Without proper ordering, you might get unexpected rows.

Click to reveal answer
advanced
Can DISTINCT ON be used without ORDER BY in PostgreSQL?

No, DISTINCT ON requires ORDER BY to define which row to keep.

PostgreSQL will raise an error if ORDER BY does not include the DISTINCT ON columns at the start.

Click to reveal answer
What does DISTINCT ON (column) return in PostgreSQL?
AOnly rows with duplicate values in the column
BAll rows with unique values in the column
CThe first row for each unique value in the column
DAll rows sorted by the column
Which clause must be used with DISTINCT ON to control which row is returned?
AGROUP BY
BORDER BY
CWHERE
DHAVING
What happens if ORDER BY does not include the DISTINCT ON columns?
APostgreSQL raises an error
BQuery runs normally
CDuplicates are removed anyway
DRows are randomly returned
How can you get the most recent order per customer using DISTINCT ON?
AUse <code>ORDER BY order_date DESC</code> only
BUse <code>DISTINCT ON (order_date)</code> and order by <code>order_date DESC</code>
CUse <code>GROUP BY customer_id</code> only
DUse <code>DISTINCT ON (customer_id)</code> and order by <code>customer_id, order_date DESC</code>
Which of these is a correct use of DISTINCT ON?
ASELECT DISTINCT ON (category) * FROM products ORDER BY category, price DESC;
BSELECT DISTINCT ON (category) * FROM products;
CSELECT DISTINCT ON (category) * FROM products ORDER BY price DESC;
DSELECT DISTINCT ON * FROM products ORDER BY category;
Explain how DISTINCT ON works in PostgreSQL and why ORDER BY is important.
Think about picking one favorite item per group.
You got /4 concepts.
    Describe a real-life scenario where DISTINCT ON is useful and how you would write the query.
    Imagine you want one special record per group.
    You got /4 concepts.