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 for Data Analysis
SQL (Structured Query Language) is an indispensable tool for data analysts, providing a powerful way to query and manipulate data stored in relational databases. With its ability to handle large datasets and perform complex operations, SQL has become a fundamental skill for anyone involved in data a
7 min read
SQL for Business Analyst
SQL (Structured Query Language) is a critical skill for business analysts. It allows them to extract, manipulate, and analyze data stored in relational databases. Whether you're working with sales data, customer insights, or financial reports, SQL empowers business analysts to efficiently query and
6 min read
SQL for Business Analysts
In todayâs fast-changing business world, data plays an important role in making decisions. SQL (Structured Query Language) helps business analysts get, study and manage data easily from databases. With SQL, analysts can find useful information, spot patterns, and create reports to support smart busi
5 min read
Data Analyst Jobs in Indore
The demand for skilled data analysts is on the rise globally, and Indore, India, is no exception. As businesses increasingly rely on data-driven insights for decision-making, the need for professionals adept at interpreting and analyzing data has surged. This article serves as a guide for individual
6 min read
Time-Series Data Analysis Using SQL
Time-series data analysis is essential for businesses to monitor trends, forecast demand, and make strategic decisions. One effective method is calculating a 7-day moving average, which smooths out short-term fluctuations and highlights underlying patterns in sales data. This technique helps busines
5 min read
SQL for Data Analysis Cheat Sheet
SQL (Structured Query Language) is essential for data analysis as it enables efficient data retrieval, manipulation, and transformation. It allows analysts to filter, sort, group, and aggregate large datasets, making data-driven decision-making easier. SQL integrates seamlessly with business intelli
4 min read
Data Analyst Jobs in Jaipur
Data analysis has become a cornerstone in modern businesses, driving informed decision-making and strategic planning. In Jaipur, the demand for skilled data analysts is burgeoning across various industries. This guide aims to provide insights into the landscape of data analyst jobs in Jaipur, includ
6 min read
Top 50 SQL Questions For Data Analyst Interview
SQL interview questions for data analysts often cover a range of topics, from basic querying techniques to advanced data manipulation and performance optimization. These questions are designed to assess a candidate's understanding of SQL concepts, their ability to write and optimize queries, and the
10 min read
Healthcare Data Analysis using SQL
Healthcare data analysis plays a vital role in enhancing patient care, improving hospital efficiency and managing financial operations. By utilizing Power BI, healthcare professionals and administrators can gain valuable insights into patient demographics, medical conditions, hospital performance, a
7 min read
What is Data Analytics?
Data analytics, also known as data analysis, is a crucial component of modern business operations. It involves examining datasets to uncover useful information that can be used to make informed decisions. This process is used across industries to optimize performance, improve decision-making, and ga
9 min read