Explain the purpose of the 'ORDER BY' clause in SQL.

Instruction: Write a SQL query to retrieve records from a 'products' table, ordered by the 'price' column in ascending order.

Context: This question evaluates the candidate's understanding of the ORDER BY clause, used to sort the results of a query in ascending or descending order.

Updated

Official answer

ORDER BY defines the order of the returned result. For PostgreSQL products(product_id integer PRIMARY KEY, price numeric):

SELECT product_id, price
FROM products
ORDER BY price ASC NULLS LAST, product_id ASC;

Prices increase from lowest to highest; missing prices appear last. Product ID gives a deterministic order among equal prices. Without a complete tie-breaker, tied rows may appear in any order. Without an outer ORDER BY, do not assume insertion order or an index defines the result order.

ASC is the default direction, but spelling it out can clarify intent. NULL ordering and supported syntax vary by engine. Sorting can require work or use an appropriate index; choose indexes for the measured workload. LIMIT without deterministic ordering is unsuitable for a stable top-N or paginated result.

Related Questions