SQL Exercises for Data Analyst
Last Updated :
27 Feb, 2025
Structured Query Language (SQL) is an essential skill for data analysts which enables them to extract, manipulate and analyze data efficiently. Regular practice with SQL exercises helps improve query-writing skills, enhances understanding of database structures, and builds expertise in using aggregation functions, joins, subqueries, and performance optimization techniques.
By working through beginner, intermediate, and advanced SQL exercises, analysts can strengthen their ability to handle real-world data challenges and make informed decisions based on data insights. In this article, We will learn about the SQL exercise which helps you to get more insight by performing the SQL scripts and so on.
Why SQL Exercises are Important for Data Analysts
Data analysts rely on SQL to extract insights from databases efficiently. Regular practice with SQL exercises enhances proficiency in:
- Writing efficient queries
- Understanding database structures
- Working with aggregation functions
- Using joins and subqueries
- Optimizing query performance
Beginner-Level SQL Exercises
Practicing SQL with beginner-friendly exercises helps build a strong foundation in database querying. Start with basic queries like retrieving all records using SELECT *, selecting specific columns, and filtering data with WHERE. Learn to sort results using ORDER BY and apply aggregate functions like COUNT(*) with GROUP BY. These exercises enhance data manipulation skills and prepare beginners for more advanced SQL concepts.
1. Retrieve All Records from a Table
SELECT * FROM employees;
Output:
OutputExplanation: This query retrieves all records from the "employees" table, displaying every column for each row.
2. Select Specific Columns
SELECT first_name, last_name FROM employees;
Output:
Output Explanation: This query selects only the "first_name" and "last_name" columns from the "employees" table.
3. Filter Data Using WHERE Clause
SELECT * FROM employees WHERE department = 'Sales';
Output:
Output Explanation: This query filters and retrieves only the employees who belong to the "Sales" department.
4. Sort Data Using ORDER BY
SELECT * FROM employees ORDER BY salary DESC;
Output:
Explanation: This query sorts employees in descending order based on their salary.
5. Use GROUP BY and Aggregate Functions
SELECT department, COUNT(*) FROM employees GROUP BY department;
Output:
OutputExplanation: This query groups employees by department and counts the number of employees in each department.
Medium-Level SQL Exercises
Enhancing SQL skills involves practicing more advanced queries, such as filtering employees with salaries above the company average using subqueries, finding employees with the same manager, and performing table joins to retrieve related data. Learning to determine the second highest salary with nested queries and extracting employees hired within the last five years strengthens analytical abilities. These exercises help users master SQL for real-world data management.
1. Find Employees with a Salary Greater than the Average Salary
SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
Output:
OutputExplanation: This query retrieves employees whose salary is higher than the average salary in the company.
2. Retrieve Employees Who Have the Same Manager
SELECT * FROM employees WHERE manager_id = 101;
Output:
OutputExplanation: This query selects employees who report to the manager with ID 101.
3. Use Joins to Retrieve Data from Multiple Tables
SELECT employees.first_name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.department_id;
Output:
Output Explanation: This query joins the "employees" and "departments" tables on "department_id" to get each employee's department name.
4. Find the Second Highest Salary
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
Output:
Output Explanation:
- The subquery (SELECT MAX(salary) FROM employees) finds the highest salary in the table.
- The outer query filters salaries that are less than this maximum salary using WHERE salary < (...).
- Finally, MAX(salary) is applied to get the highest value among the remaining salaries, which is the second highest salary.
5. Retrieve Employees Hired in the Last 5 Years
SELECT * FROM employees WHERE hire_date > DATE_SUB(CURDATE(), INTERVAL 5 YEAR);
Output:
Output Explanation: This query selects employees who were hired within the last five years.
Advanced-Level SQL Exercises
Mastering SQL involves handling complex queries like identifying employees with multiple job roles, calculating running salary totals within departments, and using recursive queries for hierarchical data. Detecting duplicate records with GROUP BY and HAVING, as well as optimizing queries with indexes, enhances performance and efficiency.
These exercises develop advanced SQL skills for handling large datasets, improving query execution speed, and managing structured data effectively.
1. Find Employees Earning More Than Their Department’s Average Salary
SELECT employee_id, first_name, last_name, salary, department_id
FROM employees e
WHERE salary > (SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id);
Output:
Output Explanation: This query selects employees whose salary is higher than the average salary of their respective department. It uses a correlated subquery to calculate the department's average salary and compares each employee’s salary with that value.
2. Retrieve the Top 2 Highest Paid Employees from Each Department
SELECT employee_id, first_name, last_name, department_id, salary
FROM (SELECT employee_id, first_name, last_name, department_id, salary,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees) ranked
WHERE rnk <= 2;
Output:
Output Explanation: This query uses the DENSE_RANK() function to assign a rank to employees based on their salary within each department (PARTITION BY department_id). The outer query filters for only the top 2 highest-paid employees in each department.
3. Find Employees Who Have More Experience Than Their Department’s Average
SELECT employee_id, first_name, last_name, department_id, hire_date
FROM employees e
WHERE hire_date < (SELECT AVG(hire_date)
FROM employees
WHERE department_id = e.department_id);
Output:
OutputExplanation: This query selects employees who were hired before the average hire date of their department. The correlated subquery calculates the department-wise average hire date, and employees with an earlier hire date are considered more experienced.
4. Get Employees with a Higher Salary Than Their Manager
SELECT e.employee_id, e.first_name, e.last_name, e.salary, e.manager_id
FROM employees e
JOIN employees m ON e.manager_id = m.employee_id
WHERE e.salary > m.salary;
Output:
OutputExplanation: This query joins the employees table to itself (self-join) to compare each employee's salary with their manager’s salary. It returns employees who earn more than their manager.
5. Optimize a Query Using Indexes
CREATE INDEX idx_employee_salary ON employees(salary);
Explanation: This command creates an index on the "salary" column to improve query performance when filtering or sorting by salary.
How to Effectively Practice SQL Exercises
To maximize the benefits of SQL exercises, follow these best practices:
- Start with Basics: Ensure a solid understanding of simple queries before moving to advanced topics.
- Use a Real Database: Practice with databases like PostgreSQL, MySQL, or SQLite instead of just reading solutions.
- Experiment with Variations: Modify queries and explore different solutions to understand their impact.
- Work on Real-World Scenarios: Try solving business-related problems using SQL.
- Optimize Queries: Learn how to improve query performance by using indexes and avoiding unnecessary computations.
Conclusion
Mastering SQL requires consistent practice with various query types, from simple data retrieval to complex analytical queries. By engaging in structured SQL exercises, data analysts can develop a deep understanding of database operations, improve their problem-solving skills, and optimize query performance. Practicing SQL in real-world scenarios, experimenting with different queries, and applying indexing techniques can significantly enhance efficiency. As SQL remains a critical tool in data analysis, continuous learning and hands-on practice will help analysts stay proficient and competitive in the field.
Similar Reads
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
SQL Query Interview Questions SQL or Structured Query Language, is the standard language for managing and manipulating relational databases such as MySQL, Oracle, and PostgreSQL. It serves as a powerful tool for efficiently handling data whether retrieving specific data points, performing complex analysis, or modifying database
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read