Preview article · Original demonstration content, not attributed to the founder.
SQL · 1 min readPreview

Better SQL starts with better questions

Before you write a query, get clear on what one row of your answer should represent.

A query is easier to write when you know the shape of the answer. Before choosing functions or joins, describe the result you need in everyday language.

Define the result first

Imagine an orders table. To compare regions, you might want one row per region with its total sales. The region becomes your grouping key and sales becomes your measure.

sql
SELECT region, SUM(sales) AS total_sales
FROM orders
GROUP BY region
ORDER BY total_sales DESC;
QuestionSQL concept
Which records matter?WHERE
What does one row represent?GROUP BY
Which result comes first?ORDER BY

Check your assumptions

Check whether sales values can be missing, whether orders contain duplicate rows and whether your date range matches the question. A query can run successfully and still answer the wrong question.

Back to all articles