sql practice exercises with solutions

SQL Practice Exercises with Solutions: Boost Your Database Skills

sql practice exercises with solutions are an essential tool for anyone looking to sharpen their database management and querying skills. Whether you're a beginner just starting out or an experienced developer aiming to polish your expertise, working through practical SQL problems can dramatically improve your understanding of relational databases. In this article, we'll explore a variety of exercises designed to cover fundamental to advanced SQL concepts, complete with detailed solutions and explanations to help you truly grasp the logic behind each query.

By engaging with these exercises, you’ll not only learn how to write efficient SQL commands but also develop a deeper intuition for database design, data manipulation, and optimization strategies. Let's dive into a hands-on journey that makes learning SQL both fun and effective.

Why Practice SQL Exercises with Solutions Matters

Understanding SQL syntax and commands theoretically is one thing, but applying that knowledge through exercises is where real learning happens. When you practice SQL queries:


  • You reinforce your memory of commands such as SELECT, JOIN, GROUP BY, and subqueries.

  • You encounter common challenges like filtering data, aggregating results, or handling NULL values.

  • You improve your ability to troubleshoot and optimize queries, which is crucial for working with large datasets.

  • You prepare yourself for real-world scenarios in data analysis, software development, and database administration.


Having solutions at your fingertips allows you to compare your approach and learn alternative ways to solve the same problem. This comparison deepens your understanding and exposes you to best practices and efficient query patterns.

Essential SQL Practice Exercises with Solutions

Below are several exercises spanning different difficulty levels, along with their solutions and explanations. These examples use a sample database with tables such as Employees, Departments, and Sales, common in many SQL learning environments.

Exercise 1: Retrieve All Employees’ Names and Their Departments

Problem: Write a query to list each employee's full name alongside the department they belong to.

Solution:
```sql
SELECT e.FirstName, e.LastName, d.DepartmentName
FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID;
```

Explanation:
This query uses an INNER JOIN to combine the Employees and Departments tables based on the DepartmentID. It demonstrates the fundamental concept of joining tables to fetch related data, a key skill in relational databases.

Exercise 2: Find Employees with Salaries Above Average

Problem: List employees whose salaries exceed the average salary in the company.

Solution:
```sql
SELECT FirstName, LastName, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
```

Explanation:
Here, a subquery calculates the average salary across all employees. The outer query then filters employees earning more than this average. This exercise highlights the use of aggregate functions and subqueries.

Exercise 3: Count the Number of Employees per Department

Problem: Determine how many employees work in each department.

Solution:
```sql
SELECT d.DepartmentName, COUNT(e.EmployeeID) AS EmployeeCount
FROM Departments d
LEFT JOIN Employees e ON d.DepartmentID = e.DepartmentID
GROUP BY d.DepartmentName;
```

Explanation:
Using a LEFT JOIN ensures that even departments without employees are included, showing a count of zero if applicable. GROUP BY aggregates data per department, which is a common requirement in reporting and analytics.

Exercise 4: List Top 3 Highest Paid Employees

Problem: Display the top three employees with the highest salaries.

Solution:
```sql
SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 3;
```

Explanation:
ORDER BY sorts the employees by salary in descending order, and LIMIT restricts the output to the top three rows. This pattern is useful when querying for rankings or top performers.

Exercise 5: Find Employees Hired in the Last Year

Problem: Retrieve employees who joined the company within the past 12 months.

Solution:
```sql
SELECT FirstName, LastName, HireDate
FROM Employees
WHERE HireDate >= DATEADD(year, -1, GETDATE());
```

Note: The exact date function may vary based on the SQL dialect (e.g., MySQL uses `DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`).

Explanation:
This query filters employees based on their HireDate compared to the current date minus one year, demonstrating date functions and conditional filtering.

Advanced SQL Practice Exercises with Solutions

For those ready to tackle more complex scenarios, these exercises incorporate multiple joins, nested queries, and window functions.

Exercise 6: Calculate Running Total of Sales per Employee

Problem: For each employee, calculate a cumulative total of their sales ordered by date.

Solution:
```sql
SELECT
EmployeeID,
SaleDate,
Amount,
SUM(Amount) OVER (PARTITION BY EmployeeID ORDER BY SaleDate) AS RunningTotal
FROM Sales;
```

Explanation:
Window functions like SUM() OVER() allow you to compute running totals without collapsing rows. This technique is invaluable for time series analysis and financial reporting.

Exercise 7: Identify Departments Without Any Employees

Problem: List departments that currently have no employees assigned.

Solution:
```sql
SELECT DepartmentName
FROM Departments d
LEFT JOIN Employees e ON d.DepartmentID = e.DepartmentID
WHERE e.EmployeeID IS NULL;
```

Explanation:
A LEFT JOIN combined with a NULL check on the right table’s key finds records without matching entries, a common pattern for identifying missing relationships.

Exercise 8: Find Employees Who Have Made Sales Above $10,000

Problem: List employees who have at least one sale exceeding $10,000.

Solution:
```sql
SELECT DISTINCT e.FirstName, e.LastName
FROM Employees e
JOIN Sales s ON e.EmployeeID = s.EmployeeID
WHERE s.Amount > 10000;
```

Explanation:
Using DISTINCT removes duplicates since an employee might have multiple sales over the threshold. This exercise reinforces JOINs and filtering conditions.

Tips for Maximizing Your SQL Practice

Working through exercises is only part of the journey. Here are some tips to enhance your learning experience:


  • Understand the schema: Before jumping into queries, familiarize yourself with the database structure, relationships, and data types.

  • Write queries by hand first: Thinking through the logic before typing helps clarify your approach and reduces errors.

  • Explain your queries: Try explaining what each part of your query does, either aloud or in comments. Teaching is a great way to reinforce learning.

  • Experiment with variations: Modify exercises by adding more conditions, using different joins, or applying aggregate functions differently.

  • Use online platforms: Websites like LeetCode, HackerRank, and Mode Analytics offer interactive SQL challenges with instant feedback.

  • Review optimized solutions: Compare your queries with optimized versions to learn about performance considerations and best practices.


Incorporating SQL Exercises into Your Learning Routine

Consistency is key when mastering SQL. Setting aside regular time to solve practice problems helps cement your skills over time. Consider these strategies:


  • Start with basics: Build a solid foundation with simple SELECT statements, filters, and joins.

  • Gradually increase difficulty: Move towards subqueries, window functions, and complex aggregations.

  • Work on real datasets: Applying your skills to open datasets or projects you care about makes learning more engaging.

  • Join study groups or forums: Discussing problems with others exposes you to diverse approaches and solutions.


Engaging with SQL practice exercises with solutions in a structured manner ensures that your knowledge evolves from theoretical concepts to practical expertise, preparing you for challenges in data-driven roles.

Whether you're aiming to land a job in data analysis, enhance your software development toolkit, or manage enterprise databases, regular practice will keep your SQL skills sharp and ready for any scenario. Keep exploring, experimenting, and solving—there's always something new to learn in the world of SQL.

Frequently Asked Questions

What are some effective SQL practice exercises for beginners?
Effective SQL practice exercises for beginners include writing basic SELECT queries, filtering data with WHERE clauses, using aggregate functions like COUNT and SUM, and performing simple JOIN operations. Websites like LeetCode, HackerRank, and SQLZoo offer structured exercises with solutions.
Where can I find SQL practice exercises with solutions online?
You can find SQL practice exercises with solutions on platforms such as LeetCode, HackerRank, SQLZoo, Mode Analytics SQL tutorials, and W3Schools. These sites provide interactive problems ranging from beginner to advanced levels along with detailed solutions.
How can practicing SQL exercises improve my database skills?
Practicing SQL exercises helps improve your ability to write efficient and accurate queries, understand database schema design, optimize query performance, and solve real-world data retrieval problems, ultimately making you more proficient in managing and analyzing data.
What types of SQL exercises should I focus on to prepare for job interviews?
To prepare for job interviews, focus on exercises involving complex JOINs, subqueries, window functions, groupings with HAVING clauses, data manipulation (INSERT, UPDATE, DELETE), and designing queries that handle real-world scenarios like reporting and data aggregation.
Can you provide a sample SQL practice exercise with solution?
Sample Exercise: Retrieve the names of customers who have placed more than 5 orders. Solution: SELECT customer_name FROM customers c JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.customer_name HAVING COUNT(o.order_id) > 5;
How often should I practice SQL exercises to become proficient?
Consistency is key. Practicing SQL exercises daily or several times a week for at least 30 minutes to an hour can significantly improve your skills over time. Regular practice helps reinforce concepts and keeps your knowledge fresh.
Are there SQL practice exercises that focus on database optimization and performance?
Yes, advanced SQL practice exercises often focus on query optimization, indexing strategies, analyzing execution plans, and rewriting queries for better performance. Platforms like Mode Analytics and SQL Performance Explained offer such exercises with solutions.
What is the best way to approach solving SQL practice problems?
The best approach is to first understand the problem requirements, analyze the database schema, write a rough query outline, test it incrementally, and refine it for correctness and efficiency. Reviewing solutions and explanations after attempting problems also helps deepen understanding.
Can practicing SQL exercises help in learning different SQL dialects?
Yes, practicing SQL exercises across different platforms exposes you to various SQL dialects like MySQL, PostgreSQL, SQL Server, and Oracle SQL. While core SQL syntax remains similar, practicing helps you learn dialect-specific functions and features.