Dev Duel

SQL Challenges

Train with filtering, joins, grouping, subqueries, and window functions.

Filter challenges

Narrow down by difficulty or category.

Showing 48 of 48 challenges

All challenges

Practice concepts, improve problem-solving, and build confidence.

intermediate10 minutes

Find the Second Highest Salary

Return the second highest salary from an employees table.

subqueriessubqueriessorting
beginner10 minutes

Calculate Total Sales Per Employee Using SQL GROUP BY

Learn how to aggregate sales data by employee using the SQL GROUP BY clause and aggregate functions in this beginner-friendly challenge.

aggregationsGROUP BYSUM()
beginner10 minutes

Calculate Total Sales per Product Using SQL Aggregate Functions

Write an SQL query to find the total sales for each product using aggregate functions.

aggregate functionsSUM()GROUP BY
beginner10 minutes

Find the Top 3 Customers by Total Purchase Amount

Write an SQL query to identify the top 3 customers who have spent the most in total purchases, using a sample sales database.

queriesGROUP BYSUM()
beginner10 minutes

Find Customers Who Made Purchases Above $100 Using SQL

Practice writing a SQL query to identify customers who have made purchases greater than $100 from a sales table.

queriesSELECT DISTINCTWHERE clause
beginner10 minutes

SQL Beginner Challenge: Calculate Total Sales per Customer

Practice basic SQL aggregation by calculating the total sales amount for each customer in a sales database.

aggregationSQL AggregationGROUP BY clause
beginner10 minutes

Find Employees with Salaries Above Department Average

Write an SQL query to find employees whose salaries are higher than the average salary of their respective departments.

queriesaggregate functionssubqueries
beginner10 minutes

Fix the Broken SELECT Query to Retrieve Employee Names

A simple SQL query intended to retrieve all employee names is not working correctly. Your task is to identify and fix the syntax errors so the query runs successfully and returns the correct results.

debuggingBasic SQL syntaxSELECT statement
advanced15 minutes

Build a SQL Function to Calculate Running Median Over a Dynamic Window

In this challenge, you will create a SQL function that calculates the running median value of a numeric column over a dynamic sliding window based on timestamps. This requires advanced use of window functions, array manipulation, and median calculation within SQL.

queriesWindow FunctionsMedian Calculation
intermediate15 minutes

Design and Query a Library Management Data Model

Create a SQL data model for a library management system and write queries to retrieve meaningful information about books, authors, borrowers, and loans.

data-modelingSQL JOINsmany-to-many relationships
advanced15 minutes

Fix Bug in Complex SQL Query Summarizing Sales Data

Debug and fix the provided SQL query that intends to summarize monthly sales data by product category but produces incorrect results due to logical errors and misused joins.

debuggingSQL JoinsAggregation and GROUP BY
beginner10 minutes

Fix the Bug in SQL Query to Filter Active Users

Identify and fix the bug in the provided SQL query that is supposed to retrieve only active users from the users table.

debuggingSQL WHERE clauseString comparison
intermediate10 minutes

Fix Incorrect Join and Aggregation in Sales Report Query

A SQL query intended to generate a monthly sales report per product category uses incorrect join syntax and aggregation logic. Fix the query to produce accurate total sales per category per month.

debuggingSQL JOINGROUP BY and Aggregations
beginner10 minutes

Fix the Incorrect SQL Query Filtering by Date

Identify and fix the bug in the provided SQL query that aims to filter orders placed after January 1, 2023. The original query incorrectly returns all rows due to a syntax mistake in the WHERE clause.

debuggingWHERE clauseDate comparison
intermediate10 minutes

Refactor SQL Query for Sales Aggregation Optimization

Improve the given SQL query that calculates total and average sales per product category. The original query uses multiple subqueries and redundant joins, causing inefficiencies. Refactor it to be cleaner and more performant while preserving the exact results.

optimizationSQL joinsaggregate functions
advanced10 minutes

Predict the Output of a Recursive CTE with Aggregations and Window Functions

Analyze the output of an advanced SQL query using recursive common table expressions (CTEs), aggregations, and window functions. Predict the final result set given the schema and sample data.

query-analysisRecursive CTEAggregation
intermediate10 minutes

Predict the Output of an SQL Query with Subqueries and Joins

