How to set a default row for a query that returns no rows?

后端 未结 11 1444
青春惊慌失措
青春惊慌失措 2020-12-03 06:43

I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I\'m only returning a single column from this particular table

11条回答
  •  情深已故
    2020-12-03 06:58

    One approach for Oracle:

    SELECT val
    FROM myTable
    UNION ALL
    SELECT 'DEFAULT'
    FROM dual
    WHERE NOT EXISTS (SELECT * FROM myTable)
    

    Or alternatively in Oracle:

    SELECT NVL(MIN(val), 'DEFAULT')
    FROM myTable
    

    Or alternatively in SqlServer:

    SELECT ISNULL(MIN(val), 'DEFAULT')
    FROM myTable
    

    These use the fact that MIN() returns NULL when there are no rows.

提交回复
热议问题