MySQL + SQL · Lesson 112
SQL Queries Practice Set
How to Practice Effectively
The best way to learn SQL is to write queries on a real table. Create the sample table below and try the exercises.
Sample Table
CREATE TABLE employees (
id INT PRIMARY KEY, name VARCHAR(50),
dept VARCHAR(20), salary INT, city VARCHAR(20)
);
Exercises
-- 1. Highest paid employee in each department
SELECT dept, MAX(salary) FROM employees GROUP BY dept;
-- 2. Employees earning above company average
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
-- 3. Count employees per city
SELECT city, COUNT(*) FROM employees GROUP BY city;
-- 4. Second highest salary
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
Summary
- Practice on a real table; write the query before checking.
- Master grouping, subqueries and "second highest" patterns.