Share via

Row number issue

Scott Huang 3,511 Reputation points
2022-08-10T09:55:55.48+00:00

Hi,
Is there one example for that I want to ensure only one row is returned for the select statement?

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


3 answers

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2022-08-10T10:25:45.343+00:00

    Check one example:

    select top(1) * from MyTable

    Usually you will also use order by to return the first or the last row from a table.

    Was this answer helpful?

    3 people found this answer helpful.
    0 comments No comments

  2. LiHong-MSFT 10,061 Reputation points
    2022-08-11T01:55:54.203+00:00

    Hi @Scott Huang

    I want to ensure only one row is returned for the select statement

    You can use TOP(1) to select only one row of data and edit the 'order by' clause according to different needs.
    Check this example:

    CREATE TABLE ForgeRock ([productName] varchar(13), [description] varchar(57), [amount] INT);  
      
    INSERT INTO ForgeRock VALUES  
    ('OpenIDM', 'Platform for building enterprise provisioning solutions',100),  
    ('OpenAM', 'Full-featured access management',200),  
    ('OpenDJ', 'Robust LDAP server for Java',300);  
      
    --Select one row that has the least amount  
    SELECT TOP(1)* FROM ForgeRock  
    ORDER BY amount ASC;  
      
    --Select one row that has the biggest amount  
    SELECT TOP(1)* FROM ForgeRock  
    ORDER BY amount DESC;  
      
    --select Random One row in a table  
    SELECT TOP(1)* FROM ForgeRock  
    ORDER BY NewId();  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. 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.

    Was this answer helpful?

    0 comments No comments

  3. Jingyang Li 5,901 Reputation points Volunteer Moderator
    2022-08-10T14:49:01.823+00:00

    You can use a row_number windown function to define your first row and retrieve it.
    Here are some examples:
    select * from (
    select *, row_number()Over(order by somecolumn asc) rn
    from yourtable) t
    where rn=1

    --or  
      
    select * from (  
    select *, row_number()Over(order by somecolumn  desc)  rn   
    from yourtable) t  
    where rn=1  
    

    Was this answer helpful?

    0 comments No comments

Your answer

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