Write a query to list the top 3 most frequent values in a column.

Instruction: In PostgreSQL sales(product_name), treat each row as one occurrence. Return up to three non-NULL product names by descending frequency, breaking frequency ties alphabetically. Explain how this differs from returning all tied products or summing units sold.

Context: This question tests the candidate's ability to use aggregate functions, GROUP BY, and ORDER BY clauses to analyze data and extract valuable insights.

Updated

Official answer

If each sales row represents one occurrence and NULL product names should be excluded, PostgreSQL can return up to three names deterministically:

SELECT product_name, COUNT(*) AS frequency
FROM sales
WHERE product_name IS NOT NULL
GROUP BY product_name
ORDER BY frequency DESC, product_name ASC
LIMIT 3;

The secondary alphabetical order resolves equal frequencies under the database collation. This returns exactly three groups when at least three exist, rather than all groups tied at the third frequency. Fewer distinct non-NULL names produce fewer rows.

For A appearing 3 times, B 2 times, C 2 times and D once, results are (A,3), (B,2), (C,2). If rows contain a quantity field, row frequency is not necessarily units sold; use SUM(quantity) for that different metric. To include all frequency ties, rank aggregated counts under a separately stated tie policy. Duplicate events should be addressed at their source, not silently counted as genuine sales.

Related Questions