2

I have been running a sql query for large number of rows in a table. The structure of query is similar to the following query.

SELECT id FROM
(
SELECT
     id,(ROW_NUMBER() OVER (ORDER BY id)) AS Row 
FROM 
     <table>
)
temp_table WHERE Row BETWEEN 1 AND 50

I am using paging at the UI so that I need fifty records in a single fetch. My concern is that, I am fetching all the records and then select 50 from them isnt there a way that allows me to select only those records that I truly need. Please note that this a simplified query the original query is very complex and have lot of joins. Is there any standard way of implementing queries that support paging?

1 Answer 1

1

What I suggest here is:

1.Create a indexed view(view_sample) with the query

SELECT
     id,(ROW_NUMBER() OVER (ORDER BY id)) AS Row 
FROM 
     <table>

2.Now create an index (clustered) on row

3.Select id from view_sample where Row BETWEEN 1 AND 50

Sign up to request clarification or add additional context in comments.

5 Comments

I am generating query dynamically at run time so the order by column can be changed any time. The whole query is dynamic in nature so creating indexes is not easy at all.
which query are you generating dynamically?
Here I am asking you to create the index on column row which you are populating by ROW_NUMBER and I guess this column will always be there
No this column wont always be there. Actually there are 6-7 columns that I need to fetch and this index column could be any one of them. Further these columns could be resultant of joins applied on different tables. This query is just the format to make query understandable. I was looking for a solution that could help me save time wasted on fetching those columns which I dont need. I really appreciate your help but indexes are not the option for me this time.
you mean you cant use indexes? and can you pls post your actual query bcos your sample query is not good enough to get your actual problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.