Resources / Data & AI
Free to readData & AI⏱ 13 min read

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

📖 SQL

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

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

📖 Table, row, column, primary key, foreign key

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:

idnamedeptcitysalaryjoined
1AshaSalesHyderabad420002023-06-01
2RaviITBengaluru650002022-01-15
3MeenaITChennai720002021-09-10
4KiranHRHyderabad380002024-02-20
5FarhanSalesPune470002023-11-05
6DivyaITBengaluru580002024-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

SQL
SELECT name, salary FROM employees;
▶ Output
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

SQL
SELECT name AS employee, salary * 12 AS yearly_salary FROM employees;
▶ Output
employee | yearly_salary
---------+--------------
Asha     | 504000
Ravi     | 780000
Meena    | 864000
Kiran    | 456000
Farhan   | 564000
Divya    | 696000

2. WHERE — filter rows

📖 SELECT and WHERE

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

SQL
SELECT name FROM employees WHERE city = 'Hyderabad';
▶ Output
name
-----
Asha
Kiran

Result: Asha, Kiran. Text goes in single quotes; numbers don't.

You wantWrite
more than 50,000salary > 50000
between two valuessalary BETWEEN 40000 AND 60000
one of a listdept IN ('IT', 'HR')
names starting with Kname LIKE 'K%'
no valuemanager IS NULL
two conditionsdept = 'IT' AND city = 'Bengaluru'

3. ORDER BY and LIMIT — sort and keep the top rows

SQL
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3;
▶ Output
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

📖 Aggregate functions

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

FunctionMeaning
COUNT(*)how many rows
SUM(salary)total
AVG(salary)average
MIN / MAXsmallest / biggest
SQL
SELECT COUNT(*) AS people, AVG(salary) AS avg_pay FROM employees;
▶ Output
people | avg_pay
-------+---------
6      | 53666.67

5. GROUP BY and HAVING — totals per group

📖 GROUP BY and HAVING

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

SQL
SELECT dept, COUNT(*) AS people, AVG(salary) AS avg_pay
FROM employees
GROUP BY dept;
▶ Output
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):

SQL
SELECT dept, AVG(salary) AS avg_pay
FROM employees
GROUP BY dept
HAVING AVG(salary) > 50000;
▶ Output
dept | avg_pay
-----+--------
IT   | 65000

Result: only IT.

💡 Tip

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

📖 JOIN

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:

deptfloorhead
Sales1Nikhil
IT3Sara
Finance2Omar
SQL
SELECT e.name, e.dept, d.head
FROM employees e
JOIN departments d ON e.dept = d.dept;
▶ Output
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)
JoinKeeps
INNER JOIN (just JOIN)only rows that match in both tables (HR people disappear — HR is not in departments)
LEFT JOINevery employee; head is NULL when there is no match
RIGHT JOINevery department, even Finance with no employees
FULL JOINeverything from both sides

7. Subqueries — a query inside a query

📖 Subquery and CTE

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?

SQL
SELECT name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
▶ Output
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

SQL
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
▶ Output
MAX(salary)
-----------
65000

8. Change data — INSERT, UPDATE, DELETE

SQL
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;
▶ Output
1 row inserted
2 rows updated   (Kiran and Sana in HR)
1 row deleted
💡 Tip

Always write the WHERE first when you UPDATE or DELETE. Without it, every row changes.

9. Create a table

SQL
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)
);
▶ Output
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)

📖 Window functions

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:

SQL
SELECT name, dept, salary,
       RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rank_in_dept
FROM employees;
▶ Output
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.

  1. Show every column of every employee.
  2. Show only name and city.
  3. Employees in IT.
  4. Employees earning at least 50,000.
  5. Employees in Hyderabad or Pune.
  6. Names that end with "a".
  7. All employees sorted by joining date, newest first.
  8. The lowest-paid employee.
  9. How many employees are there?
  10. Total salary paid every month.
  11. Average salary in Sales.
  12. Number of employees in each city.
  13. Departments with more than one person.
  14. Highest salary in each department.
  15. Employees who joined in 2024.
  16. Each employee with their department head.
  17. Every employee, with head (NULL if none).
  18. Departments that have no employees.
  19. Employees earning more than Ravi.
  20. Second highest salary.
  21. Give everyone in Sales a 10% raise.
  22. Delete employees who joined before 2022.
  23. Create a table projects (id, title, dept, budget).
  24. Rank employees by salary inside each department.
  25. Show department, number of people and total salary, biggest total first.

Answers

  1. SELECT * FROM employees;
  2. SELECT name, city FROM employees;
  3. SELECT * FROM employees WHERE dept = 'IT';
  4. SELECT * FROM employees WHERE salary >= 50000;
  5. SELECT * FROM employees WHERE city IN ('Hyderabad', 'Pune');
  6. SELECT name FROM employees WHERE name LIKE '%a';
  7. SELECT * FROM employees ORDER BY joined DESC;
  8. SELECT * FROM employees ORDER BY salary ASC LIMIT 1;
  9. SELECT COUNT(*) FROM employees;
  10. SELECT SUM(salary) FROM employees;
  11. SELECT AVG(salary) FROM employees WHERE dept = 'Sales';
  12. SELECT city, COUNT(*) FROM employees GROUP BY city;
  13. SELECT dept FROM employees GROUP BY dept HAVING COUNT(*) > 1;
  14. SELECT dept, MAX(salary) FROM employees GROUP BY dept;
  15. SELECT * FROM employees WHERE joined BETWEEN '2024-01-01' AND '2024-12-31';
  16. SELECT e.name, d.head FROM employees e JOIN departments d ON e.dept = d.dept;
  17. SELECT e.name, d.head FROM employees e LEFT JOIN departments d ON e.dept = d.dept;
  18. SELECT d.dept FROM departments d LEFT JOIN employees e ON e.dept = d.dept WHERE e.id IS NULL;
  19. SELECT name FROM employees WHERE salary > (SELECT salary FROM employees WHERE name = 'Ravi');
  20. SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
  21. UPDATE employees SET salary = salary * 1.10 WHERE dept = 'Sales';
  22. DELETE FROM employees WHERE joined < '2022-01-01';
  23. CREATE TABLE projects (id INT PRIMARY KEY, title VARCHAR(80), dept VARCHAR(20), budget INT);
  24. SELECT name, dept, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) FROM employees;
  25. 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:

🔥Join the free 30-Day Placement ChallengeOne resource and one task a day — from resume to offer.