SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Prev and Next Row Without RowNumber


Prev and Next Row Without RowNumber

Author
Message
dwain.c
dwain.c
SSCertifiable
SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)

Group: General Forum Members
Points: 7321 Visits: 6431
No ROW_NUMBER() necessary.

If you know the largest value stored in each of the 3 columns of interest, you could create a COMPUTED PERSISTED column that is INDEXed and do it something like this:


CREATE TABLE #Invoice_t(
[Cost_Center_code] [int] NOT NULL,
[Payment_code] [int] NOT NULL,
[INV_No] [int] NOT NULL,
[Composite_key] AS (RIGHT('0000000000'+CAST([Cost_Center_code] AS VARCHAR(9)),10) +
RIGHT('0000000000'+CAST([Payment_code] AS VARCHAR(9)),10) +
RIGHT('0000000000'+CAST([INV_No] AS VARCHAR(9)),10)) PERSISTED,
CONSTRAINT [PK_Invoice_t] PRIMARY KEY CLUSTERED
(
[Cost_Center_code] ASC,
[Payment_code] ASC,
[INV_No] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE INDEX composite_index
ON #Invoice_t ([Composite_key]);

INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (1, 1, 1)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (1, 1, 2)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (1, 1, 3)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (2, 1, 1)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (2, 1, 2)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (2, 2, 1)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (2, 2, 2)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (1, 2, 1)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (3, 2, 1)
INSERT #Invoice_t ([Cost_Center_code], [Payment_code], [INV_No]) VALUES (3, 1, 1)
---------------------------------------------------------------

SELECT *
FROM #Invoice_t;

SELECT a.Cost_Center_Code, a.Payment_code, a.Inv_NO
,Prev.Cost_Center_Code, Prev.Payment_code, Prev.Inv_NO
,Next.Cost_Center_Code, Next.Payment_code, Next.Inv_NO
FROM #Invoice_t a
OUTER APPLY (
SELECT TOP 1 Cost_Center_Code, Payment_code, Inv_NO
FROM #Invoice_t b
WHERE b.Composite_key < a.Composite_key
ORDER BY Composite_key DESC) Prev
OUTER APPLY (
SELECT TOP 1 Cost_Center_Code, Payment_code, Inv_NO
FROM #Invoice_t b
WHERE b.Composite_key > a.Composite_key
ORDER BY Composite_key ASC) Next
ORDER BY a.Cost_Center_Code, a.Payment_code, a.Inv_NO;
GO
DROP TABLE #Invoice_t;




Note that the execution plan this produced for the admittedly tiny sample data set showed two INDEX seeks and a CLUSTERED INDEX scan.

You don't even really need the COMPUTED column, but it does make the final query a bit more terse.

Edit: Note that originally I overall ordered by Composite_key which generated a NON-CLUSTERED INDEX scan instead of the above stated CLUSTERED INDEX scan.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
patrickmcginnis59 10839
patrickmcginnis59 10839
SSCommitted
SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)SSCommitted (1.8K reputation)

Group: General Forum Members
Points: 1770 Visits: 5520
Khalid Hanif-458693 (7/16/2013)
patrickmcginnis59 10839 (7/16/2013)
keebler96 (7/16/2013)
The order of the previous and the next rows should be ordered just like the SQL has inserted according to the primary keys.


This is the problem. There is no default order by in SQL Server. You MUST order your data by the use of the order by clause. You must define the proper order for your result set.

Just because you inserted records in a particular order does not mean that the table stores them in that order.

From what you have provided us, you have to use Row_Number, and you have to order your composite primary key in the way you want the rows to be ordered.

Hope that helps.


I was able to get the previous and next rows with the SQL I posted and not use row number. I suspect the row number version would be more concise because I had to build up the comparison criteria to account for all keys.


I was not able to get the Previous or the next row, the where condition should include all the columns.
Cost_Center_Code,Payment_Code,Inv_No.

Can you check your code with the updated OP code.


Never mind, it was my mistake, I was only working with one row and trying to take that route for a query doesn't work well at all compared to using row numbers.

to properly post on a forum:
http://www.sqlservercentral.com/articles/61537/
Khalid Hanif-458693
Khalid Hanif-458693
Grasshopper
Grasshopper (12 reputation)Grasshopper (12 reputation)Grasshopper (12 reputation)Grasshopper (12 reputation)Grasshopper (12 reputation)Grasshopper (12 reputation)Grasshopper (12 reputation)Grasshopper (12 reputation)

Group: General Forum Members
Points: 12 Visits: 50
Dwain,

Thanks for the great idea, instead of the computed column, I used the bigint column with all the values.

working like a charm with index seek.
ChrisM@Work
ChrisM@Work
SSCoach
SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)

Group: General Forum Members
Points: 16302 Visits: 19551
Khalid Hanif-458693 (7/18/2013)
Dwain,

Thanks for the great idea, instead of the computed column, I used the bigint column with all the values.

working like a charm with index seek.


Khalid, I'd be fascinated to see the actual execution plan for your solution, if you have the time to post it up as an attachment. Thanks!

“Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Exploring Recursive CTEs by Example Dwain Camps
dwain.c
dwain.c
SSCertifiable
SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)SSCertifiable (7.3K reputation)

Group: General Forum Members
Points: 7321 Visits: 6431
Khalid Hanif-458693 (7/18/2013)
Dwain,

Thanks for the great idea, instead of the computed column, I used the bigint column with all the values.

working like a charm with index seek.


You're welcome. Email notifications must not be working again.

Although, I must confess that like Chris I am curious how you managed an INDEX SEEK without the computed column.


My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!

My thought question: Have you ever been told that your query runs too fast?

My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.


Need to UNPIVOT? Why not CROSS APPLY VALUES instead?
Since random numbers are too important to be left to chance, let's generate some!
Learn to understand recursive CTEs by example.
Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search