sql
How to Select and SubQuery in SQL Syntax
SQL has a small number of statements that combine to handle almost any data question. Here's a quick reference for the patterns I use most.
10 Apr 2024
SQL has a small number of statements that combine to handle almost any data question. Here's a quick reference for the patterns I use most.
SELECT everything
SELECT * FROM Customers
Returns all rows and columns. Fine for exploring. Never use SELECT * in production queries -- always name the columns you need.
Filtering with WHERE
SELECT name, city
FROM Customers
WHERE country = 'Germany'
WHERE filters rows before they're returned. Any column, any comparison operator.
Sorting with ORDER BY
SELECT name, city
FROM Customers
ORDER BY name ASC
ASC for ascending (A-Z, 0-9). DESC for descending. You can sort by multiple columns.
Grouping with GROUP BY
SELECT country, COUNT(*) AS customer_count
FROM Customers
GROUP BY country
Collapses rows into groups. Aggregate functions (COUNT, SUM, AVG) compute values per group.
Filtering groups with HAVING
SELECT country, COUNT(*) AS customer_count
FROM Customers
GROUP BY country
HAVING COUNT(*) > 5
HAVING filters after grouping. WHERE filters before. Use HAVING when you need to filter on aggregate results.
Subqueries
SELECT name
FROM Customers
WHERE country IN (
SELECT country
FROM Orders
GROUP BY country
HAVING SUM(amount) > 10000
)
A SELECT inside another SELECT. The inner query finds countries with high-value orders. The outer query returns customers from those countries.
The mental model
Every SQL query follows the same execution flow:
FROM-- which tableWHERE-- filter rowsGROUP BY-- create groupsHAVING-- filter groupsSELECT-- choose columnsORDER BY-- sort resultsLIMIT-- cap the output
Memorize this order. It explains why you can't use a column alias from SELECT in your WHERE clause -- WHERE runs first.