SQL Exercises
Fill in the blanks to check your knowledge. Each exercise belongs to a lesson.
SQL Syntax
Exercise
End the statement correctly.
SELECT * FROM studentsSELECT
Exercise
Select every column.
SELECT FROM students;
SELECT DISTINCT
Exercise
Return each country only once.
SELECT country FROM students;
WHERE
Exercise
Keep only rows with a score above 80.
SELECT * FROM students score > 80;
AND, OR and NOT
Exercise
Require both conditions.
SELECT * FROM students WHERE country = 'Ghana' score > 70;
ORDER BY
Exercise
Sort from highest to lowest.
SELECT * FROM students ORDER BY score ;
LIMIT (and TOP)
Exercise
Return only 2 rows.
SELECT * FROM students 2;
Aliases
Exercise
Rename the column in the result.
SELECT name student FROM students;
NULL Values
Exercise
Find rows with no score.
SELECT * FROM students WHERE score NULL;
LIKE and Wildcards
Exercise
Names that start with the letter A.
SELECT * FROM students WHERE name 'A%';
The IN Operator
Exercise
Match any of the listed countries.
SELECT * FROM students WHERE country ('Ghana', 'Kenya');
BETWEEN
Exercise
Check a score from 70 to 90.
SELECT * FROM students WHERE score 70 AND 90;
INSERT INTO
Exercise
Add a new row.
INTO students (id, name) VALUES (10, 'Sam');UPDATE
Exercise
Change the score.
UPDATE students score = 90 WHERE id = 1;
DELETE
Exercise
Remove rows from a table.
FROM students WHERE id = 8;MIN and MAX
Exercise
Find the largest value.
SELECT (score) FROM students;
COUNT, AVG and SUM
Exercise
Count all rows.
SELECT (*) FROM students;
String Functions
Exercise
Make the text uppercase.
SELECT (name) FROM students;
Date Functions
Exercise
Which format sorts dates correctly?
Store dates as -MM-DD
CASE
Exercise
Finish the CASE expression.
CASE WHEN score > 50 THEN 'pass' 'fail' END
COALESCE and NULL Handling
Exercise
Use 0 when the value is NULL.
SELECT (score, 0) FROM students;
GROUP BY
Exercise
Group the rows by country.
SELECT country, COUNT(*) FROM students BY country;
HAVING
Exercise
Filter the groups.
... GROUP BY country COUNT(*) > 1
INNER JOIN
Exercise
Add the join condition keyword.
SELECT * FROM a JOIN b a.id = b.a_id;
LEFT JOIN
Exercise
Keep all rows from the left table.
SELECT * FROM a JOIN b ON a.id = b.a_id;
RIGHT JOIN
Exercise
Keep all rows from the right table.
SELECT * FROM a JOIN b ON a.id = b.a_id;
FULL JOIN
Exercise
Name the join that keeps everything.
SELECT * FROM a JOIN b ON a.id = b.id;
Self Join
Exercise
Add the join condition keyword.
SELECT * FROM students s JOIN students r r.id = s.referred_by;
UNION
Exercise
Keep duplicates when combining results.
SELECT a FROM t1 UNION SELECT a FROM t2;
Subqueries
Exercise
Compare with the average using a subquery.
SELECT * FROM students WHERE score > ( AVG(score) FROM students);
EXISTS
Exercise
Test whether the subquery has rows.
WHERE (SELECT 1 FROM enrolments)
ANY and ALL
Exercise
True if the value beats every result.
WHERE score > (SELECT score FROM students)
INSERT INTO SELECT
Exercise
Fill a table from a query.
INSERT INTO archive SELECT * students;
CREATE DATABASE
Exercise
Create a new database.
DATABASE school;CREATE TABLE
Exercise
Define a new table.
TABLE teachers (id INTEGER);DROP TABLE and ALTER TABLE
Exercise
Add a column to a table.
ALTER TABLE notes COLUMN created TEXT;
Data Types
Exercise
Which type should store money exactly?
amount (10,2)
NOT NULL and UNIQUE
Exercise
Make the column required.
email TEXT NOT PRIMARY KEY
Exercise
Mark the identifying column.
id INTEGER PRIMARY FOREIGN KEY
Exercise
Point the column at another table.
FOREIGN KEY (course_id) courses(id)
CHECK and DEFAULT
Exercise
Give the column a starting value.
status TEXT 'pending'
Auto Increment
Exercise
Which keyword generates ids in MySQL?
id INT PRIMARY KEY
Indexes
Exercise
Create an index.
INDEX idx_name ON students (name);Views
Premium exercise. See plans
Transactions
Premium exercise. See plans
SQL Injection
Premium exercise. See plans
SQL Operators
Premium exercise. See plans
Comments
Premium exercise. See plans
Database Design Basics
Premium exercise. See plans
Window Functions
Premium exercise. See plans
PARTITION BY
Premium exercise. See plans
Running Totals and Moving Averages
Premium exercise. See plans
LAG and LEAD
Premium exercise. See plans
NTILE and FIRST_VALUE
Premium exercise. See plans
Common Table Expressions
Premium exercise. See plans
Chaining CTEs
Premium exercise. See plans
Recursive CTEs
Premium exercise. See plans
Generating Series with Recursion
Premium exercise. See plans
Conditional Aggregation and Pivots
Premium exercise. See plans
Correlated Subqueries
Premium exercise. See plans
EXISTS versus IN and NOT EXISTS
Premium exercise. See plans
UNION, INTERSECT and EXCEPT
Premium exercise. See plans
Aggregating Text
Premium exercise. See plans
JSON in SQL
Premium exercise. See plans
Dates and Time Arithmetic
Premium exercise. See plans
UPSERT: Insert or Update
Premium exercise. See plans
RETURNING and Bulk Changes
Premium exercise. See plans
Triggers
Premium exercise. See plans
NULL Pitfalls
Premium exercise. See plans
Pagination: OFFSET and Keyset
Premium exercise. See plans
Changing Data Safely
Premium exercise. See plans
Indexing Strategy
Premium exercise. See plans
Avoiding Slow Query Patterns
Premium exercise. See plans
SQL Injection and Least Privilege
Premium exercise. See plans
Schema Design Habits
Premium exercise. See plans
Reporting Query Patterns
Premium exercise. See plans
Migrations and Testing Queries
Premium exercise. See plans
Differences Between Databases
Premium exercise. See plans
SQL Best Practices
Premium exercise. See plans
Expressions in SELECT
Exercise
Name a calculated column.
SELECT price * 2 double FROM courses;
Sorting by Several Columns
Exercise
Sort high to low.
ORDER BY score LIMIT and OFFSET
Exercise
Skip 2 rows.
LIMIT 3 2
COUNT DISTINCT
Exercise
Count unique values.
COUNT( country)
Comparison Operators
Exercise
Not equal.
WHERE country 'Ghana'
IN and NOT IN
Exercise
Match any in a list.
WHERE country ('Ghana')
BETWEEN with Dates
Exercise
Inclusive range.
WHERE score 70 AND 90
LIKE Patterns
Exercise
Names ending in a.
name LIKE ''
IS NULL and IS NOT NULL
Exercise
Missing scores.
WHERE score NULL
CASE for Labels
Exercise
Close a CASE.
CASE WHEN a THEN 1 ELSE 0 Aggregate Functions Together
Exercise
Highest value.
SELECT (score) FROM students;
GROUP BY More Than One Column
Exercise
Group by a column.
GROUP country
HAVING versus WHERE
Exercise
Filter groups.
GROUP BY country COUNT(*) > 1
INNER JOIN in Practice
Exercise
Join condition keyword.
JOIN b a.id = b.a_id
LEFT JOIN to Find Gaps
Exercise
Keep all left rows.
FROM a JOIN b
Self Join
Exercise
Second alias.
FROM students s JOIN students ON r.id = s.referred_by
CROSS JOIN
Exercise
Pair all rows.
a JOIN b
UNION and UNION ALL
Exercise
Keep duplicates.
UNION Subquery in WHERE
Exercise
Subquery brackets.
WHERE x > SELECT 1)
Subquery in FROM
Exercise
Alias the subquery.
FROM (SELECT 1 a) Insert Several Rows
Exercise
Values keyword.
INSERT INTO t (1), (2);
UPDATE with WHERE
Exercise
Set a column.
UPDATE courses price = 1
DELETE Safely
Exercise
Remove rows.
FROM t WHERE id = 1CREATE TABLE
Exercise
Unique identifier.
id INTEGER KEY
ALTER TABLE ADD COLUMN
Exercise
Add a column.
ALTER TABLE t COLUMN c INT
DEFAULT and CHECK
Exercise
Rule for values.
qty INT (qty > 0)
Foreign Keys
Exercise
Link to another table.
student_id INT students(id)
Indexes
Exercise
Create an index.
CREATE idx ON t(c)
Views
Exercise
Make a saved query.
CREATE v AS SELECT 1
Transactions
Exercise
Undo changes.
;Joining Text
Exercise
Text length.
(name)SUBSTR, REPLACE and TRIM
Exercise
Cut text.
(name, 1, 3)Numbers: ROUND, ABS, modulo
Exercise
Absolute value.
(-7)COALESCE and NULLIF
Exercise
First non-null.
(NULL, 5)Date Basics
Exercise
Add days.
date(d, '+7 ')
Counting by Month
Exercise
Year and month.
strftime('%Y-', joined)
Top N per Group
Exercise
Number rows.
() OVER (ORDER BY a)EXISTS
Exercise
Test any row.
WHERE (SELECT 1)
ANY and ALL Alternatives
Exercise
Beat the best of a group.
score > (SELECT (score) FROM students)
INSERT ... SELECT
Exercise
Copy from a query.
INSERT INTO a * FROM b
Simple Pagination
Exercise
Page 2 of size 3.
LIMIT 3 OFFSET DISTINCT
Exercise
Unique rows.
SELECT country
Table Aliases
Exercise
Alias a table.
FROM students s
Counting Groups with NULL
Exercise
Missing flag.
score IS AS missing
Sorting and NULL
Exercise
Put NULLs last.
ORDER BY score IS , score
Percentages
Exercise
Avoid integer division.
100. * a / b
Finding Duplicates
Exercise
Repeated values.
HAVING COUNT(*) 1
Joining Three Tables
Exercise
Link the next table.
JOIN courses c c.id = e.course_id
Revenue Report
Exercise
Add up amounts.
(price)CASE Pivot
Exercise
Count matches.
SUM(CASE WHEN a THEN ELSE 0 END)
WITH for Readable Queries
Exercise
Name a step.
x AS (SELECT 1) SELECT * FROM xSanity Checks
Exercise
Count rows.
SELECT (*) FROM t
NULL and Joins
Exercise
Keep unmatched.
FROM a JOIN b ON a.x = b.x
Comments and Formatting
Exercise
Line comment.
notePractice: Top Students
Exercise
Limit to 3.
LIMIT Practice: Average per Country
Exercise
Average.
(score)Practice: Unenrolled Students
Exercise
No match test.
WHERE e.student_id NULL