Skip to content
Advertisement

How to print NULL when table has no rows in SQL Server?

I have a table with a named column but no rows.

Col1

I wanted to write a select similar to:

SELECT TOP(1)
    NULLIF(Col1, '')
FROM table

I wanted to get a result like:

   Col1
1  NULL

But instead I get just the Col1 name and no results. How can I get a table with NULL as the result?

Advertisement

Answer

You can use aggregation:

    select max(col1)
    from t;

An aggregation query with no group by or having always returns one row. If there are no rows then the value is (generally) NULL for aggregation functions (the exception is COUNT()).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement