Search code examples
sqlsql-serverssms-2012

SQL left outer join with nested select optimisation


I am querying SQL Server 2012.

I have a left outer join onto a large result set, that looks like the following:

Data
LEFT OUTER JOIN
(
    SELECT
        MemberID
        ,MIN(Date)
    FROM
        Tables
    GROUP BY
        MemberID
) T
ON Data.MemberID = T.MemberID

Where Data is already a large query (tens of thousands of rows returned).

My question is: Is this nested select query evaluated only for the MemberIDs I already have in "Data"? This seems to have slowed the sproc down fairly significantly, is there a more standard way of doing this? Or is this just to be expected?

Thanks in advance.


Solution

  • No, the subquery is evaluated for all the rows.

    If you want the first row for something, then do:

    row_number() over (partition by Memberid order by Date) as seqnum
    

    And then use:

    where seqnum = 1