Query optimization

ooj-4672 60 Reputation points
2023-06-23T08:23:27.9166667+00:00

Hello.

I have such a query. But it looks a bit cumbersome, and I might need to nest the query a few more times. Is there a way to optimize it?

select * from
(select *,row_number()over(partition by deptno order by eid) as rownumber from
(select * from MyTable where Left(op,2) = 'al' ) s ) t where rownumber < 4;

Any help is appreciated.

SQL Server Other
{count} votes

Accepted answer
  1. Anonymous
    2023-06-23T08:30:11.4933333+00:00

    Hi @ooj-4672

    You can learn to use CTE. It can make your code intuitive.

    https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver16

    Just like this.

    ;with T1 as(
      select * from MyTable where Left(op,2) = 'al' 
    ),T2 as(
      select *,row_number()over(partition by deptno order by eid) as rownumber from T1)
    select * from T2 where rownumber < 4;
    

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-06-23T08:34:32.07+00:00

    I think a query like this would benefit from this index:

    CREATE INDEX MyIndex ON MyTable(op, deptno, eid)
    

    And, very important, the condition

    left(op,2) = 'a1'
    

    should be rewritten as

    op LIKE 'a1%'
    

    The optimizer is not able to understand that the expression with left is good for seeking the index.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.