Sql Practice Exercises With Solutions
SQL Practice Exercises with Solutions Mastering SQL (Structured Query Language) is
essential for anyone aiming to excel in data analysis, database management, or backend
development. Whether you're a beginner or looking to sharpen your skills, practicing SQL
through well-designed exercises can significantly enhance your understanding and
problem-solving abilities. This article provides comprehensive SQL practice exercises with
solutions, covering fundamental concepts and gradually progressing to more advanced
topics. By working through these exercises, you'll strengthen your ability to write efficient
queries, manipulate data effectively, and understand complex database operations. ---
Basic SQL Practice Exercises
These exercises focus on fundamental SQL concepts such as SELECT statements, filtering
data, and simple aggregations. They are ideal for beginners starting their SQL journey.
Exercise 1: Retrieve All Data from a Table
Problem: Retrieve all records from the `employees` table. Solution: ```sql SELECT FROM
employees; ```
Exercise 2: Select Specific Columns
Problem: Display only the `employee_id`, `first_name`, and `salary` columns from the
`employees` table. Solution: ```sql SELECT employee_id, first_name, salary FROM
employees; ```
Exercise 3: Filter Data Using WHERE
Problem: Find all employees with a salary greater than $50,000. Solution: ```sql SELECT
FROM employees WHERE salary > 50000; ```
Exercise 4: Use of AND, OR Operators
Problem: Retrieve employees who work in department 10 or 20 and earn less than
$60,000. Solution: ```sql SELECT FROM employees WHERE (department_id IN (10, 20))
AND salary < 60000; ```
Exercise 5: Sorting Data with ORDER BY
Problem: List employees ordered by their `hire_date` from newest to oldest. Solution:
```sql SELECT FROM employees ORDER BY hire_date DESC; ```
2
Exercise 6: Limit the Number of Rows
Problem: Retrieve the top 5 highest-paid employees. Solution: ```sql SELECT FROM
employees ORDER BY salary DESC LIMIT 5; ``` ---
Intermediate SQL Practice Exercises
Building on basic skills, these exercises introduce joins, subqueries, grouping, and
functions.
Exercise 7: Using JOINs
Problem: List employee names along with their department names. Assume `employees`
and `departments` tables with `department_id` as a common key. Solution: ```sql SELECT
e.first_name, e.last_name, d.department_name FROM employees e JOIN departments d
ON e.department_id = d.department_id; ```
Exercise 8: Aggregate Functions
Problem: Calculate the average salary of employees in each department. Solution: ```sql
SELECT department_id, AVG(salary) AS average_salary FROM employees GROUP BY
department_id; ```
Exercise 9: Filtering with HAVING
Problem: Find departments with an average salary greater than $70,000. Solution: ```sql
SELECT department_id, AVG(salary) AS average_salary FROM employees GROUP BY
department_id HAVING AVG(salary) > 70000; ```
Exercise 10: Subqueries
Problem: Retrieve employees who earn more than the average salary across all
employees. Solution: ```sql SELECT first_name, last_name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees); ```
Exercise 11: Using CASE Statements
Problem: Create a new column `salary_grade` that categorizes salaries into 'Low',
'Medium', and 'High'. Solution: ```sql SELECT first_name, last_name, salary, CASE WHEN
salary < 40000 THEN 'Low' WHEN salary BETWEEN 40000 AND 70000 THEN 'Medium'
ELSE 'High' END AS salary_grade FROM employees; ``` ---
3
Advanced SQL Practice Exercises
These exercises explore complex queries, window functions, and database design
considerations.
Exercise 12: Window Functions
Problem: For each employee, calculate their salary rank within their department. Solution:
```sql SELECT first_name, last_name, department_id, salary, RANK() OVER (PARTITION BY
department_id ORDER BY salary DESC) AS salary_rank FROM employees; ```
Exercise 13: Recursive Queries
Problem: Display an organizational hierarchy from the `employees` table with
`employee_id` and `manager_id`. Solution: ```sql WITH RECURSIVE employee_hierarchy
AS ( SELECT employee_id, manager_id, first_name, last_name, 1 AS level FROM employees
WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.manager_id,
e.first_name, e.last_name, eh.level + 1 FROM employees e INNER JOIN
employee_hierarchy eh ON e.manager_id = eh.employee_id ) SELECT FROM
employee_hierarchy; ```
Exercise 14: Data Modification - UPDATE
Problem: Increase the salary of all employees in department 30 by 10%. Solution: ```sql
UPDATE employees SET salary = salary 1.10 WHERE department_id = 30; ```
Exercise 15: Data Modification - DELETE
Problem: Remove all employees who have not made a salary payment in the last year.
Assume there's a `last_payment_date` column. Solution: ```sql DELETE FROM employees
WHERE last_payment_date < DATE_SUB(CURDATE(), INTERVAL 1 YEAR); ``` ---
Tips for Effective SQL Practice
Start with simple queries and gradually move to complex ones.
Practice writing queries without looking at solutions first.
Use sample datasets to simulate real-world scenarios.
Understand the problem before jumping into writing SQL code.
Test your queries with different parameters and edge cases.
Review SQL documentation and resources to learn new functions and techniques.
4
Resources for Further Practice
SQL Practice Problems
LeetCode SQL Problems
Mode SQL Tutorial
W3Schools SQL Tryit Editor
---
Conclusion
Practicing SQL exercises with solutions is an invaluable method to deepen your
understanding of database management and query writing. By steadily progressing
through beginner, intermediate, and advanced problems, you'll develop the confidence
and skills necessary to handle real-world data challenges. Remember to analyze each
problem carefully, test your queries thoroughly, and explore different techniques to
optimize your SQL proficiency. With consistent practice and curiosity, you'll become
proficient in SQL and open up numerous opportunities in data-driven roles. Happy coding!
QuestionAnswer
What are some effective
SQL practice exercises for
beginners?
Beginner exercises include creating tables, inserting data,
retrieving data with SELECT statements, filtering with
WHERE clauses, updating records, and deleting entries.
Practice with real-world datasets like employee or product
tables to build foundational skills.
How can I improve my SQL
query writing skills through
exercises?
Consistently solve problems such as writing complex
JOINs, aggregate functions, subqueries, and nested
queries. Use online platforms like LeetCode, HackerRank,
or SQLZoo that offer hands-on exercises with solutions and
explanations to enhance your understanding.
Are there sample SQL
exercises with solutions
available for practicing
joins?
Yes, many resources provide exercises on different types
of joins (INNER, LEFT, RIGHT, FULL). For example, practice
retrieving data from multiple tables with sample datasets
and refer to step-by-step solutions to understand join
logic.
What are some common
SQL practice problems
involving data
manipulation?
Common problems include updating multiple records with
conditions, deleting duplicate entries, inserting data with
constraints, and transforming data formats. Solving these
helps you master data manipulation commands like
UPDATE, DELETE, INSERT, and ALTER.
How can I use SQL practice
exercises to prepare for
SQL certification exams?
Focus on exercises covering core topics like data retrieval,
aggregation, joins, subqueries, indexing, and transaction
management. Use practice problems with solutions from
certification prep books or online courses to simulate
exam conditions.
5
Are there advanced SQL
exercises with solutions to
challenge my skills?
Yes, advanced exercises include writing recursive queries,
optimizing query performance, working with window
functions, and handling complex subqueries. Practice
these with datasets that mimic real-world complexities to
deepen your expertise.
What are some online
platforms offering SQL
practice exercises with
detailed solutions?
Platforms like LeetCode, HackerRank, SQLZoo, Mode
Analytics, and W3Schools offer a wide range of SQL
exercises with solutions and explanations, suitable for all
skill levels.
How can I verify my SQL
practice solutions are
correct?
Compare your query results with provided solutions, use
test datasets to validate outputs, and understand the logic
behind each solution. Additionally, using database
management tools to run and debug queries helps ensure
correctness.
SQL Practice Exercises with Solutions: A Comprehensive Guide to Mastering SQL Skills SQL
(Structured Query Language) is the backbone of database management and a crucial skill
for data analysts, developers, and database administrators. Whether you're just starting
out or looking to sharpen your existing skills, practicing with real-world exercises is one of
the most effective ways to learn SQL. In this guide, we will explore a series of SQL practice
exercises with solutions designed to help you build a strong foundation and advance your
query-writing capabilities. By working through these examples, you'll develop confidence
in handling complex queries, understanding database structures, and optimizing your SQL
code. --- Why Practice SQL Exercises? Before diving into the exercises, let’s understand
why consistent practice is essential: - Reinforces Learning: Applying concepts in practical
scenarios helps solidify your understanding. - Builds Problem-Solving Skills: SQL exercises
often involve troubleshooting and optimizing queries. - Prepares for Real-World Tasks:
Many job roles require proficiency in writing efficient SQL queries. - Identifies Knowledge
Gaps: Practice reveals areas where you need further study. --- Setting Up Your
Environment To get the most out of these exercises, ensure you have access to a SQL
environment. You can use: - Online Platforms: SQLZoo, LeetCode, HackerRank, Mode
Analytics - Local Setup: Install MySQL, PostgreSQL, or SQLite on your machine - Sample
Databases: Use provided sample databases like Sakila, Northwind, or create your own ---
Sample Database Schema For these exercises, we'll assume a simplified e-commerce
database with the following tables: Customers | customer_id | name | email | city |
registration_date | |--------------|----------------|-----------------------|-------------|-------------------| | 1 |
Alice Johnson | alice@example.com | New York | 2020-01-15 | | 2 | Bob Smith |
bob@example.com | Los Angeles | 2019-07-22 | | ... | ... | ... | ... | ... | Orders | order_id |
customer_id | order_date | total_amount | |------------|--------------|------------|--------------| | 101 |
1 | 2021-11-20 | 250.00 | | 102 | 2 | 2021-11-21 | 125.50 | | ... | ... | ... | ... | Products |
product_id | name | category | price | |--------------|-----------------|----------------|--------| | 1001 |
Wireless Mouse | Accessories | 25.00 | | 1002 | Mechanical Keyboard | Accessories | 70.00
Sql Practice Exercises With Solutions
6
| | ... | ... | ... | ... | OrderDetails | order_id | product_id | quantity | |------------|--------------|------
----| | 101 | 1001 | 2 | | 101 | 1002 | 1 | | 102 | 1001 | 1 | | ... | ... | ... | --- Basic SQL Practice
Exercises with Solutions 1. Retrieve All Customers Exercise: Write a SQL query to select all
columns for every customer. ```sql SELECT FROM Customers; ``` Solution Explanation:
This simple query fetches all the data from the Customers table, providing a
comprehensive list of customers. --- 2. Find Customers from a Specific City Exercise: List
all customers who are from 'New York'. ```sql SELECT name, email FROM Customers
WHERE city = 'New York'; ``` Solution Explanation: The WHERE clause filters records to
only include customers whose city matches 'New York'. --- 3. Count Total Number of
Orders Exercise: Find out how many orders have been placed. ```sql SELECT COUNT() AS
total_orders FROM Orders; ``` Solution Explanation: The COUNT() function tallies all rows
in the Orders table, giving the total number of orders. --- Intermediate SQL Exercises 4.
List Orders with Total Amount Greater Than $200 Exercise: Retrieve order IDs and total
amounts for orders exceeding $200. ```sql SELECT order_id, total_amount FROM Orders
WHERE total_amount > 200; ``` Solution Explanation: The WHERE clause filters the orders
to only include those with total_amount greater than 200. --- 5. Find the Customer Name
for Each Order Exercise: Join Orders with Customers to display order IDs alongside
customer names. ```sql SELECT o.order_id, c.name AS customer_name FROM Orders o
JOIN Customers c ON o.customer_id = c.customer_id; ``` Solution Explanation: This uses a
JOIN to connect Orders with Customers based on matching customer_id values, enabling
display of customer names alongside their orders. --- 6. List Products and Their Prices
Exercise: Retrieve all products with their names and prices. ```sql SELECT name, price
FROM Products; ``` Solution Explanation: A straightforward SELECT statement fetching
product names and prices. --- Advanced SQL Practice Exercises 7. Find the Top 3 Most
Expensive Products Exercise: List the top three products with the highest prices. ```sql
SELECT name, price FROM Products ORDER BY price DESC LIMIT 3; ``` Solution
Explanation: ORDER BY sorts products by price in descending order, and LIMIT restricts
the output to the top 3. --- 8. Calculate Total Revenue per Customer Exercise: For each
customer, compute the total revenue from their orders. ```sql SELECT c.name,
SUM(o.total_amount) AS total_revenue FROM Customers c JOIN Orders o ON c.customer_id
= o.customer_id GROUP BY c.customer_id, c.name; ``` Solution Explanation: This joins
Customers and Orders, groups the data by customer, and sums the total_amounts to get
total revenue per customer. --- 9. Find Customers Who Have Not Placed Any Orders
Exercise: List customers who haven't placed any orders. ```sql SELECT c.name FROM
Customers c LEFT JOIN Orders o ON c.customer_id = o.customer_id WHERE o.order_id IS
NULL; ``` Solution Explanation: A LEFT JOIN includes all customers, and the WHERE clause
filters for those with no matching orders (NULL in order_id). --- 10. Identify Products Never
Ordered Exercise: List products that haven't been included in any order. ```sql SELECT
p.name FROM Products p LEFT JOIN OrderDetails od ON p.product_id = od.product_id
Sql Practice Exercises With Solutions
7
WHERE od.product_id IS NULL; ``` Solution Explanation: Similar to previous, but focusing
on Product and OrderDetails. The WHERE clause filters for products with no corresponding
entries in OrderDetails. --- Tips for Effective SQL Practice - Start with simple queries and
gradually increase complexity. - Use sample databases to practice real-world scenarios. -
Write queries from scratch rather than copying solutions. - Test your queries with different
parameters. - Optimize your queries for performance, especially on large datasets. -
Document your thought process to improve problem-solving skills. --- Additional
Resources - Books: "SQL in 10 Minutes, Sams Teach Yourself" by Ben Forta - Online
Courses: Coursera, Udemy, Khan Academy - Practice Platforms: LeetCode, HackerRank,
Mode Analytics - Official Documentation: MySQL, PostgreSQL, SQLite docs --- Conclusion
Mastering SQL requires consistent practice and exposure to diverse query challenges. The
SQL practice exercises with solutions provided in this guide are designed to help you
develop a robust understanding of fundamental and advanced concepts. By working
through these exercises and exploring variations, you'll be well on your way to becoming
proficient in SQL, capable of handling complex data retrieval and manipulation tasks with
confidence. Remember, the key to mastery is perseverance—keep practicing, stay
curious, and leverage available resources to deepen your knowledge.
SQL exercises, SQL solutions, SQL practice problems, SQL tutorial, SQL query examples,
SQL training, SQL query exercises, SQL coding practice, SQL query solutions, SQL learning