SQL basics for a data analyst come down to 4 groups of statements: SELECT to choose columns, WHERE to filter rows, GROUP BY with aggregate functions (SUM, COUNT, AVG) to calculate per group, and JOIN to combine tables. Master these 4 and you can answer most everyday questions such as "revenue this month by store", "which customers buy the most" or "which city is underperforming". This lesson goes through each statement on a small data set from a retail chain, with results worked out by hand so you can check yourself, and points out the mistakes that make the numbers wrong even though the query still runs.
By the end of this lesson, you will be able to:
- Write
SELECTqueries that pick the right columns, give them readable names, sort them and limit the number of rows. - Filter data with
WHEREusing conditions on numbers, dates, strings,IN,BETWEEN, and handle emptyNULLvalues. - Calculate totals, counts and averages per group with
GROUP BY, and filter groups withHAVING. - Combine two tables with
INNER JOINandLEFT JOIN, and know when rows get lost or duplicated. - Reconcile query results against a control total to make sure the numbers are right before sending a report.
Learning data analysis? SQL is step 3 of the roadmap, after analytical thinking and basic statistics and advanced Excel and Google Sheets. See the 8-step data analyst roadmap to learn in the right order.
What SQL is and why a data analyst needs it
SQL (Structured Query Language) is the language for asking questions of data in relational databases such as PostgreSQL, MySQL, SQL Server, SQLite or the BigQuery data warehouse. A company's sales, order and customer data usually lives on servers (Figure 1), not in a ready-made Excel file. A data analyst uses SQL to pull exactly the data needed and pre-calculate totals by group, then moves it into Excel, Python or Power BI. If you are not yet sure what a data analyst does day to day, start with the lesson what is a data analyst.
Photo: BalticServers.com / Wikimedia Commons, CC BY-SA 3.0
Tables, rows, columns: like Excel but stricter
A database table looks like an Excel sheet (Figure 2): each row is a record (one order) and each column is an attribute (date, store, amount). Unlike Excel, each column has a fixed data type (number, text, date), and there is usually a primary key column with no duplicates, such as the order ID. Tables link to each other through key columns: the orders table has a store ID column that points to the stores table.
Photo: MikeRun / Wikimedia Commons, CC BY-SA 4.0
Queries only read, they do not damage data
A SELECT statement only reads data and changes nothing in the table. Data analysts almost only use SELECT; write statements such as UPDATE, DELETE and DROP are the job of data engineers or database administrators.
Data safety note: Ask for read-only access when doing analysis. Do not runUPDATE,DELETEorDROPon a live database unless it is your assigned task and a backup exists. Do not download customers' personal data (phone numbers, addresses, ID card numbers) to a personal device or send it over chat; follow the personal data protection rules in force in Vietnam and your company's policies. A very heavy query on a server that is taking live sales can slow the system down: ask whether to run it on a reporting replica or at off-peak hours.
The sample data set: a retail chain with 4 branches
The whole lesson uses two small tables from a convenience-store chain. Every time a cashier scans items and prints a receipt at the checkout (Figure 3), the system writes one row into the don_hang (orders) table. The data is small so you can check it by hand; real data has millions of rows but the statements are exactly the same. The table and column names are kept as they would appear in a Vietnamese company's database: don_hang = orders, cua_hang = stores, ma_don = order ID, ngay = date, ma_ch = store ID, ma_kh = customer ID, tong_tien = order total.
Photo: Nielsoncaetanosalmeron / Wikimedia Commons, CC BY 4.0
The don_hang table (8 orders, in thousands of VND)
| ma_don | ngay | ma_ch | ma_kh | tong_tien |
|---|---|---|---|---|
| 1001 | 2026-10-01 | CH01 | KH01 | 250 |
| 1002 | 2026-10-01 | CH02 | KH02 | 180 |
| 1003 | 2026-10-02 | CH01 | KH03 | 420 |
| 1004 | 2026-10-02 | CH03 | KH01 | 90 |
| 1005 | 2026-10-03 | CH02 | KH04 | 310 |
| 1006 | 2026-10-03 | CH01 | KH02 | 150 |
| 1007 | 2026-10-04 | CH03 | KH05 | 260 |
| 1008 | 2026-10-04 | CH04 | KH03 | 340 |
Control total: 250 + 180 + 420 + 90 + 310 + 150 + 260 + 340 = 2,000 thousand VND, i.e. 2 million VND (about US$77), across 8 orders. Write these two numbers down; every aggregate query that follows must add back up to exactly 2,000 and 8.
The cua_hang table (5 branches)
| ma_ch | ten_ch (branch) | thanh_pho (city) |
|---|---|---|
| CH01 | District 1 | Ho Chi Minh City |
| CH02 | Thu Duc | Ho Chi Minh City |
| CH03 | Cau Giay | Hanoi |
| CH04 | Long Bien | Hanoi |
| CH05 | Hai Chau | Da Nang |
Notice that CH05 has just opened and has no orders in these 4 days. That small detail will matter when we get to JOIN.
SELECT: choose columns, name them, sort them
SELECT says "which columns", FROM says "from which table". This is the skeleton of every query.
Choosing columns and using aliases
SELECT ma_don, ngay, tong_tien AS doanh_thu
FROM don_hang;
The result is 8 rows and 3 columns, with tong_tien displayed as doanh_thu (revenue) thanks to AS. SELECT * fetches every column, which is handy for a quick look but best avoided in report queries, because real tables can have dozens of columns, making the query slow and hard to read.
Sorting and limiting rows
SELECT ma_don, tong_tien
FROM don_hang
ORDER BY tong_tien DESC
LIMIT 3;
Result: 1003 (420), 1008 (340), 1005 (310). DESC means descending; the default is ASC, ascending. LIMIT works in PostgreSQL, MySQL, SQLite and BigQuery; SQL Server uses SELECT TOP 3. Each database system has small differences like this, known as SQL "dialects".
Calculated columns
SELECT ma_don, tong_tien, tong_tien * 0.08 AS thue_uoc_tinh
FROM don_hang;
You can add, subtract, multiply and divide directly in SELECT. The example only illustrates multiplication; a real tax rate must come from the regulations and accounting data, not be made up.
WHERE: filter exactly the rows you need
WHERE keeps the rows that meet a condition and runs before any aggregation. It is where mistakes happen most, because the query still runs but filters the wrong rows.
Number and date conditions
SELECT ma_don, tong_tien
FROM don_hang
WHERE tong_tien >= 200;
The result is 5 orders: 1001 (250), 1003 (420), 1005 (310), 1007 (260), 1008 (340), totalling 250 + 420 + 310 + 260 + 340 = 1,580. Filtering by date:
SELECT ma_don, ngay, tong_tien
FROM don_hang
WHERE ngay BETWEEN '2026-10-01' AND '2026-10-02';
The result is 4 orders, 1001 to 1004, totalling 250 + 180 + 420 + 90 = 940. BETWEEN includes both ends. If the date column also stores hours and minutes (a timestamp), BETWEEN '2026-10-01' AND '2026-10-02' will miss orders after midnight on the 2nd; it is safer to write ngay >= '2026-10-01' AND ngay < '2026-10-03'.
AND, OR, IN and brackets
SELECT ma_don, ma_ch, tong_tien
FROM don_hang
WHERE ma_ch IN ('CH01', 'CH02')
AND tong_tien >= 200;
Result: 1001, 1003, 1005, totalling 250 + 420 + 310 = 980. Strings go in single quotes. When you mix AND and OR, always use brackets: WHERE (ma_ch = 'CH01' OR ma_ch = 'CH02') AND tong_tien >= 200. Without brackets, AND is evaluated first and you also get CH01's small orders back.
NULL: an empty value equals nothing
A cell with no data holds the value NULL. Writing WHERE ma_kh = NULL always returns 0 rows; you must write WHERE ma_kh IS NULL or IS NOT NULL. Walk-in customers' orders often have an empty ma_kh, so when counting customers you need to decide clearly whether to include this group.
GROUP BY: totals per group
Business questions are almost always "by something": by store, by day, by product. GROUP BY collects rows with the same value into a group, and the aggregate function calculates over each group.
Five common aggregate functions
| Function | Meaning | Result on the whole don_hang table |
|---|---|---|
| COUNT(*) | Count rows | 8 |
| COUNT(DISTINCT ma_kh) | Count distinct values | 5 customers |
| SUM(tong_tien) | Total | 2,000 |
| AVG(tong_tien) | Average | 250 |
| MIN / MAX(tong_tien) | Smallest / largest | 90 / 420 |
Check: 2,000 ÷ 8 = 250, matching AVG. The five customers are KH01 to KH05, of whom KH01, KH02 and KH03 bought twice.
Revenue by store
SELECT ma_ch,
COUNT(*) AS so_don,
SUM(tong_tien) AS doanh_thu
FROM don_hang
GROUP BY ma_ch
ORDER BY doanh_thu DESC;
| ma_ch | so_don (orders) | doanh_thu (revenue) | Working |
|---|---|---|---|
| CH01 | 3 | 820 | 250 + 420 + 150 |
| CH02 | 2 | 490 | 180 + 310 |
| CH03 | 2 | 350 | 90 + 260 |
| CH04 | 1 | 340 | 340 |
Control total: 3 + 2 + 2 + 1 = 8 orders; 820 + 490 + 350 + 340 = 2,000. It matches the source table, so the query is right. Rule: every column in SELECT that is not inside an aggregate function must appear in GROUP BY, otherwise most database systems will raise an error.
HAVING: filter after aggregating
SELECT ma_ch, SUM(tong_tien) AS doanh_thu
FROM don_hang
GROUP BY ma_ch
HAVING SUM(tong_tien) >= 400;
Result: CH01 (820) and CH02 (490). WHERE filters individual rows before grouping; HAVING filters groups after the totals are calculated. For "stores with revenue of 400 or more" you must use HAVING, because when WHERE runs, the per-store total does not exist yet.
JOIN: combining the orders table with the stores table
The don_hang table only holds the store ID; to report by city you must join it to the cua_hang table through the shared ma_ch column.
INNER JOIN: keep only rows that match in both tables
SELECT c.thanh_pho,
COUNT(*) AS so_don,
SUM(d.tong_tien) AS doanh_thu
FROM don_hang d
JOIN cua_hang c ON d.ma_ch = c.ma_ch
GROUP BY c.thanh_pho;
Result: Ho Chi Minh City 5 orders, 820 + 490 = 1,310; Hanoi 3 orders, 350 + 340 = 690. Total 1,310 + 690 = 2,000 and 5 + 3 = 8, which matches. d and c are table aliases that keep the query short and avoid confusion between columns with the same name. Average per order: Ho Chi Minh City 1,310 ÷ 5 = 262, Hanoi 690 ÷ 3 = 230.
LEFT JOIN: keep every row from the left table
SELECT c.ten_ch,
COUNT(d.ma_don) AS so_don,
COALESCE(SUM(d.tong_tien), 0) AS doanh_thu
FROM cua_hang c
LEFT JOIN don_hang d ON d.ma_ch = c.ma_ch
GROUP BY c.ten_ch;
The result has 5 rows, including Hai Chau with 0 orders and 0 revenue. With INNER JOIN, Hai Chau disappears from the report and management will never know this branch has not sold anything. Note the use of COUNT(d.ma_don) rather than COUNT(*): COUNT(*) counts the empty row too and would report 1 order for Hai Chau. COALESCE turns NULL into 0 to make it easier to read.
Comparing the types of JOIN
| Type | Keeps | Use when |
|---|---|---|
| INNER JOIN | Only rows that match in both tables | You only care about what happened: revenue by city |
| LEFT JOIN | Every row in the left table; NULL where the right table has no match | You want to see branches, products or customers with no transactions too |
| RIGHT JOIN | The reverse of LEFT JOIN | Rarely used; swap the table order and use LEFT JOIN for readability |
| FULL OUTER JOIN | Every row from both tables | Reconciling two data sources, finding rows that exist on only one side |
Execution order and a process for writing queries
You write SELECT first, but the database runs things in a different order: FROM and JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Understanding this order explains why you cannot use a SELECT column alias inside WHERE, and why filtering on totals needs HAVING.
Write the question on paper before typing
Before opening the SQL editor, write the business question as one clear sentence (Figure 4): "Revenue and number of orders by city, from 1 to 4 October 2026, paid orders only". From that sentence, break out: the unit of each result row (city), the metrics (revenue, order count), the filters (date, status) and the tables to join.
Photo: Shixart1985 / Wikimedia Commons, CC BY 2.0
A 5-step process
- Preview the data:
SELECT * FROM don_hang LIMIT 10;to learn the column names, data types and currency unit. - Calculate the control total of the source table:
SELECT COUNT(*), SUM(tong_tien) FROM don_hang; - Build it piece by piece:
FROM→JOIN→WHERE, running it and counting rows after each step. - Add
GROUP BYand the aggregate functions, and compare the sum of the groups with the control total. - Format it, give clear aliases, and save the query with a comment stating the question and the run date.
Common mistakes that give wrong numbers while the query still runs
A JOIN that doubles revenue
Sign: total revenue after the join is larger than the total of the source table. Cause: joining don_hang to an order-lines table (several product lines per order) and then running SUM(tong_tien), so each order total is added once per product line. Fix: aggregate at the right level of detail, for example summing line amounts in the order-lines table, or aggregate each table separately before joining.
Using WHERE instead of HAVING, or the other way round
Sign: an error such as "aggregate functions are not allowed in WHERE", or a wrong filter result. Cause: confusing when the filtering happens. Fix: put conditions on individual rows in WHERE and conditions on group totals in HAVING.
Comparing with NULL using an equals sign
Sign: the count of walk-in customers comes out as 0 although you know there are some. Cause: writing = NULL. Fix: use IS NULL; when averaging, remember that AVG skips NULL rows.
A date filter that misses the end of the day
Sign: revenue on the last day of the period is unusually low. Cause: a timestamp column filtered with BETWEEN two dates. Fix: use >= the first day and < the day after the last day, and check the time zone stored in the data.
Frequently asked questions
How long does it take to learn SQL basics for data analysis?
If you are already comfortable with Excel, 1–2 hours a day for about 3–4 weeks is enough to write SELECT, WHERE, GROUP BY and JOIN fluently. Add a few more weeks for subqueries, CTEs (WITH) and window functions such as ROW_NUMBER.
Should I learn MySQL, PostgreSQL or SQL Server?
The basics are the same in every database system; the differences are mainly in date functions and LIMIT/TOP. Beginners can start with free SQLite or PostgreSQL, then learn the dialect their company uses.
If I know Excel PivotTables, do I still need SQL?
Yes. A PivotTable does a job similar to GROUP BY on data already in the file, but company data sits in databases with millions of rows; SQL fetches and aggregates it at the source, and Excel is then used for presentation.
What does an SQL test in a data analyst interview usually cover?
Usually filtering, grouping and aggregating, joining tables, finding the top N per group, calculating ratios and comparing periods. Mastering this lesson gives you the foundation; test practice comes in the last step of the roadmap.
Practice exercises and self-assessment
Create the two tables above in SQLite or PostgreSQL (typing in the 13 rows of data by hand), then write a query for each question:
- List the orders of customers KH01 and KH03, sorted by date ascending.
- Revenue by day, with the number of orders each day.
- Revenue by city, counting only orders of 150 thousand VND or more.
- A list of every store with the number of distinct customers who bought there, including stores with no orders.
Self-assessment criteria
- Pass: question 2 adds up to exactly 2,000 thousand VND and 8 orders (1 October: 430, 2 October: 510, 3 October: 460, 4 October: 600).
- Pass: question 3 gives Ho Chi Minh City 1,310 and Hanoi 600, because CH03's 90-thousand order is excluded.
- Pass: question 4 lists all 5 stores, with Hai Chau showing 0 customers.
- Not yet: you use
INNER JOINand lose Hai Chau, use= NULL, or do not reconcile the totals with the source table.
Once your SQL is solid, the next step of the roadmap is Python pandas for cleaning and analysis: you load query results into pandas to handle messy data, do more complex calculations and prepare for dashboards.
Keep learning data analysis: after SQL come Python pandas, Power BI or Looker Studio dashboards, data storytelling and a sales analysis project for a retail chain. See the 8-step data analyst roadmap.






