Return null values if there is no record for top n selected

sudhir bharti 1 Reputation point
2020-08-20T16:40:24.183+00:00

I am trying to get the top ‘n’ rows from the following query:
SELECT TOP 1 ImageName FROM (SELECT TOP 5 * FROM ClientKeywordMedia where keywordid=1147 ORDER BY ID) z ORDER BY ID DESC
The above query is working fine if top 5 is used in subquery as there is only 5 records in subquery.
The problem occurred when I am trying to run the following query
SELECT TOP 1 ImageName FROM (SELECT TOP 7 * FROM ClientKeywordMedia where keywordid=1147 ORDER BY ID) z ORDER BY ID DESC
Its returning the 5th rows values as 7th row, which is incorrect, because there are only 5 rows for the subquery.
Any ideas how to return false or null record if there are only 5 records if we run top 7

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,640 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 117.6K Reputation points
    2020-08-20T18:11:24.543+00:00

    Try the next query too:

    select ImageName from ( select *, ROW_NUMBER() over (order by ID) as rn from ClientKeywordMedia where keywordid=1147) as t where t.rn = 7
    

    It does not return any record if the row does not exist.

    1 person found this answer helpful.
    0 comments No comments

  2. Guoxiong 8,206 Reputation points
    2020-08-20T17:28:13.81+00:00
    ;WITH CTE AS (
        SELECT TOP 7 ID, ImageName
        FROM ClientKeywordMedia 
        where keywordid=1147 
        ORDER BY ID
    )
    
    SELECT TOP 1 CASE WHEN (SELECT COUNT(*) FROM CTE) = 7 THEN ImageName ELSE NULL END AS ImageName 
    FROM CTE
    ORDER BY ID DESC;
    
    0 comments No comments

  3. MelissaMa-MSFT 24,201 Reputation points
    2020-08-21T01:53:12.383+00:00

    Hi sudhirbharti,

    Please find another method from below:

    select top 1 ImageName FROM (
        SELECT TOP 7 isDummy,ID,keywordid,ImageName FROM (
            SELECT 1 isDummy,* FROM ClientKeywordMedia where keywordid=1147 
            UNION ALL 
            SELECT 0 isDummy,t1.* FROM ClientKeywordMedia T1
                  RIGHT JOIN INFORMATION_SCHEMA.COLUMNS ON t1.id = -1000
        )A ORDER BY isDummy desc
    ) B  ORDER BY isDummy ,ID DESC 
    
    /*
    ImageName
    NULL
    */
    

    If the response is helpful, please click "Accept Answer" and upvote it.

    Best regards
    Melissa

    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.