In this puzzle, we're going to learn how to find a gap in a sequence using SQL Server. I was recently reviewing my bank statement and noticed that they flagged the start of a missing check number with ***
s.
I figured with would be a great example for a SQL puzzle as there are many ways you could solve it.
Solving puzzles is a great way to learn SQL. Nothing beats practicing what you've learned. Once you have figured out the puzzle, post your answer in the comments so we can all learn from one another. We also discuss the puzzle and more in Essential SQL Learning Group on Facebook. Be sure to find us there!
SQL Puzzle Question
You've been asked to analyze some checking account registers and indicate where there is a gap in a Sequence of check numbers.
Here is the table structure:
DECLARE @CheckRegister TABLE
(
AccountNumber Varchar(10),
CheckNumber Varchar(10)
)
If the checks are numbered 101, 102, 104, 105 then you'll want to indicate a gap starts at 3. In fact, you'll want to indicate this place appending ***
to the check number. Below is an example:
Can you come up with a query that displays the check register and the gaps?
You can use this script to define the table and sample data.
Good luck!
How to Find a Gap in a Sequence Answer
I thought this puzzle was going to be hard to answer. I thought about using joins and comparing the joined values to see if there were gaps and I even thought I might try using a recursive CTE to find gaps, but once I thought about it for a bit, I realized I could use window functions.
There is this really cool function called LEAD. It allows you to look at a value from the next row in a query result.
All I needed to do to find a gap in a sequence was to define a partition and then use LEAD to see whether the next number was more than one greater than the current check number. If so, we have a gap.
Here is the SQL I used to find the current and next CheckNumber
.
SELECT AccountNumber,
CheckNumber,
Lead(CheckNumber, 1) OVER (PARTITION BY AccountNumber ORDER BY CheckNumber) NextCheckNumber
FROM @CheckRegister
It's crazy simple, that is once you understand how partitions work. :)
Partitions can be used to segment the data. In our example, we use it to separate the check numbers by account numbers.
To make it easy to separate the logic of obtaining the next value and then comparing it to the current, I used a common table expression.
The CTE is used to get the next value. This result set is then used in the final query alongside a case
statement to detect the gap.
If a gap is detected, then ***
is appended to the CheckNumber
value.
Below is the final query:
WITH CTE_CheckRegister (AccountNumber, CheckNumber, NextCheckNumber)
AS
(
SELECT AccountNumber,
CheckNumber,
Lead(CheckNumber, 1) OVER (PARTITION BY AccountNumber ORDER BY CheckNumber) NextCheckNumber
FROM @CheckRegister
)
SELECTÂ Â AccountNumber,
CASE
WHEN NextCheckNumber is NULL THEN CheckNumber
WHEN (CheckNumber = NextCheckNumber - 1) THEN CheckNumber
ELSE CheckNumber + '***'
END as CheckNumber
FROMÂ Â Â Â CTE_CheckRegister
ORDER BY AccountNumber, CheckNumber
The CTE is in bold.
As you can see, it is straight forward. I think it is easy to read.
What type of solution did you come up with? Please post your answer in our comments section.
The post How to Find a Gap in a Sequence using SQL SERVER appeared first on Essential SQL.
Hello my name is Kris. I’m here because I am passionate about helping non-techie people to overcome their fear of learning SQL.
I know what it is like to not know where to start or whether the time spent learning is worth the effort. That is why I am here to help you to:
- Get started in an easy to follow step-by-step manner.
- Use your time wisely so you focus on what is important to learn to get the most value from your time.
- Answer your questions. Really! Just post a comment and I’ll respond. I’m here to help.
It wasn’t long ago that I was helping a colleague with some reporting. She didn’t know where to start and soon got overwhelmed and lost as she didn’t know SQL.
I felt really bad, as she was under pressure to get some summary information to her boss, the built-in reports were falling short, and to make them better would require her to know SQL. At that time that seemed impossible! It in dawned on me, it doesn’t have to be that way.
Then I discovered a way for anyone with the desire to easily learn SQL. I worked with my co-worker, started to teach her what I learned and soon she was able to write reports and answer her boss’ questions without getting stressed or ploughing hours into manipulating data in Excel.
It hasn’t always been easy. Sometimes the information seems abstract or too conceptual. In this case I’ve found out that a visual explanation is best. I really like to use diagrams or videos to explain hard-to-grasp ideas.
Having video, pictures, and text really help to reinforce the point and enable learning.
And now I want to help you get the same results.
The first step is simple, click here http://www.essentialsql.com/get-started-with-sql-server/