Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace empty value in SQL query

I’ve got the next query

Select LAST_NAME from test.[USER]
        Where ID = (Select test_support from test.UPGRADE
        Where KEYED_NAME Like '%abc%'
        and STATE = 'Active')

The result like:

 LastName1

But if the Keyed_Name doesn’t exist, the result is empty. I get the empty column:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

How to change it to receive some other value like ‘-‘ instead empty.

So if the query result is empty, I will receive:

enter image description here

I tried next query

DECLARE @EmptyString NVARCHAR( 10 ) = ''; 
        Select CASE WHEN LAST_NAME <> @EmptyString THEN LAST_NAME ELSE '-' END
        from test.[USER]
        Where ID = (Select test_support from test.UPGRADE
        Where KEYED_NAME Like '%abc%'
        and STATE = 'Active')

but it works only for case when the string is not empty.

>Solution :

We can put the whole query in COALESCE and take ‘-‘ if the query doesn’t find records:

SELECT COALESCE(
(SELECT LAST_NAME from users
        Where ID = (SELECT test_support FROM upgrade
        Where KEYED_NAME LIKE '%abc%'
        AND state = 'Active')), '-') AS LAST_NAME;

Try out here: db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading