SQL Best Practices: 12 Rules for Clean, Correct Queries

12 SQL best practices for cleaner, safer queries: explicit columns, JOIN habits, NULL traps, CTEs and more. Each rule has an example, then a free drill.

customers first_name last_name city result first_name · city
SELECT chooses which columns appear in the result.

The short version

These rules apply in PostgreSQL, MySQL, SQL Server and SQLite. The examples run on the same four-table shop used in every exercise here (customers, orders, order_items, products), and every result quoted below comes from that data.

  1. Name the columns you need
  2. Alias tables and qualify columns
  3. Write JOINs with an explicit ON
  4. WHERE filters rows, HAVING filters groups
  5. Know your row grain before you count
  6. COUNT(*) counts rows, COUNT(column) skips NULLs
  7. Test NULL with IS NULL
  8. Use NOT EXISTS or LEFT JOIN … IS NULL for “has none”
  9. Name the steps with CTEs
  10. ORDER BY whenever order matters
  11. Format for the next reader
  12. Build in small steps and check the numbers

1. Name the columns you need

SELECT * is fine for a first look at a table. Anywhere else, list the columns. The result is easier to read, it does not change shape when someone adds a column, and the next person can see what you actually wanted.

-- Quick look only
SELECT * FROM customers;
-- Better: say what you need
SELECT first_name, city
FROM customers
ORDER BY first_name;

2. Alias tables and qualify columns

Once a query has a JOIN, give each table a short alias that still means something (o for orders, c for customers, not a and b) and put the alias in front of every column. It removes ambiguity and makes a long query readable at a glance.

SELECT c.first_name, o.order_id, o.status
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
WHERE o.status = 'paid'
ORDER BY o.order_id;

Give computed columns a name too. SUM(oi.qty * p.price) AS revenue beats an unnamed column called SUM(oi.qty * p.price).

3. Write JOINs with an explicit ON

The join condition is the whole point of a JOIN. Leave it out, or use the old comma style and forget the WHERE, and every row meets every other row. With 10 customers and 14 orders that is 140 rows instead of 14.

-- 140 rows: nothing says which order belongs to which customer
SELECT COUNT(*) FROM customers, orders;
-- 14 rows: each order matched to its customer
SELECT COUNT(*)
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id;

4. WHERE filters rows, HAVING filters groups

Filter individual rows in WHERE, before grouping. Filter on an aggregate like COUNT(*) in HAVING, after grouping. Putting row filters in WHERE also means fewer rows to group.

SELECT city, COUNT(*) AS customers
FROM customers
WHERE country = 'USA'
GROUP BY city
HAVING COUNT(*) >= 2
ORDER BY customers DESC, city;

On the practice shop this returns Austin, Chicago and Denver with two customers each. More on the difference in HAVING vs WHERE. With a LEFT JOIN there is one more trap: a WHERE condition on the right-hand table silently turns it into an inner join (see LEFT JOIN and WHERE).

5. Know your row grain before you count

Before you count or sum, say it out loud: “my result has one row per ___.” Joining orders to order_items gives one row per order line, not per order, so a plain COUNT(*) overcounts.

-- 25: that is order lines, not orders
SELECT COUNT(*)
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id;
-- 14: the real number of orders
SELECT COUNT(DISTINCT o.order_id)
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id;

This is a very common silent bug in analytics queries, because nothing errors out. Read more in why JOINs multiply rows.

6. COUNT(*) counts rows, COUNT(column) skips NULLs

COUNT(*) counts rows. COUNT(column) counts rows where that column is not NULL. They return the same number only when the column has no NULLs. Pick the one that matches the question, and read COUNT(*) vs COUNT(column) if the difference is new to you.

7. Test NULL with IS NULL

NULL means “unknown”, and nothing equals unknown, not even another NULL. So = NULL never matches a row.

-- Never matches, even when discount is NULL
WHERE discount = NULL

-- Correct
WHERE discount IS NULL

(The practice shop has no nullable columns, so this one is shown on its own. The rule is the same everywhere. See NULL vs IS NULL.)

