Advanced SQL Puzzles
Advanced SQL Puzzles
Scott Peters
https://advancedsqlpuzzles.com/
Welcome
I hope you enjoy these puzzles as much as I have enjoyed creating them!
As my list of puzzles continues to grow, I have decided to combine the puzzles into one document
broken down into two sections.
In the first section, I have 64 of the most difficult puzzles I could create, randomly organized and in no
specific order. These are primarily set-based puzzles, interspersed with a small number of puzzles that
require knowledge of constraints, specific data types, cursors, loops, etc...
Working through these puzzles will give you an understanding of the SQL language and what types of
problems the SQL language solves best. Remember that SQL is a declarative and not an imperative
language, and always think in sets when providing a solution.
I collected all the puzzles related to permutations, combinations, and sequences in the second set of
puzzles. Solving these puzzles will require a deeper knowledge of your SQL thinking, focusing on such
constructs as using recursion or sequence objects to reach the desired output (and, of course, some will
require using traditional set-based thinking). Ultimately, these puzzles resolve to creating number
tables, which can be used to fill in gaps, create ranges and tallies, provide custom sorting, and allow you
to create set-based solutions over iterative solutions. I also included a few puzzles from Part 1 into this
set as they ultimately deal with creating a numbers table.
I hope navigating through the GitHub repository to find the solutions is straightforward. The first set of
puzzles are combined into one single SQL document, and the second set has a separate folder with
individual solutions, as these solutions are a little more involved in solving. For my sanity, it is easiest
not to embed the SQL solutions into this text document and instead provide them separately as SQL files
in the GitHub repository. If you have any issues navigating the website or GitHub, please contact me
and I would be happy to help.
I welcome any corrections, new tricks, new techniques, dead links, misspellings, bugs, and especially any
new puzzles that would be a great fit for this document.
Please contact me through the contact page on my website or use the discussion board in the GitHub
repository.
https://advancedsqlpuzzles.com/
Happy coding!
https://advancedsqlpuzzles.com/
Page |2
PART I
Thinking in Sets
https://advancedsqlpuzzles.com/
Page |3
Puzzle #1
Shopping Carts
You are tasked with providing an audit of two shopping carts.
Write an SQL statement to transform the following tables into the expected output.
Item Item
Sugar Sugar
Bread Bread
Juice Butter
Soda Cheese
Flour Fruit
https://advancedsqlpuzzles.com/
Page |4
Puzzle #2
Managers and Employees
Given the following hierarchical table, write an SQL statement that determines the level of depth each
employee has from the president.
https://advancedsqlpuzzles.com/
Page |5
Puzzle #3
Fiscal Year Pay Rates
For each standard fiscal year, a record exists for each employee that states their current pay rate for the
specified year.
Can you determine all the constraints that can be applied to this table to ensure it contains only correct
information? Assume that no pay raises are given mid-year. There are quite a few of them, so think
carefully.
CREATE TABLE #EmployeePayRecord
(
EmployeeID INTEGER
FiscalYear INTEGER,
StartDate DATE,
EndDate DATE,
PayRate MONEY
);
https://advancedsqlpuzzles.com/
Page |6
Puzzle #4
Two Predicates
Write an SQL statement given the following requirements.
For every customer that had a delivery to California, provide a result set of the customer orders that
were delivered to Texas.
• Customer ID 1001 would be in the expected output as this customer had deliveries to both
California and Texas.
• Customer ID 3003 would not appear in the result set as they did not have a delivery to Texas.
• Customer ID 4004 would not appear in the result set as they did not have a delivery to
California.
https://advancedsqlpuzzles.com/
Page |7
Puzzle #5
Phone Directory
Your customer phone directory table allows individuals to set up a home, cellular, or work phone
number.
Write an SQL statement to transform the following table into the expected output.
https://advancedsqlpuzzles.com/
Page |8
Puzzle #6
Workflow Steps
Write an SQL statement that determines all workflows that have started but have not been completed.
Workflow
Bravo
Charlie
• The expected output would be Bravo and Charlie, as they have a workflow that has started but
has not been completed.
• Bonus: Write this query using only the COUNT function with no subqueries. Can you figure out
the trick?
https://advancedsqlpuzzles.com/
Page |9
Puzzle #7
Mission to Mars
You are given the following tables that list the requirements for a space mission and a list of potential
candidates.
Write an SQL statement to determine which candidates meet the mission's requirements.
Candidates
Candidate ID Description
1001 Geologist
1001 Astrogator
1001 Biochemist
1001 Technician
2002 Surgeon
2002 Machinist
2002 Geologist
3003 Geologist
3003 Astrogator
4004 Selenologist
Requirements
Description
Geologist
Astrogator
Technician
Candidate ID
1001
• The expected output would be Candidate ID 1001, as this candidate has all the necessary skills
for the space mission.
• Candidate ID 2002 and 3003 would not be in the output as they have some but not all the
required skills, and Candidate ID 4004 has none of the needed requirements.
https://advancedsqlpuzzles.com/
P a g e | 10
Puzzle #8
Workflow Cases
You have a report of all workflows and their case results.
A value of 0 signifies the workflow failed, and a value of 1 signifies the workflow passed.
Write an SQL statement that transforms the following table into the expected output.
Workflow Passed
Alpha 0
Bravo 2
Charlie 1
Delta 0
https://advancedsqlpuzzles.com/
P a g e | 11
Puzzle #9
Matching Sets
Write an SQL statement that matches an employee to all other employees who carry the same licenses.
Employee ID License
1001 Class A
1001 Class B
1001 Class C
2002 Class A
2002 Class B
2002 Class C
3003 Class A
3003 Class D
4004 Class A
4004 Class B
4004 Class D
5005 Class A
5005 Class B
5005 Class D
• Employee IDs 1001 and 2002 would be in the expected output as they both carry a Class A, Class
B, and a Class C license.
• Employee IDs 4004 and 5005 would be in the expected output as they both carry a Class A, Class
B, and a Class D license.
• Although Employee ID 3003 has the same licenses as Employee ID 4004 and 5005, these
Employee IDs do not have the same license as Employee ID 3003.
https://advancedsqlpuzzles.com/
P a g e | 12
Puzzle #10
Mean, Median, Mode, and Range
• The mean is the average of all numbers.
• The median is the middle number in a sequence of numbers.
• The mode is the number that occurs most often within a set of numbers.
• The range is the difference between the largest and smallest values in a set of numbers.
Write an SQL statement to determine the mean, median, mode, and range of the set of integers
provided in the following DDL statement.
https://advancedsqlpuzzles.com/
P a g e | 13
Puzzle #11
Permutations
You are given the following list of test cases and must determine all possible permutations.
Write an SQL statement that produces the expected output. Ensure your code can account for a
changing number of elements without rewriting.
Test Case
A
B
C
Test Cases
A,B,C
A,C,B
B,A,C
B,C,A
C,A,B
C,B,A
https://advancedsqlpuzzles.com/
P a g e | 14
Puzzle #12
Average Days
Write an SQL statement to determine the average number of days between executions for each
workflow.
https://advancedsqlpuzzles.com/
P a g e | 15
Puzzle #13
Inventory Tracking
You work for a manufacturing company and need to track inventory adjustments from the warehouse.
Some days the inventory increases, on other days the inventory decreases.
Write an SQL statement that will provide a running balance of the inventory.
https://advancedsqlpuzzles.com/
P a g e | 16
Puzzle #14
Indeterminate Process Log
Your process log has several workflows broken down by step numbers with the possible status values of
Complete, Running, or Error.
Your task is to write an SQL statement that creates an overall status based on the following
requirements.
• If all steps of a workflow are of the same status (Error, Complete, or Running), then return the
distinct status.
• If any steps of a workflow have an Error status along with a status of Complete or Running, set
the overall status to Indeterminate.
• If the workflow steps have a combination of Complete and Running (without any Errors), set the
overall status to Running.
Workflow Status
Alpha Indeterminate
Bravo Complete
Charlie Running
Delta Error
Echo Running
https://advancedsqlpuzzles.com/
P a g e | 17
Puzzle #15
Group Concatenation
Write an SQL statement that can group concatenate the following values.
Sequence Syntax
1 SELECT
2 Product,
3 UnitPrice,
4 EffectiveDate
5 FROM
6 Products
7 WHERE
8 UnitPrice
9 > 100
Syntax
SELECT Product, UnitPrice, EffectiveDate FROM Products WHERE UnitPrice > 100
https://advancedsqlpuzzles.com/
P a g e | 18
Puzzle #16
Reciprocals
You work for a software company that released a 2-player game and you need to tally the scores.
Given the following table, write an SQL statement to determine the reciprocals and calculate their
aggregate score.
In the data below, players 3003 and 4004 have two valid entries, but their scores need to be aggregated
together.
https://advancedsqlpuzzles.com/
P a g e | 19
Puzzle #17
De-Grouping
Write an SQL Statement to de-group the following data.
Product Quantity
Pencil 3
Eraser 4
Notebook 2
Product Quantity
Pencil 1
Pencil 1
Pencil 1
Eraser 1
Eraser 1
Eraser 1
Eraser 1
Notebook 1
Notebook 1
https://advancedsqlpuzzles.com/
P a g e | 20
Puzzle #18
Seating Chart
Given the set of integers provided in the following DDL statement, write the SQL statements to
determine the following:
• Gap start and gap ends
• Total missing numbers
• Count of odd and even numbers
Type Count
Even Numbers 8
Odd Numbers 9
https://advancedsqlpuzzles.com/
P a g e | 21
Puzzle #19
Back to the Future
Here is one of the more difficult puzzles to solve with a declarative SQL statement.
https://advancedsqlpuzzles.com/
P a g e | 22
Puzzle #20
Price Points
Write an SQL statement to determine the current price point for each product.
https://advancedsqlpuzzles.com/
P a g e | 23
Puzzle #21
Average Monthly Sales
Write an SQL statement that returns a list of states where customers have an average monthly sales
value that is consistently greater than $100.
State
TX
• Texas would show in the result set as Customer ID 1001 and 2002 each have their average
monthly value over $100.
• Iowa would not show in the result set because Customer ID 4004 did not have an average
monthly value over $100 in May 2018.
https://advancedsqlpuzzles.com/
P a g e | 24
Puzzle #22
Occurrences
Write an SQL statement that returns all distinct process log messages and the workflow where the
message occurred the most often.
https://advancedsqlpuzzles.com/
P a g e | 25
Puzzle #23
Divide in Half
You work for a gaming company and need to rank players by their score into two categories.
Players that rank in the top half must be given a value of 1, and the remaining players must be given a
value of 2.
Player ID Score
1001 2343
2002 9432
3003 6548
4004 1054
5005 6832
https://advancedsqlpuzzles.com/
P a g e | 26
Puzzle #24
Page Views
Write an SQL statement that retrieves records 5 to 10 ordered by the Order ID column.
https://advancedsqlpuzzles.com/
P a g e | 27
Puzzle #25
Top Vendors
Write an SQL statement that returns the vendor from which each customer has placed the most orders.
Customer ID Vendor
1001 Direct Parts
2002 ACME
https://advancedsqlpuzzles.com/
P a g e | 28
Puzzle #26
Previous Year’s Sales
Write an SQL statement that shows the current year’s sales, along with the previous year’s sales, and
the sales from two years ago.
Year Amount
2018 $352,645
2017 $165,565
2017 $254,654
2016 $159,521
2016 $251,696
2016 $111,894
https://advancedsqlpuzzles.com/
P a g e | 29
Puzzle #27
Delete the Duplicates
Given the set of integers provided in the following DDL statement, write an SQL statement that deletes
the duplicated integers (1 and 3).
Integer Value
1
2
3
4
https://advancedsqlpuzzles.com/
P a g e | 30
Puzzle #28
Fill the Gaps
The answer to this problem is often referred to as a data smear or a flash fill.
https://advancedsqlpuzzles.com/
P a g e | 31
Puzzle #29
Count the Groupings
Write an SQL statement that counts the consecutive values in the Status column.
https://advancedsqlpuzzles.com/
P a g e | 32
Puzzle #30
Select Star
Your developers have many bad practices; the worst of them being they routinely deploy procedures
that do not explicitly define which columns to return in their SELECT clause.
Modify the following table in such a way that the statement SELECT * FROM Products will return an
error when executed.
https://advancedsqlpuzzles.com/
P a g e | 33
Puzzle #31
Second Highest
Given the set of integers in the following DDL statement, how many different SQL statements can you
write that will return the second-highest integer?
Integer Value
3762
https://advancedsqlpuzzles.com/
P a g e | 34
Puzzle #32
First and Last
Write an SQL statement that determines the most and least experienced Spaceman ID by their job
description.
https://advancedsqlpuzzles.com/
P a g e | 35
Puzzle #33
Deadlines
How many different SQL statements can you write that determines if an order will be fulfilled by the
requested delivery date?
Orders
Order ID Product Days to Deliver
1 Widget 7
2 Gizmo 3
3 Doodad 9
Manufacturing Time
Part Product Days to Manufacture
AA-111 Widget 7
BB-222 Widget 2
CC-333 Widget 3
DD-444 Widget 1
AA-111 Gizmo 7
BB-222 Gizmo 2
AA-111 Doodad 7
DD-444 Doodad 1
Order ID Product
1 Widget
3 Doodad
• Order ID 1 and 2 would be in the output as these orders have a promised delivery date that is
equal to or greater than the days to manufacture.
https://advancedsqlpuzzles.com/
P a g e | 36
Puzzle #34
Specific Exclusion
Write an SQL statement that returns all rows except where the Customer ID is 1001 and the Amount is
$50.
https://advancedsqlpuzzles.com/
P a g e | 37
Puzzle #35
International vs. Domestic Sales
You work in a sales office that sells widgets both domestically and internationally.
Write an SQL statement that shows all sales representatives who either had a domestic sale or an
international sale, but not both.
Sales Rep ID
3003
4004
5005
6006
• Sales Rep IDs 3003, 4004, 5005, and 6006 would appear in the result set as they had either an
international sale or a domestic sale, but not both.
https://advancedsqlpuzzles.com/
P a g e | 38
Puzzle #36
Traveling Salesman
Here is a well-known problem that is called the Traveling Salesman.
Write an SQL statement that shows all the possible routes from Austin to Des Moines. Which route is
the most expensive? Which route is the least expensive?
https://advancedsqlpuzzles.com/
P a g e | 39
Puzzle #37
Group Criteria Keys
Write an SQL statement that provides a key based upon the distinct combination of the columns
Distributor, Facility, and Zone.
https://advancedsqlpuzzles.com/
P a g e | 40
Puzzle #38
Reporting Elements
You must provide a report of all distributors and their sales by region. If a distributor did not have any
sales for a region, provide a zero-dollar value for that day. Assume there is at least one sale for each
region.
• In the result set, Ace and Direct Parts each have a fabricated record with 0 sales.
https://advancedsqlpuzzles.com/
P a g e | 41
Puzzle #39
Prime Numbers
A prime number is a natural number greater than one that has no positive divisors other than one and
itself.
Write an SQL statement to determine which of the integers provided in the following DDL statement are
prime numbers.
Integer Value
2
3
5
7
https://advancedsqlpuzzles.com/
P a g e | 42
Puzzle #40
Sort Order
Write an SQL statement that sorts the following values into the expected output. Can you find the most
elegant solution?
City
Atlanta
Baltimore
Chicago
Denver
City
Baltimore
Denver
Atlanta
Chicago
https://advancedsqlpuzzles.com/
P a g e | 43
Puzzle #41
Associate IDs
The following table shows two hierarchical structures.
1. The first is the association between Anne, Betty, Charles, Dan, and Emma.
2. The second is the association between Francis, George, and Harriet.
Write an SQL statement that creates a grouping number for each hierarchical association and display the
member in the associations.
Associate 1 Associate 2
Anne Betty
Anne Charles
Betty Dan
Charles Emma
Francis George
George Harriet
Grouping Associate
1 Anne
1 Betty
1 Charles
1 Dan
1 Emma
2 Francis
2 George
2 Harriet
https://advancedsqlpuzzles.com/
P a g e | 44
Puzzle #42
Mutual Friends
The following table shows a cyclic data structure.
Given the following list of friend connections, determine the number of mutual connections between
the friends.
Friend 1 Friend 2
Jason Mary
Mike Mary
Mike Jason
Susan Jason
John Mary
Susan Mary
https://advancedsqlpuzzles.com/
P a g e | 45
Puzzle #43
Unbounded Preceding
Determine the minimum quantity for each record between the current row and all previous rows for
each Customer ID.
https://advancedsqlpuzzles.com/
P a g e | 46
Puzzle #44
Slowly Changing Dimension Part I
Give the following table, write an SQL statement to create a Type 2 Slowly Changing Dimension.
https://advancedsqlpuzzles.com/
P a g e | 47
Puzzle #45
Slowly Changing Dimension Part II
Given the following table with overlapping timeframes. Write an SQL statement to identify the
overlapping records.
https://advancedsqlpuzzles.com/
P a g e | 48
Puzzle #46
Negative Account Balances
How many different SQL statements can you write to determine all accounts whose balance has never
been positive?
Account ID Balance
1001 $234.45
1001 $-23.12
2002 $-93.01
2002 $-120.19
3003 $186.76
3003 $90.23
3003 $10.11
Account ID
2002
• Account ID 2002 would appear in the result set as this account has never had a positive balance.
• There are a multitude of ways to write this statement, can you think of them all?
https://advancedsqlpuzzles.com/
P a g e | 49
Puzzle #47
Work Schedule
Given a table of employee shifts, and another table of their activities, merge the two tables and write an
SQL statement that produces the desired output. If an employee is scheduled and does not have an
activity planned, label the time frame as “Work”.
Schedule
Schedule ID Start Time End Time
A 10/1/2021 10:00 10/1/2021 15:00
B 10/1/2021 10:15 10/1/2021 12:15
Activity
Schedule ID Activity Start Time End Time
A Meeting 10/1/2021 10:00 10/1/2021 10:30
A Break 10/1/2021 12:00 10/1/2021 12:30
A Meeting 10/1/2021 13:00 10/1/2021 13:30
B Break 10/1/2021 11:00 10/1/2021 11:15
https://advancedsqlpuzzles.com/
P a g e | 50
Puzzle #48
Consecutive Sales
For the following Customer IDs, write an SQL statement to determine customers that had a sale in the
current year, plus the previous two consecutive years.
You will need to adjust the test data for the current year, as the test data is coded for the year 2021.
Sales ID Year
1001 2018
1001 2019
1001 2020
2002 2020
2002 2021
3003 2018
3003 2020
3003 2021
4004 2019
4004 2020
4004 2021
Sales ID
4004
• Sales ID 4004 would be in the expected output as this customer had a sale in the current year,
plus the previous two years.
https://advancedsqlpuzzles.com/
P a g e | 51
Puzzle #49
Sumo Wrestlers
A group of Sumo wrestlers are forming a line to board an elevator. Unfortunately, the elevator can only
hold 2,000 pounds and not all Sumo wrestlers can board. Which Sumo wrestler would be the last to
enter given the following queue order?
Name
Haruki
• The expected output would be Haruki, as this is the last Sumo wrestler to fit in the elevator
before the 2,000-pound maximum capacity is reached.
https://advancedsqlpuzzles.com/
P a g e | 52
Puzzle #50
Baseball Balls and Strikes
For this puzzle, you will need to understand the rules of baseball's balls and strike count.
Given a table containing the columns Batter ID, Pitch Number and Result for each pitch. Construct an
SQL statement that returns Start Of Pitch Count and End Of Pitch Count.
Batter ID Pitch Number Result Start Of Pitch Count End Of Pitch Count
1001 1 Foul 0–0 0–1
1001 2 Foul 0–1 0–2
1001 3 Ball 0–2 1–2
1001 4 Ball 1–2 2–2
1001 5 Strike 2–2 2–3
2002 1 Ball 0–0 1–0
2002 2 Strike 1–0 1–1
2002 3 Foul 1–1 1–2
2002 4 Foul 1–2 1–2
2002 5 Foul 1–2 1–2
2002 6 In Play 1–2 In-Play
3003 1 Ball 0–0 1–0
3003 2 Ball 1–0 2–0
3003 3 Ball 2–0 3–0
3003 4 Ball 3–0 4–0
4004 1 Foul 0–0 0–1
4004 2 Foul 0–1 0–2
4004 3 Foul 0–2 0–2
4004 4 Foul 0–2 0–2
4004 5 Foul 0–2 0–2
4004 6 Strike 0–2 0–3
https://advancedsqlpuzzles.com/
P a g e | 53
Puzzle #51
Primary Key Creation
Given the following table whose natural key is a combination of the columns Assembly ID and Part, use
the HASHBYTES and CHECKSUM functions to create two new column that can be used as primary keys.
The goal here is to create a single column that is unique and re-creatable. The benefit of creating a
hashbytes or checksum column is to aid in data profiling and integrity checks when a table contains a
multitude of columns that form the natural key (and some of these columns can be NULL).
Assembly ID Part
1001 Bolt
1001 Screw
2002 Nut
2002 Washer
3003 Toggle
3003 Bolt
https://advancedsqlpuzzles.com/
P a g e | 54
Puzzle #52
Phone Numbers Table
You are creating a table that customer agents will use to enter customer phone numbers.
Create a table with the columns Customer ID and Phone Number, where the Phone Number column
must be inserted with the format (999)-999-9999.
Agents will enter phone numbers into this table via a form, and it is imperative that phone numbers are
formatted correctly when inputted. Create a table that meets these requirements.
https://advancedsqlpuzzles.com/
P a g e | 55
Puzzle #53
Spouse IDs
You are given the following table of individuals and their spouse. Every individual exists both as a
Primary ID and a Spouse ID. You need to create a group criteria key to match the associated records.
Primary ID Spouse ID
Pat Charlie
Jordan Casey
Ashley Dee
Charlie Pat
Casey Jordan
Dee Ashley
https://advancedsqlpuzzles.com/
P a g e | 56
Puzzle #54
Winning the Lottery
You are part of an office lottery pool where you keep a table of the winning lottery numbers along with
a table of each ticket’s chosen numbers. If a ticket has some but not all the winning numbers, you win
$10. If a ticket has all the winning numbers, you win $100. Calculate the total winnings for today’s
drawing.
Winning Numbers
Number
25
45
78
Tickets
Ticket ID Number
AAA 25
AAA 45
AAA 78
BBB 25
BBB 45
BBB 98
CCC 67
CCC 86
CCC 91
Amount
$110
• The expected output would be $110, as you have one winning ticket with all the winning
numbers, and one ticket that has some but not all the winning numbers.
https://advancedsqlpuzzles.com/
P a g e | 57
Puzzle #55
Table Audit
Conduct an audit on the following tables to identify products and their corresponding quantities that are
either matching or unique to each table, and generate the expected output listed below.
Products A
Product Name Quantity
Widget 7
Doodad 9
Gizmo 3
Products B
Product Name Quantity
Widget 7
Doodad 6
Dingbat 9
Type ProductName
Matches in both table A and table B Widget
Product does not exist in table A Dingbat
Product does not exist in table B Gizmo
Quantity in table A and table B do not match Doodad
https://advancedsqlpuzzles.com/
P a g e | 58
Puzzle #56
Numbers Using Recursion
Create a numbers table using a recursive query.
Number
1
2
3
4
5
6
7
8
9
10
https://advancedsqlpuzzles.com/
P a g e | 59
Puzzle #57
Find the Spaces
Given the following table containing SQL statements, write an SQL statement that displays the following
summary.
Statement
SELECT EmpID FROM Employees;
SELECT * FROM Transactions;
https://advancedsqlpuzzles.com/
P a g e | 60
Puzzle #58
Add Them Up
You are given the following table, which contains a VARCHAR column that contains mathematical
equations. Sum the equations and provide the answers in the output.
Equation
123
1+2+3
1+2-3
1+23
1-2+3
1-2-3
1-23
12+3
12-3
Permutation Sum
123 123
1+2+3 6
1+2-3 0
1+23 24
1-2+3 2
1-2-3 -4
1-23 -22
12+3 15
12-3 9
https://advancedsqlpuzzles.com/
P a g e | 61
Puzzle #59
Balanced String
Given a string containing parentheses, brackets, and braces, determine if the string is a balanced string.
A balanced string must have an opening symbol, a corresponding closing symbol, and the symbols
appear in the correct order.
For example, the string "([])" is balanced because the opening square bracket is followed by the closing
square bracket, and the opening parenthesis is followed by the closing parenthesis, and they are in the
correct order. However, the string "([)]" is not balanced because the closing parenthesis appears before
the closing square bracket.
Can you discover an efficient algorithm for determining whether a given string is balanced or not?
ID String
1 ()
2 []
3 {}
4 (({[]}))
5 ()[]
6 ({})
7 ({)}
8 ({)}}}()
9 }{()][
ID String Outcome
1 () Balanced
2 [] Balanced
3 {} Balanced
4 (({[]})) Balanced
5 ()[] Balanced
6 ({}) Balanced
7 ({)} Unbalanced
8 ({)}}}() Unbalanced
9 }{()][ Unbalanced
https://advancedsqlpuzzles.com/
P a g e | 62
Puzzle #60
Products Without Duplicates
Given the below products table, return a result set of all product codes not associated with multiple
products.
Product Code
EE
GG
• The result set will contain the Product Codes of EE and GG as Product Codes 01, 02, 03, and 04
are associated with Alpha and Bravo, which have multiple entries.
https://advancedsqlpuzzles.com/
P a g e | 63
Puzzle #61
Player Scores
For the following dataset, you need to find the difference between each player’s first and current scores,
as well as their last and current scores. If their score improved from their previous score, mark the
record as improved. If each iteration improved, mark the player as overall improved.
https://advancedsqlpuzzles.com/
P a g e | 64
Puzzle #62
Car and Boat Purchase
You won the lottery and want to buy both a car and a boat. However, the car must be $200,000 more
than the boat. What are your options given the following vehicles?
Car Boat
Lamborghini Spyder ATX 22-S
Lamborghini Spyder Mastercraft
Rolls-Royce Phantom ATX 22-S
Rolls-Royce Phantom Malibu
Rolls-Royce Phantom Mastercraft
https://advancedsqlpuzzles.com/
P a g e | 65
Puzzle #63
Promotion Codes
Identify all orders linked to a single product with a "PROMO" discount value. If an order is associated
with multiple products or multiple discounts, it should not be included in the result.
Order ID
3
• Order ID 3 meets these criteria because it has a connection to only one product. Item 1, and all
the products linked to it have a discount value of "PROMO”. On the other hand, Order ID 1 does
not meet the criteria as it is linked to two different products.
https://advancedsqlpuzzles.com/
P a g e | 66
Puzzle #64
Between Quotes
Given the following table of strings that have embedded quotes, return the result based on the
following:
1. If the string has more than two quotes, or has zero quotes, return “Error”.
2. If the string has two quotes and more than 10 characters between the quotes, return “True”.
3. If the string has two quotes and less than or equal to 10 characters between the quotes, return
“False”.
ID String Result
1 "12345678901234" True
2 1"2345678901234" True
3 123"45678"901234" Error
4 123"45678901234" True
5 12345678901"234" False
6 12345678901234 Error
ID String Result
1 "12345678901234" True
2 1"2345678901234" True
3 123"45678"901234" Error
4 123"45678901234" True
5 12345678901"234" False
6 12345678901234 Error
https://advancedsqlpuzzles.com/
P a g e | 67
Part II
Permutations, Combinations, Sequences
and Random Numbers
Building Complex Numbers Table
https://advancedsqlpuzzles.com/
P a g e | 68
Puzzle #1
Factorials
Create a numbers table of 1 through 10 and their factorial.
Number Factorial
1 1
2 2
3 6
4 24
5 120
6 720
7 5,040
8 40,320
9 362,880
10 3,628,800
https://advancedsqlpuzzles.com/
P a g e | 69
Puzzle #2
All Permutations
Create a numbers table of all permutations of n distinct numbers.
https://advancedsqlpuzzles.com/
P a g e | 70
Puzzle #3
Growing Numbers
Create a numbers table that shows all numbers 1 through n and their order gradually increasing by the
next number in the sequence.
Permutation
1
12
123
1234
12345
https://advancedsqlpuzzles.com/
P a g e | 71
Puzzle #4
Non-Adjacent Numbers
Given an ordered set of numbers (for example {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); create a result set of
permutations where no two adjacent entries are adjacent numbers.
For example…
The arrangement {1, 3, 5, 7, 9, 2, 4, 6, 8, 10} would fit the criteria as no two entries are adjacent
numbers.
The arrangement {1, 2, 4, 6, 8, 10, 3, 5, 7, 9} would not fit the criteria as 1 and 2 are adjacent numbers.
The arrangement {1, 4, 2, 6, 7, 10, 3, 5, 8, 9} would not fit the criteria as 6 and 7 are adjacent numbers.
The arrangement {1, 3, 2, 6, 7, 10, 9, 5, 8, 4} would not fit the criteria as 3 and 2 are adjacent numbers.
Permutation
2,4,1,3
3,1,4,2
https://advancedsqlpuzzles.com/
P a g e | 72
Puzzle #5
Add the Numbers Up
Given an ordered set of numbers 1 through n (for example 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), and a + or – sign at
all possible groupings; create all possible permutations and the amount in which they add up to.
Permutation Sum
123 123
1+2+3 6
1+2-3 0
1+23 24
1-2+3 2
1-2-3 -4
1-23 -22
12+3 15
12-3 9
https://advancedsqlpuzzles.com/
P a g e | 73
Puzzle #6
Permutations of 0 and 1
Create a result set of all permutations for the combination of 0 and 1 with a length of n digits.
Permutation
000
001
010
011
100
101
110
111
https://advancedsqlpuzzles.com/
P a g e | 74
Puzzle #7
Permutations 1 through 10
Display all permutations for the numbers 1 through n, displaying only the first n numbers.
Here is the expected output for all 24 permutations for the set {1,2,3,4}, displaying only the first three
numbers.
Permutation
1,2,3
1,2,4
1,3,2
1,3,4
1,4,2
1,4,3
2,1,3
2,1,4
2,3,1
2,3,4
2,4,1
2,4,3
3,1,2
3,1,4
3,2,1
3,2,4
3,4,1
3,4,2
4,1,2
4,1,3
4,2,1
4,2,3
4,3,1
4,3,2
https://advancedsqlpuzzles.com/
P a g e | 75
Puzzle #8
Four Vehicles Problem
Here is an example problem involving combinations.
There are 10 people in total; 5 are children, and 5 are adults. Only an adult can drive a vehicle.
Create a table of all possible 7,200 arrangements, assuming seating order does not matter.
We can determine there are 7,200 arrangements by using the following equation.
https://advancedsqlpuzzles.com/
P a g e | 76
Puzzle #9
Find the Spaces
Given the following table of SQL statements, provide a numbers table that displays a summary of the
space character for each SQL statement.
Statement
SELECT EmpID FROM Emps;
SELECT * FROM Trans;
https://advancedsqlpuzzles.com/
P a g e | 77
PuzzleSeat #10
Seating Chart
Given the set of integers provided in the following DDL statement, write the SQL statements to
determine the following:
• Gap start and gap ends
• Total missing numbers
• Count of odd and even numbers
Type Count
Even Numbers 8
Odd Numbers 9
https://advancedsqlpuzzles.com/
P a g e | 78
Puzzle #11
Count the Groupings
Write an SQL statement that counts the consecutive values in the Status column.
https://advancedsqlpuzzles.com/
P a g e | 79
Puzzle #12
Double or Add 1
Create a numbers table where you start with the number 1, and then double the number if the result is
less than 100, else add 1.
https://advancedsqlpuzzles.com/
P a g e | 80
Puzzle #13
Pascal’s Triangle
Solve for any position in Pascal’s Triangle.
https://advancedsqlpuzzles.com/
P a g e | 81
Puzzle #14
Josephus Problem
Solve the Josephus Problem.
https://advancedsqlpuzzles.com/
P a g e | 82
Puzzle #15
High-Low Card Game
Write a program that shuffles a standard deck of cards and plays a game of High-Low.
The game is played by receiving an initial card and then determining if the next card will be of higher or
lower value based on probability. Make a random decision of higher or lower where necessary.
https://advancedsqlpuzzles.com/
P a g e | 83
Puzzle #16
Monty Hall Simulation
Run 10,000 simulations of the Monty Hall problem to prove it is true.
https://advancedsqlpuzzles.com/
P a g e | 84
Puzzle #17
Dice Throw Game
What is the average number of dice throws needed to reach 100 points given the following rules?
• Starting at 0, for each dice throw resulting in 1 through 5, add the dice amount to your
score.
• If you roll a 6 (even on a re-roll), re-roll the dice and reduce your score by this amount. You
cannot go lower than 0 points.
https://advancedsqlpuzzles.com/
P a g e | 85
Puzzle #18
The Birthday Problem
Run 10,000 simulations of the Birthday problem to prove it is true.
https://advancedsqlpuzzles.com/
P a g e | 86
Puzzle #19
Random Walk
Perform a random walk best described by the following puzzle:
As the host of a weekly dinner gathering that includes you and seven friends, you've come up with an
interesting method to decide who will be the host for the upcoming dinner party.
After the meal, all attendees, including yourself, gather around a circular table. You, as the current host,
initiate a game by flipping a fair coin. If the coin lands heads up, you hand the coin to the person sitting
on your right; if it is tails, you pass it to your left.
The person who gets the coin then repeats the process, flipping it and passing it to their right or left
based on the result. This cycle continues until there is only one person left who has not yet received the
coin.
This last remaining individual, who has not touched the coin, is announced as the winner and is given
the responsibility of hosting the next dinner party.
Note that because you were the first to flip the coin in the game, you are immediately disqualified from
the possibility of hosting the upcoming dinner party.
Answers to the puzzles are located in the following GitHub repository.
AdvancedSQLPuzzles/Advanced SQL Puzzles
https://advancedsqlpuzzles.com/
P a g e | 87
Puzzle #20
Markov Chain
Perform a Markov Chain best described by the following puzzle:
In Probability Land, on a sunny day, there is an equal probability of the next day being sunny or rainy.
On a rainy day there is a 70% chance it will rain the next day, and a 30% chance it will be sunny the next
day.
https://advancedsqlpuzzles.com/
P a g e | 88
Puzzle #21
100 Prisoners Riddle
Run 10,000 simulations of the 100 Prisonsers Problem to prove it is true.
https://advancedsqlpuzzles.com/
P a g e | 89
Puzzle #22
Non-Overlapping Sets
You are given a table of orders, their line items, and the cost associated with each line item. Your task is
to write an SQL statement that finds the maximum number of non-overlapping sets of line items for
each order, with the condition that the total cost of line items in each set must be greater than or equal
to $10. A set can be no greater than 2 records.
• Order ID 1 has 2 possible combinations of line items that total over $10, each with 3 sets.
• Order ID 2 has 1 possible combination of line items that total over $10, which has 3 sets.
• Order ID 3 has 0 possible combinations of line items that total over $10.
• Order ID 4 has 1 possible combination of line items that total over $10, which has 1 set.
• Order ID 5 has 3 possible combinations of line items that total over $10, each with 2 sets.
https://advancedsqlpuzzles.com/
P a g e | 90
THE END
https://advancedsqlpuzzles.com/