When you first start learning SQL, it can feel like a lot. Different clauses, different rules, and quite a bit of syntax to remember. But in reality, most queries are built from just a small set of core commands. Once you get comfortable with these, SQL starts to feel easier to understand. In this post, I’ll go through the main ones you’ll use all the time:
SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY.
SELECT
SELECT is simply what you want to return.
At the most basic level, you’re just picking columns:
SELECT customer_id, sales
You can also create calculations:
SELECT customer_id, sales * 0.2 AS tax
Or aggregate values:
SELECT SUM(sales) AS total_sales
SELECT defines the columns that will appear in your output.
FROM
FROM tells SQL where the data is coming from.
FROM orders
Usually this is a table, but it could also be a view or a subquery. Without FROM, SQL doesn’t know what dataset you’re working with.
WHERE
WHERE is used to filter your data.
WHERE country = 'UK'
This just means you’re only keeping rows that match that condition.
You can add more conditions as well:
WHERE country = 'UK'
AND sales > 100
So now you’re only getting rows where both of those things are true. WHEREjust filters the rows.
GROUP BY
GROUP BY is where aggregation comes in.
It lets you group rows together and then apply aggregate functions like SUM(), COUNT(), or AVG().
SELECT customer_id, SUM(sales)
FROM orders
GROUP BY customer_id
Without GROUP BY, your aggregate runs over the whole table. With it, you get results per group.
HAVING
HAVING is basically WHERE, but for aggregated data.
SELECT customer_id, SUM(sales)
FROM orders
GROUP BY customer_id
HAVING SUM(sales) > 1000
The easiest way to remember it:
WHEREfilters rowsHAVINGfilters groups
ORDER BY
ORDER BY is just sorting your results.
ORDER BY sales DESC
You can sort ascending (ASC) or descending (DESC), and also by multiple columns:
ORDER BY country, sales DESC
This is usually the last step, just to make the output easier to read.
Putting It All Together
A full query might look like this:
SELECT customer_id, SUM(sales) AS total_sales
FROM orders
WHERE country = 'UK'
GROUP BY customer_id
HAVING SUM(sales) > 1000
ORDER BY total_sales DESC;
Although this looks more complicated, it’s still just those same six basic commands working together.
Final Thoughts
Most of what you’ll do in SQL comes back to these commands. Once you’re comfortable with them, everything else becomes a lot easier to follow.
In my next post, I’ll go into something that confused me quite a bit when we stated learning SQL this week, which is that SQL doesn’t actually run in the order you write it. Once you understand that, a lot of the common mistakes start to make sense.
