SQL from zero — tutorial with 25 exercises
Learn SQL step by step with one small table: SELECT, WHERE, ORDER BY, GROUP BY, JOINs and subqueries, with practice questions and answers.
Before you start
Definition: SQL (Structured Query Language) is the standard declarative language for defining, querying and changing data in a relational database.
How it works: You describe what you want, not how to get it; the database's query optimiser decides the fastest way. SQL has sub-languages: DDL (CREATE, ALTER, DROP — structure), DML (SELECT, INSERT, UPDATE, DELETE — data), DCL (GRANT, REVOKE — permissions) and TCL (COMMIT, ROLLBACK — transactions).
Example: SELECT name FROM customers WHERE city = 'Hyderabad'; asks for names of Hyderabad customers.
🧒 In simple words
SQL (say "sequel" or "S-Q-L") is how you ask a database questions. Almost every analyst, developer and tester job asks for it, and freshers' interviews love it because it is easy to test in 10 minutes.
You don't need to install anything to follow this page. Read the example, guess the answer, then check it. If you want to type the queries yourself, any free online SQL playground works (see Further reading at the end).
Tip: learn the order a query is written in — SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT. Interviewers ask this.
The table we will use
Definition: A table (relation) stores data about one kind of thing in rows (records/tuples) and columns (attributes). A primary key is a column (or set of columns) whose value uniquely identifies each row and can never be NULL. A foreign key is a column in one table that references the primary key of another table, enforcing that the linked row exists.
How it works: The database rejects a duplicate primary key, and rejects an orders.customer_id that doesn't exist in customers.id (referential integrity).
Example: customers.id = 1 is Asha; orders.customer_id = 1 links three orders to her.
🧒 In simple words
Imagine a small company table called employees:
| id | name | dept | city | salary | joined |
|---|---|---|---|---|---|
| 1 | Asha | Sales | Hyderabad | 42000 | 2023-06-01 |
| 2 | Ravi | IT | Bengaluru | 65000 | 2022-01-15 |
| 3 | Meena | IT | Chennai | 72000 | 2021-09-10 |
| 4 | Kiran | HR | Hyderabad | 38000 | 2024-02-20 |
| 5 | Farhan | Sales | Pune | 47000 | 2023-11-05 |
| 6 | Divya | IT | Bengaluru | 58000 | 2024-07-01 |
Each row is one employee. Each column is one fact about them. id is the primary key — a unique number for every row.
1. SELECT — read data
SELECT name, salary FROM employees;name | salary -------+------- Asha | 42000 Ravi | 65000 Meena | 72000 Kiran | 38000 Farhan | 47000 Divya | 58000
Shows two columns for every row. SELECT * shows all columns (fine for practice, avoid in real code).
Rename a column with AS
SELECT name AS employee, salary * 12 AS yearly_salary FROM employees;employee | yearly_salary ---------+-------------- Asha | 504000 Ravi | 780000 Meena | 864000 Kiran | 456000 Farhan | 564000 Divya | 696000
2. WHERE — filter rows
Definition: SELECT specifies which columns (or expressions) to return; WHERE is a predicate that keeps only the rows for which the condition is TRUE.
How it works: Conditions combine with AND / OR / NOT, and use operators like =, <>, >, BETWEEN, IN, LIKE and IS NULL. Rows where the condition is FALSE or UNKNOWN (NULL) are removed — which is why = NULL never matches.
Example: WHERE city = 'Pune' AND amount > 400 keeps only big Pune orders.
🧒 In simple words
SELECT name FROM employees WHERE city = 'Hyderabad';name ----- Asha Kiran
Result: Asha, Kiran. Text goes in single quotes; numbers don't.
| You want | Write |
|---|---|
| more than 50,000 | salary > 50000 |
| between two values | salary BETWEEN 40000 AND 60000 |
| one of a list | dept IN ('IT', 'HR') |
| names starting with K | name LIKE 'K%' |
| no value | manager IS NULL |
| two conditions | dept = 'IT' AND city = 'Bengaluru' |
3. ORDER BY and LIMIT — sort and keep the top rows
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3;name | salary ------+------- Meena | 72000 Ravi | 65000 Divya | 58000
Top 3 earners: Meena, Ravi, Divya. ASC (small → big) is the default.
4. Aggregates — one answer from many rows
Definition: Aggregate functions compute a single value from a set of rows: COUNT, SUM, AVG, MIN and MAX.
How it works: Without GROUP BY they summarise the whole result; with GROUP BY they produce one value per group. All except COUNT(*) ignore NULL values.
Example: SELECT AVG(amount) FROM orders → 491.43, the average order value.
🧒 In simple words
| Function | Meaning |
|---|---|
COUNT(*) | how many rows |
SUM(salary) | total |
AVG(salary) | average |
MIN / MAX | smallest / biggest |
SELECT COUNT(*) AS people, AVG(salary) AS avg_pay FROM employees;people | avg_pay -------+--------- 6 | 53666.67
5. GROUP BY and HAVING — totals per group
Definition: GROUP BY partitions rows into groups that share the same values in the listed columns, so aggregates are computed per group. HAVING filters those groups using a condition on aggregates.
How it works: Every column in SELECT must either appear in GROUP BY or be inside an aggregate. WHERE runs before grouping (filters rows); HAVING runs after (filters groups).
Example: Revenue per restaurant, keeping only restaurants above ₹1,000: GROUP BY restaurant HAVING SUM(amount) > 1000.
🧒 In simple words
SELECT dept, COUNT(*) AS people, AVG(salary) AS avg_pay
FROM employees
GROUP BY dept;dept | people | avg_pay ------+--------+-------- HR | 1 | 38000 IT | 3 | 65000 Sales | 2 | 44500
One row per department. To filter groups, use HAVING (WHERE filters rows before grouping):
SELECT dept, AVG(salary) AS avg_pay
FROM employees
GROUP BY dept
HAVING AVG(salary) > 50000;dept | avg_pay -----+-------- IT | 65000
Result: only IT.
Interview favourite: "What is the difference between WHERE and HAVING?" — WHERE filters rows before grouping, HAVING filters the groups after.
6. JOINs — combine two tables
Definition: A join combines rows from two or more tables based on a related column, producing a result set with columns from all of them.
How it works: INNER JOIN returns only matching pairs. LEFT (OUTER) JOIN returns all rows of the left table plus matches (NULLs where there's no match). RIGHT JOIN is the mirror. FULL OUTER JOIN returns all rows from both. CROSS JOIN returns every combination (Cartesian product). A self join joins a table to itself using aliases.
Example: Orders joined to customers on orders.customer_id = customers.id shows each order with the customer's name.
🧒 In simple words
A second table, departments:
| dept | floor | head |
|---|---|---|
| Sales | 1 | Nikhil |
| IT | 3 | Sara |
| Finance | 2 | Omar |
SELECT e.name, e.dept, d.head
FROM employees e
JOIN departments d ON e.dept = d.dept;name | dept | head -------+-------+------- Asha | Sales | Nikhil Ravi | IT | Sara Meena | IT | Sara Farhan | Sales | Nikhil Divya | IT | Sara (Kiran is missing — HR is not in the departments table)
| Join | Keeps |
|---|---|
| INNER JOIN (just JOIN) | only rows that match in both tables (HR people disappear — HR is not in departments) |
| LEFT JOIN | every employee; head is NULL when there is no match |
| RIGHT JOIN | every department, even Finance with no employees |
| FULL JOIN | everything from both sides |
7. Subqueries — a query inside a query
Definition: A subquery is a SELECT nested inside another statement. A CTE (Common Table Expression) is a named, temporary result defined with WITH name AS (...) that exists only for that query.
How it works: A scalar subquery returns one value; a table subquery returns rows (used with IN, EXISTS or in FROM). A correlated subquery refers to the outer row and runs once per outer row. CTEs make long queries readable and can be recursive (for hierarchies).
Example: WHERE amount > (SELECT AVG(amount) FROM orders) — orders above average.
🧒 In simple words
Who earns more than the average?
SELECT name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);name | salary ------+------- Ravi | 65000 Meena | 72000 Divya | 58000
The inner query runs first (average ≈ 53,667), the outer one uses it.
The classic: second highest salary
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);MAX(salary) ----------- 65000
8. Change data — INSERT, UPDATE, DELETE
INSERT INTO employees (id, name, dept, city, salary, joined)
VALUES (7, 'Sana', 'HR', 'Pune', 41000, '2025-01-10');
UPDATE employees SET salary = salary + 2000 WHERE dept = 'HR';
DELETE FROM employees WHERE id = 7;1 row inserted 2 rows updated (Kiran and Sana in HR) 1 row deleted
Always write the WHERE first when you UPDATE or DELETE. Without it, every row changes.
9. Create a table
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(60) NOT NULL,
branch VARCHAR(20),
cgpa DECIMAL(3,2) CHECK (cgpa BETWEEN 0 AND 10)
);Table 'students' created
Constraints keep data clean: PRIMARY KEY (unique id), NOT NULL (must have a value), UNIQUE, CHECK, FOREIGN KEY (must exist in another table).
10. Window functions (asked for analyst roles)
Definition: A window function performs a calculation across a set of rows related to the current row (its "window") without collapsing them into one row.
How it works: Syntax: FUNCTION() OVER (PARTITION BY ... ORDER BY ... ROWS ...). PARTITION BY splits rows into groups, ORDER BY orders them inside each group, and the frame (e.g. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) defines which rows are included. Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE. Offset: LAG, LEAD. Aggregates: SUM, AVG over a window.
Example: Rank employees by salary inside each department while still showing every employee.
🧒 In simple words
Rank people inside each department without losing rows:
SELECT name, dept, salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rank_in_dept
FROM employees;name | dept | salary | rank_in_dept -------+-------+--------+------------- Kiran | HR | 38000 | 1 Meena | IT | 72000 | 1 Ravi | IT | 65000 | 2 Divya | IT | 58000 | 3 Farhan | Sales | 47000 | 1 Asha | Sales | 42000 | 2
ROW_NUMBER() gives 1, 2, 3 even for ties; RANK() gives 1, 1, 3; DENSE_RANK() gives 1, 1, 2.
Practice — 25 exercises
Use the employees and departments tables above. Try first, then check the answers below.
- Show every column of every employee.
- Show only name and city.
- Employees in IT.
- Employees earning at least 50,000.
- Employees in Hyderabad or Pune.
- Names that end with "a".
- All employees sorted by joining date, newest first.
- The lowest-paid employee.
- How many employees are there?
- Total salary paid every month.
- Average salary in Sales.
- Number of employees in each city.
- Departments with more than one person.
- Highest salary in each department.
- Employees who joined in 2024.
- Each employee with their department head.
- Every employee, with head (NULL if none).
- Departments that have no employees.
- Employees earning more than Ravi.
- Second highest salary.
- Give everyone in Sales a 10% raise.
- Delete employees who joined before 2022.
- Create a table projects (id, title, dept, budget).
- Rank employees by salary inside each department.
- Show department, number of people and total salary, biggest total first.
Answers
SELECT * FROM employees;SELECT name, city FROM employees;SELECT * FROM employees WHERE dept = 'IT';SELECT * FROM employees WHERE salary >= 50000;SELECT * FROM employees WHERE city IN ('Hyderabad', 'Pune');SELECT name FROM employees WHERE name LIKE '%a';SELECT * FROM employees ORDER BY joined DESC;SELECT * FROM employees ORDER BY salary ASC LIMIT 1;SELECT COUNT(*) FROM employees;SELECT SUM(salary) FROM employees;SELECT AVG(salary) FROM employees WHERE dept = 'Sales';SELECT city, COUNT(*) FROM employees GROUP BY city;SELECT dept FROM employees GROUP BY dept HAVING COUNT(*) > 1;SELECT dept, MAX(salary) FROM employees GROUP BY dept;SELECT * FROM employees WHERE joined BETWEEN '2024-01-01' AND '2024-12-31';SELECT e.name, d.head FROM employees e JOIN departments d ON e.dept = d.dept;SELECT e.name, d.head FROM employees e LEFT JOIN departments d ON e.dept = d.dept;SELECT d.dept FROM departments d LEFT JOIN employees e ON e.dept = d.dept WHERE e.id IS NULL;SELECT name FROM employees WHERE salary > (SELECT salary FROM employees WHERE name = 'Ravi');SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);UPDATE employees SET salary = salary * 1.10 WHERE dept = 'Sales';DELETE FROM employees WHERE joined < '2022-01-01';CREATE TABLE projects (id INT PRIMARY KEY, title VARCHAR(80), dept VARCHAR(20), budget INT);SELECT name, dept, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) FROM employees;SELECT dept, COUNT(*), SUM(salary) AS total FROM employees GROUP BY dept ORDER BY total DESC;
Top 10 SQL interview questions (short answers)
- Primary key vs unique key — both are unique; a table has one primary key and it can't be NULL.
- DELETE vs TRUNCATE vs DROP — DELETE removes chosen rows (can be undone in a transaction), TRUNCATE empties the table fast, DROP removes the table itself.
- What is a foreign key? — a column that must match a primary key in another table.
- What is normalisation? — splitting data into tables so each fact is stored once (1NF, 2NF, 3NF).
- What is an index? — a lookup structure that makes searches faster but writes a bit slower.
- UNION vs UNION ALL — UNION removes duplicates, UNION ALL keeps them (faster).
- **COUNT() vs COUNT(column)* — COUNT(column) skips NULLs.
- What is a view? — a saved query you can use like a table.
- ACID — Atomicity, Consistency, Isolation, Durability: the promises a transaction keeps.
- Order of execution — FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Further reading
Finished this page? These free sites are good for typing queries yourself: