Click here to Skip to main content
15,885,366 members
Articles / Productivity Apps and Services / Sharepoint

How to Find a Gap in a Sequence using SQL SERVER

Rate me:
Please Sign up or sign in to vote.
3.91/5 (6 votes)
19 Mar 2017MIT3 min read 14.3K   4   4
How to find a gap in a sequence using SQL Server

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:

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

gap in a sequence

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.

SQL
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. :)

Image 2

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:

SQL
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.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Easy Computer Academy, LLC
United States United States
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/

Comments and Discussions

 
PraiseNeat! Pin
PeejayAdams21-Mar-17 1:48
PeejayAdams21-Mar-17 1:48 
GeneralRe: Neat! Pin
Steven121821-Mar-17 13:14
professionalSteven121821-Mar-17 13:14 
Also, both LEAD and LAG are available in Oracle too.
QuestionChar set Pin
Nelek19-Mar-17 19:58
protectorNelek19-Mar-17 19:58 
QuestionAvailability of Lead Function Pin
iamalik19-Mar-17 19:55
professionaliamalik19-Mar-17 19:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.