Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL for Business Analyst
Next article icon

SQL Exercises for Data Analyst

Last Updated : 27 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

employees
Output

Explanation: 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:

b2
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:

b3
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:

b4

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:

b5
Output

Explanation: 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:

m1
Output

Explanation: 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:

m2
Output

Explanation: 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:

m3
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:

m4
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:

m5
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:

ai
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:

a2
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:

a3
Output

Explanation: 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:

a4
Output

Explanation: 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.


Next Article
SQL for Business Analyst

G

GFG_Internal_Team
Improve
Article Tags :
  • Databases
  • SQL

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences