Rajat Saini
Rajat Saini

Reputation: 557

Optimizing SQL query

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?

Upvotes: 2

Views: 123

Answers (1)

AnandPhadke
AnandPhadke

Reputation: 13506

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

Upvotes: 1

Related Questions