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.
DISTINCT ON?You use ORDER BY to control which row appears first in each group.
The first row in the order is kept.
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.
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.
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.
DISTINCT ON (column) return in PostgreSQL?DISTINCT ON returns the first row for each unique value in the specified column(s).
DISTINCT ON to control which row is returned?ORDER BY controls which row is first and thus returned by DISTINCT ON.
ORDER BY does not include the DISTINCT ON columns?PostgreSQL requires ORDER BY to start with the DISTINCT ON columns; otherwise, it raises an error.
DISTINCT ON?Ordering by customer_id, order_date DESC ensures the latest order per customer is returned.
DISTINCT ON?DISTINCT ON columns must appear first in ORDER BY. Option A is correct.
DISTINCT ON works in PostgreSQL and why ORDER BY is important.DISTINCT ON is useful and how you would write the query.