SQL exercises with solutions: SELECT, aliases and DISTINCT
Updated on
SELECT picks the columns to show; AS renames a column, DISTINCT removes duplicates. These 4 exercises range from level 1 to level 1; they use the syntax of SQLite, SpeedQL’s SQL engine.
Tip: List the columns you need rather than SELECT *: the result is easier to read and faster.
Read the “SELECT, aliases, DISTINCT” card in the cheat sheet
Exercise 1
Show every column and every row of the employees table.
| id | name | department | salary |
|---|---|---|---|
| 1 | Alice | Finance | 32000 |
| 2 | Bob | IT | 41000 |
| 3 | Claire | Finance | 38000 |
| 4 | David | HR | 29000 |
Show the hint
Topics to use: SELECT, aliases, DISTINCT.
Query structure:
SELECT *
FROM …Show the solution
SELECT *
FROM employees;Expected result (4 rows):
| id | name | department | salary |
|---|---|---|---|
| 1 | Alice | Finance | 32000 |
| 2 | Bob | IT | 41000 |
| 3 | Claire | Finance | 38000 |
| 4 | David | HR | 29000 |
Exercise 2
Show only the name and the salary of every employee.
| id | name | department | salary |
|---|---|---|---|
| 1 | Alice | Finance | 32000 |
| 2 | Bob | IT | 41000 |
| 3 | Claire | Finance | 38000 |
| 4 | David | HR | 29000 |
Show the hint
Topics to use: SELECT, aliases, DISTINCT.
Query structure:
SELECT …, …
FROM …Show the solution
SELECT name, salary
FROM employees;Expected result (4 rows):
| name | salary |
|---|---|
| Alice | 32000 |
| Bob | 41000 |
| Claire | 38000 |
| David | 29000 |
Exercise 3
Show the employees' names in a column called employee, and their salaries in a column called annual_salary.
| id | name | department | salary |
|---|---|---|---|
| 1 | Alice | Finance | 32000 |
| 2 | Bob | IT | 41000 |
| 3 | Claire | Finance | 38000 |
| 4 | David | HR | 29000 |
Show the hint
Topics to use: SELECT, aliases, DISTINCT.
Query structure:
SELECT … AS …, … AS …
FROM …Show the solution
SELECT name AS employee, salary AS annual_salary
FROM employees;Expected result (4 rows):
| employee | annual_salary |
|---|---|
| Alice | 32000 |
| Bob | 41000 |
| Claire | 38000 |
| David | 29000 |
Exercise 4
Show the list of product categories, without duplicates.
| id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Keyboard | Office | 25 | 40 |
| 2 | Mouse | Office | 15 | 0 |
| 3 | Screen | Display | 180 | 12 |
| 4 | Headset | Audio | 60 | 8 |
| 5 | Webcam | Office | 45 | 0 |
| 6 | Speaker | Audio | 35 | 25 |
Show the hint
Topics to use: SELECT, aliases, DISTINCT.
Query structure:
SELECT DISTINCT …
FROM …Show the solution
SELECT DISTINCT category
FROM products;Expected result (3 rows):
| category |
|---|
| Office |
| Display |
| Audio |
Practice with automatic checking
In SpeedQL, you write your query and it is checked straight away, on these tables and then on a hidden dataset.