Analyze the given SQL query involving JOINs and a correlated subquery, and predict the final output based on a provided sample database schema and data.

query-analysisCorrelated subqueriesJOIN operations
advanced40 minutes

Design and Implement a Scalable E-Commerce Order Tracking Data Model

Build a comprehensive SQL data model supporting order tracking, including customers, products, orders, shipments, and status history, ensuring efficient querying for complex business insights.

data-modelingSQL schema designData normalization
beginner10 minutes

Fix the SQL Query to Correctly Calculate Average Salary

This challenge requires you to debug a simple SQL query that attempts to calculate the average salary from an employees table, but the query contains syntax errors that prevent it from running correctly.

debuggingSQL syntax basicsAggregate functions
intermediate10 minutes

Create a SQL Function to Calculate Running Sales Total per Customer

Build a SQL function that calculates the running total of sales for each customer ordered by the sale date.

querieswindow functionsrunning total
advanced15 minutes

Refactor Complex SQL Query for Improved Performance and Readability

You are given a large and complex SQL query that fetches sales summary data with multiple subqueries and redundant joins. Refactor the query to improve its readability and optimize performance while ensuring the output remains exactly the same.

optimizationSQL query optimizationCommon Table Expressions (CTEs)
advanced15 minutes

Create a SQL Function to Calculate Moving Average Sales Over Dynamic Time Windows

Build a SQL function that calculates the moving average of daily sales for a specified product over a dynamic number of previous days. The function should handle gaps in dates and provide efficient performance for large sales datasets.

querieswindow functionsdate range queries
advanced15 minutes

Fix the Aggregation Bug in Employee Salary Report Query

An SQL query intended to generate a report summarizing total salaries by department and job title has incorrect aggregation logic causing wrong results. Your task is to identify and fix the bugs in the query to produce accurate aggregation.

debuggingSQL aggregationGROUP BY clause
beginner10 minutes

Predict the Output of a Simple SQL SELECT with WHERE Clause

Analyze a basic SQL query that filters data using a WHERE clause and predict what the output will be based on the given data.

query-analysisSELECT statementWHERE clause filtering
advanced15 minutes

Refactor and Optimize Complex Sales Reporting SQL Query

Optimize a poorly written, inefficient SQL query that aggregates sales data by region and product category while filtering on multiple conditions. Improve readability, performance and ensure the output remains correct.

optimizationSQL optimizationJoins and subqueries
advanced10 minutes

Predict the Output of a Complex Window Function and CTE SQL Query

Analyze the given SQL query involving multiple CTEs and window functions to determine the exact output produced by the final SELECT statement.

query-analysisCTEsWindow Functions
intermediate10 minutes

Fix the Incorrect JOIN Logic in Customer Orders Query

Debug and fix a SQL query that attempts to retrieve customer names alongside their total order counts, but currently returns incorrect results due to improper JOIN usage and grouping.

debuggingSQL JOINsGROUP BY
advanced15 minutes

Create a SQL Function to Calculate Running Median by Group

Build an advanced SQL function that calculates the running median of a numeric column grouped by a category column over a dynamic order, using window functions and optimized querying.

querieswindow functionsdynamic SQL
beginner10 minutes

Refactor a Repetitive SQL Query to Use Better Aggregation

Improve a basic SQL query by refactoring repetitive SELECT statements with better use of aggregation and GROUP BY to optimize the code while maintaining the original result.

optimizationGROUP BYSUM()
advanced15 minutes

Fix a Bug in an SQL Query for Aggregated Sales Performance with Window Functions

Identify and fix the bug in a complex SQL query that attempts to calculate monthly sales performance rankings by salesperson, using window functions and joins.

debuggingwindow functionsSQL aggregation
beginner10 minutes

Refactor SQL Query to Optimize Simple SELECT with CASE

Improve the readability and efficiency of a beginner-level SQL query that uses multiple CASE statements to classify product sales data without changing its behavior.

optimizationCASE statementsSQL query refactoring
beginner10 minutes

Fix the SQL Query to Retrieve Employees with Salary Over 50000

In this challenge, you are given a broken SQL query intended to select all employees earning more than 50000. Your task is to identify and fix the bugs so that the query returns the correct results.

debuggingSQL SELECT statementWHERE clause
advanced15 minutes

