How do you retrieve the top N records from a table?

Instruction: Using PostgreSQL, return at most three sales with the highest amount, breaking equal amounts by smaller sale_id.

Context:

The table is sales(sale_id INTEGER PRIMARY KEY, amount NUMERIC NOT NULL). Its rows are (1,100), (2,120), (3,120), (4,80). Return both columns in the requested order. Return exactly three rows when at least three exist; do not include additional ties.

Updated

Official Answer

For PostgreSQL, sort by descending amount, then by the unique ID to make ties deterministic:

SELECT sale_id, amount
FROM sales
ORDER BY amount DESC, sale_id ASC
LIMIT 3;

With the supplied data, the result is (2, 120), (3, 120), (1, 100) in that order. LIMIT 3 means at most three rows; it returns fewer if fewer exist. The ID tie-breaker chooses a stable order without returning every row tied at the cutoff.

If the requirement instead means all sales in the top three distinct amount levels, that is a different ranking problem. Clarify the tie policy before choosing LIMIT, FETCH ... WITH TIES or a ranking function. Without ORDER BY, there is no defined top result.

Source

PostgreSQL: LIMIT and OFFSET.

Related Questions