5 Essential SQL Commands Every Analytics Engineer Should Know
SELECT, WHERE, GROUP BY, JOIN, and ORDER BY, each run on the same two tables, with the order a query is evaluated in and the NULL mistakes that change a number without raising an error.
On this page · 17 sections
- The five commands at a glance
- What SQL is, and the sample data
- 1. SELECT: choose the columns
- 2. WHERE: filter rows
- The NULL comparison that returns the wrong count
- 3. GROUP BY: summarize with aggregate functions
- 4. JOIN: combine tables
- 5. ORDER BY: sort the result
- The order a SELECT is evaluated in
- Beyond the five: CASE, CTEs, and window functions
- Common mistakes
- Frequently Asked Questions
- What are the basic SQL commands needed for analytics work?
- How do aggregate functions work in SQL?
- Which SQL data types are most important for data analysis?
- How do subqueries work in SQL?
- Primary sources and further reading
- Topic
- SQL for Analytics Engineers
- Category
- SQL
The five SQL commands to know first for analytics work are SELECT, WHERE, GROUP BY, JOIN, and ORDER BY. SELECT chooses the columns, WHERE filters rows, GROUP BY collapses rows into groups that aggregate functions such as COUNT and SUM summarize, JOIN combines tables, and ORDER BY sorts the result. Strictly, SELECT is the command and the other four are clauses of it, and the database evaluates them in a different order from the one you write them in. Each is shown below on one small dataset with real PostgreSQL 16 output.
The five commands at a glance
| Command | What it does | Position in the written query | Typical analytics use |
|---|---|---|---|
| SELECT | Lists the columns and expressions to return | First | Pick, rename, and compute columns |
| JOIN | Combines rows from two tables that satisfy a condition | Second, inside FROM | Attach customer attributes to orders |
| WHERE | Keeps only the rows for which a condition is true | Third | Completed orders in a date range |
| GROUP BY | Collapses rows that share a value into one row per group | Fourth, before HAVING | Revenue per customer, month, or status |
| ORDER BY | Sorts the result | Fifth, before LIMIT | Top customers by revenue |
What SQL is, and the sample data
SQL is the query language of relational databases, which store data in tables: named collections of rows in which every row has the same columns and each column has a data type. A query describes the result you want, and the database's planner decides how to produce it.
Paste this setup once into a PostgreSQL database to follow along:
create table customers (
customer_id integer primary key,
customer_name text not null,
country text
);
create table orders (
order_id integer primary key,
customer_id integer not null references customers (customer_id),
order_date date not null,
status text not null,
amount numeric(10, 2) not null
);
insert into customers values
(1, 'Acme Retail', 'US'),
(2, 'Borealis Labs', 'CA'),
(3, 'Cobalt Foods', 'US'),
(4, 'Dune Travel', null),
(5, 'Elm Studio', 'DE');
insert into orders values
(1001, 1, '2026-03-02', 'completed', 120.00),
(1002, 2, '2026-03-03', 'completed', 75.50),
(1003, 1, '2026-03-05', 'refunded', 40.00),
(1004, 3, '2026-03-09', 'completed', 310.00),
(1005, 4, '2026-03-12', 'completed', 59.99),
(1006, 2, '2026-03-15', 'completed', 220.00),
(1007, 1, '2026-03-20', 'completed', 89.00),
(1008, 3, '2026-03-24', 'pending', 145.00),
(1009, 4, '2026-04-01', 'completed', 18.50),
(1010, 1, '2026-04-03', 'completed', 260.00);
The columns use four data types: integer, text, date, and numeric(10, 2), an exact decimal that PostgreSQL recommends for money because floating-point types are inexact. A primary key is unique and not null, so it identifies each row. references declares a foreign key: every customer_id in orders must exist in customers.
NULL represents an unknown value. It is not zero and not an empty string. Two details matter later: Dune Travel's country is NULL, and Elm Studio has no orders. The SQL hub lists the site's other SQL guides.
1. SELECT: choose the columns
SELECT lists the columns to return, and FROM names the table they come from.
select
customer_name,
country
from customers;
customer_name | country
---------------+---------
Acme Retail | US
Borealis Labs | CA
Cobalt Foods | US
Dune Travel |
Elm Studio | DE
(5 rows)
psql, PostgreSQL's command-line client, prints NULL as an empty cell, as in Dune Travel's row. In the select list, * returns every column, as gives an output column a name (an alias), and select distinct removes duplicate rows. No row order was requested, so the rows may come back in any order.
2. WHERE: filter rows
WHERE keeps the rows for which its condition is true. This query returns the completed orders from March 2026 worth at least 100:
select
order_id,
order_date,
amount
from orders
where status = 'completed'
and order_date between '2026-03-01' and '2026-03-31'
and amount >= 100
order by order_id;
order_id | order_date | amount
----------+------------+--------
1001 | 2026-03-02 | 120.00
1004 | 2026-03-09 | 310.00
1006 | 2026-03-15 | 220.00
(3 rows)
Conditions are built from a few operators:
=,<>,<,>,<=, and>=compare two values.and,or, andnotcombine conditions.in ('refunded', 'pending')matches any value in a list.betweenincludes both endpoints.like '%Labs'matches a pattern:%is any sequence of characters,_exactly one.is nullandis not nulltest for NULL.
The NULL comparison that returns the wrong count
A comparison with NULL yields NULL, meaning unknown, and WHERE keeps only the rows whose condition is true. So this count of customers outside the US leaves out Dune Travel, and no error is raised:
select count(*) as non_us_customers
from customers
where country <> 'US';
non_us_customers
------------------
2
(1 row)
is distinct from works like <> but treats NULL as an ordinary value:
select count(*) as non_us_customers
from customers
where country is distinct from 'US';
non_us_customers
------------------
3
(1 row)
Which number is right depends on the question. where country = null fails the same way and matches no rows. Write is null.
3. GROUP BY: summarize with aggregate functions
GROUP BY puts the rows that share a value into one group, and an aggregate function (count, sum, avg, min, max) returns one value per group.
select
status,
count(*) as orders,
sum(amount) as revenue,
round(avg(amount), 2) as avg_order,
min(amount) as smallest,
max(amount) as largest
from orders
group by status
order by revenue desc;
status | orders | revenue | avg_order | smallest | largest
-----------+--------+---------+-----------+----------+---------
completed | 8 | 1152.99 | 144.12 | 18.50 | 310.00
pending | 1 | 145.00 | 145.00 | 145.00 | 145.00
refunded | 1 | 40.00 | 40.00 | 40.00 | 40.00
(3 rows)
A selected column must be in GROUP BY or inside an aggregate, unless GROUP BY contains its table's primary key. count(*) counts rows. count(column), sum, avg, min, and max skip NULL values.
To filter on an aggregate, use HAVING, which runs after grouping: adding having count(*) > 1 below the GROUP BY line leaves only the completed row. WHERE runs before the groups exist. See HAVING vs. WHERE.
4. JOIN: combine tables
A join matches rows from two tables on the condition after on. An inner join returns only the matching pairs. A left join also keeps every left-table row, with NULL in the right table's columns where nothing matched. This query counts each customer's orders two ways:
select
c.customer_name,
count(*) as count_star,
count(o.order_id) as count_order_id,
sum(o.amount) as revenue
from customers as c
left join orders as o
on o.customer_id = c.customer_id
group by c.customer_id, c.customer_name
order by c.customer_name;
customer_name | count_star | count_order_id | revenue
---------------+------------+----------------+---------
Acme Retail | 4 | 4 | 509.00
Borealis Labs | 2 | 2 | 295.50
Cobalt Foods | 2 | 2 | 455.00
Dune Travel | 2 | 2 | 78.49
Elm Studio | 1 | 0 |
(5 rows)
Elm Studio has no orders, yet count(*) reports 1. The left join produced one Elm Studio row with NULL in every orders column, and count(*) counts rows. count(o.order_id) skips NULLs and returns the correct 0. Revenue is NULL, not 0, because sum had no non-null values to add. coalesce(sum(o.amount), 0) shows zero. With inner join, Elm Studio would not appear at all.
Right, full, cross, and self joins are in SQL joins explained with visual diagrams.
5. ORDER BY: sort the result
ORDER BY sorts by one or more columns or expressions, ascending by default and descending with desc. Without it, row order is unspecified. This query ranks customers by completed revenue:
select
c.customer_name,
sum(o.amount) as revenue
from customers as c
left join orders as o
on o.customer_id = c.customer_id
and o.status = 'completed'
group by c.customer_id, c.customer_name
order by revenue desc;
customer_name | revenue
---------------+---------
Elm Studio |
Acme Retail | 469.00
Cobalt Foods | 310.00
Borealis Labs | 295.50
Dune Travel | 78.49
(5 rows)
Elm Studio comes first with no revenue. PostgreSQL sorts NULL as if it were larger than any other value, so NULLs lead a descending sort. order by revenue desc nulls last moves Elm Studio to the bottom, and adding limit 3 keeps the top three.
For indexes and query plans, see query optimization basics.
The order a SELECT is evaluated in
A query is written SELECT first, but PostgreSQL's reference page for SELECT describes its processing in this order:
| Step | Clause | What happens | Consequence |
|---|---|---|---|
| 1 | FROM and JOIN | Tables are read and joined | ON conditions apply before WHERE |
| 2 | WHERE | Rows that fail the condition are removed | No aggregates or aliases here |
| 3 | GROUP BY | Rows are grouped and aggregates computed | Aggregates see only rows that passed WHERE |
| 4 | HAVING | Groups that fail the condition are removed | Filter on aggregates here |
| 5 | SELECT | Output expressions are computed | Aliases start here. Window functions run after HAVING |
| 6 | DISTINCT | Duplicate rows are removed | Compares whole output rows |
| 7 | ORDER BY | Rows are sorted | Can use aliases |
| 8 | LIMIT | The first rows are kept | Predictable only after a sort |
WITH queries are computed before step 1, and UNION, INTERSECT, and EXCEPT apply between steps 6 and 7. This is the logical order, not the execution plan. It explains this error:
select
order_id,
date_trunc('month', order_date)::date as order_month
from orders
where order_month = '2026-04-01';
ERROR: column "order_month" does not exist
LINE 5: where order_month = '2026-04-01';
^
WHERE runs at step 2 and the alias is created at step 5, so repeat the expression in WHERE. PostgreSQL does accept an output column name in GROUP BY and ORDER BY.
Beyond the five: CASE, CTEs, and window functions
CASE is SQL's conditional expression. It returns the result of the first WHEN condition that is true, otherwise the ELSE value, or NULL when there is no ELSE. case when amount >= 200 then 'large' else 'small' end labels orders 1004, 1006, and 1010 as large.
A common table expression (CTE) is a subquery named with WITH: see the CTE tutorial for beginners. Window functions calculate across related rows without collapsing them: see SQL window functions explained with examples.
Common mistakes
- Comparing with NULL using
=or<>. Rows drop out and no error is raised. Useis nulloris distinct from. - Using
count(*)after a left join. It counts unmatched rows too. Count a right-table column. - Filtering the right-hand table of a left join in WHERE. Unmatched rows disappear, as in an inner join. Put the condition in ON, as the revenue query does with its status filter.
- Mixing AND and OR without parentheses. AND binds more tightly than OR. On the sample data,
status = 'refunded' or status = 'pending' and amount > 100matches two orders. With parentheses around the OR pair it matches one. - Putting an aggregate in WHERE. PostgreSQL answers
aggregate functions are not allowed in WHERE. Use HAVING.
To practice, try the graded practice exercises or query the larger tables on the datasets page.
Frequently Asked Questions
What are the basic SQL commands needed for analytics work?
SELECT, WHERE, GROUP BY, JOIN, and ORDER BY. SELECT with FROM retrieves columns, WHERE filters rows, GROUP BY with an aggregate function summarizes them, JOIN combines tables, and ORDER BY sorts the result. INSERT, UPDATE, and DELETE change data instead of reading it.
How do aggregate functions work in SQL?
An aggregate function computes one value from many rows: COUNT counts, SUM adds, AVG averages, and MIN and MAX return the smallest and largest value. With GROUP BY the result is one value per group, and without it one value for all the selected rows. In PostgreSQL they skip NULL inputs, except count(*), which counts rows.
Which SQL data types are most important for data analysis?
Whole numbers (integer), exact decimals (numeric), text, dates and timestamps, and boolean. NULL is not a type: a column of any type can hold it unless it is declared not null.
How do subqueries work in SQL?
A subquery is a SELECT in parentheses inside another query. A scalar subquery returns one row and one column and acts as a single value: where amount > (select avg(amount) from orders) keeps the four orders above the average of 133.80. A subquery in FROM acts as a table.
Primary sources and further reading
- SELECT. Processing order, the grouping rule, where aliases work.
- Table expressions. Join types, ON versus WHERE, WHERE and NULL.
- Comparison operators. NULL comparisons, BETWEEN, IS DISTINCT FROM.
- Aggregate functions and the aggregate tutorial. What aggregates ignore, WHERE versus HAVING.
- Sorting rows and LIMIT. Unspecified order, NULL ordering.
- Select lists, window functions, and operator precedence. Aliases, DISTINCT, window function timing.
- Pattern matching and conditional expressions. LIKE, CASE, COALESCE.
- Data types, numeric types, and constraints. Numeric for money, keys.
- Concepts and using EXPLAIN. Tables and the planner.
- WITH queries and value expressions. CTEs, scalar subqueries.
- psql. How NULL is displayed.
The SQL was run on PostgreSQL 16, and the output shown is what psql printed. The sources are pages of the PostgreSQL 16 documentation, read in November 2026.
- SQL
HAVING vs WHERE in SQL: Clause Differences with Examples
WHERE filters rows before grouping; HAVING filters groups after aggregation. Learn the key difference, when to use each clause, and how to combine them for faster SQL.
- SQL
Learn SQL: Introduction to SQL with a No‑Fluff 4‑Week Plan
A practitioner’s 4‑week plan to learn SQL for data analytics. Daily graded practice, concrete milestones, and realistic examples—no fluff, just queries.
- SQL
LAG and LEAD in SQL: Compare Each Row With the One Before or After
A practitioner’s guide to SQL LAG and LEAD for period-over-period analysis, churn flags, and sessionization—plus syntax, pitfalls, and performance tips.
Drill it in the exercise library.
Portfolio-ready builds on this topic.
- intermediate · open →
SQL Alien Invasion Challenge: Defend Earth
Crisis-response analytics: defend Earth with multi-table joins, aggregation, and CTEs.
- advanced · open →
SQL Mystery Challenge: The Case of the Vanishing Artifacts
Investigative SQL: follow the evidence across museum audit logs to unmask a thief.