Debugging an Inefficient Employee Salary Ranking Query

Fix a broken SQL query that attempts to rank employees by salary within each department but produces incorrect rankings and poor performance due to improper use of window functions and filters.

debuggingWindow FunctionsSQL Ranking Functions
advanced60 minutes

Design and Optimize a Sales Database Schema with Advanced Queries

Create a normalized database schema for a retail sales system that handles customers, products, orders, and shipments. Then, write optimized SQL queries to retrieve key business insights including sales trends, customer segmentation, and shipment statuses.

data-modelingNormalized schema designRelational database modeling
beginner10 minutes

Refactor SQL Query to Remove Redundant Subquery

Optimize a basic SQL query by refactoring it to remove an unnecessary subquery, improving readability and performance without changing the output.

optimizationsimple SELECTWHERE clause
advanced45 minutes

Design and Query a Multi-Level Employee Management Hierarchy

Create a relational data model to represent an organization's employee hierarchy with multiple reporting levels and implement complex SQL queries to retrieve hierarchical reports and aggregate statistics.

data-modelingrecursive Common Table Expressionsself-referencing foreign keys
beginner10 minutes

Create a SQL Function to Return the Total Number of Orders for a Customer

Write a simple SQL function that takes a customer ID as input and returns the total count of orders placed by that customer.

queriesSQL functionsSELECT query
intermediate15 minutes

Design and Query a Movie Rental Database Schema

Build a normalized relational schema for a movie rental system including customers, movies, rentals, and payments, then write SQL queries to retrieve key business insights.

data-modelingdatabase schema designprimary and foreign keys
intermediate10 minutes

Create a SQL Function to Calculate Employee Tenure in Years

Write a SQL function that calculates the tenure of an employee in years based on their hire date and an optional end date. The function should return the number of full years the employee has worked.

queriesSQL functionsDate calculations
advanced30 minutes

Design and Query an Employee Hierarchy Data Model

Create a normalized data model to represent an employee hierarchy within a company, then write an advanced SQL query to retrieve hierarchical reports and aggregated information.

data-modelingrecursive CTEself-referencing foreign key
beginner10 minutes

Create a Simple Employee Department Summary Query

Build a SQL query to summarize employee data by department with basic aggregation and grouping techniques.

data-modelingSQL JOINGROUP BY
advanced15 minutes

Create a SQL Function to Calculate Customer Lifetime Value (CLV)

Write a SQL function that calculates the Customer Lifetime Value (CLV) based on customer transactions, applying discounting over time and accounting for customer churn rate.

querieswindow functionsdate/time calculation
beginner10 minutes

Create a Simple Student Grades Table and Query

Build a beginner-level SQL project to create a basic data model for student grades. Define a table, insert sample data, and write a query to retrieve student names with their corresponding grades.

data-modelingCREATE TABLEINSERT INTO
intermediate10 minutes

Refactor SQL Query for Optimized Employee Sales Report

Improve the given SQL query for generating a monthly sales report by employee to increase readability and performance without changing the output.

optimizationSQL joinsAggregate functions
advanced15 minutes

Fix the Recursive Sales Totals Query for Hierarchical Employees

You are given a broken SQL query intended to calculate total sales made by each employee and their subordinates in a hierarchical company structure. The query uses a recursive CTE but produces incorrect or incomplete totals. Your task is to identify and fix the bugs so that the query accurately computes cumulative sales totals including all levels of subordinates.

debuggingrecursive CTEhierarchical queries
intermediate15 minutes

Design and Query an Employee-Project Assignment Schema

Create a normalized database schema to manage employees, projects, and their assignments. Write SQL queries to retrieve project involvement and employee workloads.

data-modelingdatabase normalizationjoins (LEFT JOIN)
intermediate10 minutes

Refactor Complex Sales Report Query for Performance Optimization

Improve a verbose and inefficient SQL query that generates a monthly sales report by refactoring it into a cleaner, optimized form while maintaining its original behavior.

optimizationSQL optimizationCommon Table Expressions (CTEs)
beginner10 minutes

Create a Simple Employee and Department Tables with Basic Queries

Build and query basic employee and department tables to practice simple SQL data modeling and retrieval.

data-modelingCREATE TABLEINSERT INTO