8. Use NOT EXISTS or LEFT JOIN … IS NULL for “has none”

To find rows with no match, such as customers with no paid order, avoid NOT IN. If the list it checks against contains a single NULL, NOT IN returns no rows at all. Both of these are safe:

SELECT c.first_name
FROM customers AS c
LEFT JOIN orders AS o
  ON o.customer_id = c.customer_id AND o.status = 'paid'
WHERE o.order_id IS NULL
ORDER BY c.first_name;
SELECT c.first_name
FROM customers AS c
WHERE NOT EXISTS (
  SELECT 1 FROM orders AS o
  WHERE o.customer_id = c.customer_id AND o.status = 'paid'
)
ORDER BY c.first_name;

Both return Noah, whose only order was cancelled. Note that the status condition sits in the ON clause of the LEFT JOIN, not in WHERE. Full walkthrough: anti-joins and NOT IN.

9. Name the steps with CTEs

When a query needs two or three logical steps, a CTE (WITH) lets you name each one. A reader sees “paid orders, then count per customer” instead of a nested puzzle.

WITH paid_orders AS (
  SELECT order_id, customer_id
  FROM orders
  WHERE status = 'paid'
)
SELECT c.first_name, COUNT(*) AS paid_orders
FROM paid_orders AS po
JOIN customers AS c ON c.customer_id = po.customer_id
GROUP BY c.first_name
ORDER BY paid_orders DESC, c.first_name;

Pick CTE names that describe the rows inside, not the step number. See CTEs explained.

10. ORDER BY whenever order matters

Without ORDER BY, SQL does not promise any order. A result can look sorted today and come back shuffled after a data change. Always sort when order matters, and always pair LIMIT with an ORDER BY, or “top 3” means “any 3”.

SELECT name, price
FROM products
ORDER BY price DESC, name
LIMIT 3;

The second sort key (name) breaks ties so the answer is the same every time.

11. Format for the next reader

You will read this query again in three months, and so will a colleague. One clause per line, indented joins, aligned conditions, and a short comment for the why, not the what.

-- Paid orders only: pending and cancelled orders are not revenue
SELECT
  c.city,
  COUNT(DISTINCT o.order_id) AS paid_orders,
  SUM(oi.qty * p.price)      AS revenue
FROM orders      AS o
JOIN customers   AS c  ON c.customer_id = o.customer_id
JOIN order_items AS oi ON oi.order_id   = o.order_id
JOIN products    AS p  ON p.product_id  = oi.product_id
WHERE o.status = 'paid'
GROUP BY c.city
ORDER BY revenue DESC
LIMIT 3;

On the practice shop this gives Austin first (3 paid orders, 81.80), then Chicago (2, 50.60) and Denver (1, 27.50). Whether keywords are upper or lower case matters less than using one style consistently.

12. Build in small steps and check the numbers

Do not write the whole query and hope. Start with FROM and one JOIN, look at a few rows, then add the filter, then the grouping. After each step ask whether the row count makes sense. A quick independent check, like SELECT COUNT(*) FROM orders returning 14, tells you whether the later number is believable.

That habit, more than any single rule above, is what separates a query that runs from a query you can trust.

FAQ

What are SQL best practices?

Habits that make a query easier to read, harder to get wrong, and safe to change later: name the columns you need, join with an explicit ON, know what one row of your result means, handle NULL on purpose, and format the query for the next reader.

Is SELECT * bad practice?

It is fine for a quick look at a table. In saved queries, views and application code, list the columns you need so the result stays stable when the table gains new columns and so the intent is obvious.

Should SQL keywords be uppercase?

It is a convention, not a rule. Many teams write keywords in uppercase so the structure stands out. What matters is that one team, one codebase, uses one style.

How do I practice SQL best practices?

Write the same small query two ways, once carelessly and once following the rule, and compare the results. Short exercises on one dataset make the difference visible, which is why the drills here all use the same four tables.

Try it yourself

The fastest way to lock this in is a short drill on the same Northstar Market tables.

Practice writing clean queries

Related guides