0

Suppose I have a Select Statement like this...

select a,b,c 
from table1 where d='' 
union 
select a,b,c 
from table1 where d>='' and e='' order by f asc,g desc offset 0 rows 
fetch next 100 rows only 

Lets say I need both the select with the union but the thing is when I do order by with non-primary keys i.e. with f and g it takes a lot of time to execute the query. But when I do the order by with primary keys say a and b it executes faster.

Please suggest me a way where I can execute the above query faster with order by of non-primary keys.

TomTom
  • 61,059
  • 10
  • 88
  • 148
user3085636
  • 15
  • 1
  • 7

1 Answers1

0

Personally I'd start by removing the UNION leaving you something like:

SELECT
    a,b,c 
FROM
    table1 
WHERE 
    ISNULL(d,'') = ''
    OR ((NOT ISNULL(d,'') = '') AND e='')
ORDER BY 
    f ASC
    , g DESC
OFFSET 0 rows FETCH NEXT 100 ROWS ONLY

I'd then review the indexes assigned to the database and probably add f and g as indexed, if you're not confident with indexing, I'd suggest either doing a (insert search engine name here) to find suitable articles or even review other Stack Overflow questions such as this one. If you have the facility you should consider using an SQL Profiler to determine where indexes would benefit your database and improve its performance.

Another thing worth looking at is the efficiencies of your paging method, if you're only ever wanting the first 100 results you could do something like SELECT TOP 100... or you could look at this article which details efficient paging. I've not used OFFSET n ROWS SELECT NEXT 100 ROWS ONLY myself but have used ROW_NUMBER()OVER() (see here) and not had too many problems myself.

Community
  • 1
  • 1
talegna
  • 2,407
  • 2
  • 19
  • 22