SQL Sub-query or INNER-JOIN?

后端 未结 4 958
执笔经年
执笔经年 2021-01-13 05:38

I\'ve the two following queries:

declare @UserId as int
set @UserId = 1

-- Query #1: Sub-query
SELECT
    u.[Id] ,
    u.[Name] ,
    u.[OrgId] AS Organizat         


        
4条回答
  •  [愿得一人]
    2021-01-13 06:34

    The best thing you can do is try both and compare what gives you the best performance. It's difficult to second guess what the query optimiser will do (you could write 2 different queries that actually end up being optimised to the same execution plan).

    To compare performance fairly, you should ensure you try them from a level playing field by clearing down the execution plan and data cache before trying each one. This can be done using the following commands, though only do this on a development/test db server:

    DBCC FREEPROCCACHE
    DBCC DROPCLEANBUFFERS
    

    The approach I usually take is to run each query 3 times, with SQL Profiler running so I can monitor the duration, reads, CPU and writes of the query which I then base my decision on.

    e.g.
    1) clear cache using above commands
    2) run query and record stats
    3) clear cache
    4) run query again
    5) run query again (this will use cached execution plan/data)

    Then repeat for the second query to compare.

提交回复
热议问题