Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6691591
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T05:46:10+00:00 2026-05-26T05:46:10+00:00

How can I get SQL Server to return the first value (any one, I

  • 0

How can I get SQL Server to return the first value (any one, I don’t care, it just needs to be fast) it comes across when aggregating?

For example, let’s say I have:

ID      Group
1       A
2       A
3       A
4       B
5       B

and I need to get any one of the ID’s for each group. I can do this as follows:

Select 
max(id)
,group 
from Table 
group by group

which returns

ID      Group
3       A
5       B

That does the job, but it seems stupid to me to ask SQL Server to calculate the highest ID when all it really needs to do is to pick the first ID it comes across.

Thanks

PS – the fields are indexed, so maybe it doesn’t really make a difference?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T05:46:11+00:00Added an answer on May 26, 2026 at 5:46 am

    There is an undocumented aggregate called ANY which is not valid syntax but is possible to get to appear in your execution plans. This does not provide any performance advantage however.

    Assuming the following table and index structure

    CREATE TABLE T
    (
    id int identity primary key,
    [group] char(1) 
    )
    
    CREATE NONCLUSTERED INDEX ix ON T([group])
    
    INSERT INTO T
    SELECT TOP 1000000 CHAR( 65 + ROW_NUMBER() OVER (ORDER BY @@SPID) % 3)
    FROM sys.all_objects o1, sys.all_objects o2, sys.all_objects o3
    

    I have also populated with sample data such that there are many rows per group.

    Your original query

    SELECT MAX(id),
           [group]
    FROM   T
    GROUP  BY [group]  
    

    Gives Table 'T'. Scan count 1, logical reads 1367 and the plan

      |--Stream Aggregate(GROUP BY:([[T].[group]) DEFINE:([Expr1003]=MAX([[T].[id])))
           |--Index Scan(OBJECT:([[T].[ix]), ORDERED FORWARD)
    

    Rewritten to get the ANY aggregate…

    ;WITH cte AS
    (
    SELECT *,
            ROW_NUMBER() OVER (PARTITION BY [group] ORDER BY [group] ) AS RN
    FROM T)
    SELECT id,
           [group]
    FROM    cte     
    WHERE RN=1
    

    Gives Table 'T'. Scan count 1, logical reads 1367 and the plan

      |--Stream Aggregate(GROUP BY:([[T].[group]) DEFINE:([[T].[id]=ANY([[T].[id])))
           |--Index Scan(OBJECT:([[T].[ix]), ORDERED FORWARD)
    

    Even though potentially SQL Server could stop processing the group as soon as the first value is found and skip to the next one it doesn’t. It still processes all rows and the logical reads are the same.

    For this particular example with many rows in the group a more efficient version would be a recursive CTE.

    WITH    RecursiveCTE
    AS      (
            SELECT TOP 1 id, [group]
            FROM T
            ORDER BY [group]
            UNION   ALL
            SELECT  R.id, R.[group]
            FROM    (
                    SELECT  T.*,
                            rn = ROW_NUMBER() OVER (ORDER BY (SELECT 0))
                    FROM    T
                    JOIN    RecursiveCTE R
                            ON  R.[group] < T.[group]
                    ) R
            WHERE   R.rn = 1
            )
    SELECT  *
    FROM    RecursiveCTE
    OPTION  (MAXRECURSION 0);
    

    Which gives

    Table 'Worktable'. Scan count 2, logical reads 19
    Table 'T'. Scan count 4, logical reads 12
    

    The logical reads are much less as it retrieves the first row per group then seeks into the next group rather than reading a load of records that don’t contribute to the final result.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Question: I can get the SQL Server database language by querying: SELECT @@language And
How can I get a SQL dump of a SQL Server 2008 database? That
I'm using SQL Server 2005 and would like to know how I can get
Where can I get the 64 bit bootstrapper for SQL Server Express 2005 64
How can I get the list of available databases on a SQL Server instance?
In SQL server you can use the DATENAME function to get the day of
I know you can get the SQL, but it's paramterized without the parameters being
How can you get the SQL for a Django model's .save(), i.e. from django.db
I'm simply trying to get data from two sql server db tables using ado.net
I get a problem with SQL Server 2005, where a stored procedure seems to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.