user517406
user517406

Reputation: 13773

Show field dependent on whether other field contains data

Is it possible in an SQL query to only show a field if another field has data? For example, if Field1 <> '', then show the value in Field2 else don't show the value?

Upvotes: 1

Views: 154

Answers (4)

onedaywhen
onedaywhen

Reputation: 57023

Take a look at Standard SQL functions COALESCE() and NULLIF():

COALESCE(NULLIF(Field1, ''), Field2)

Upvotes: 0

Alex_L
Alex_L

Reputation: 2654

if 'has no data' means the empty string (''), you need to use this statement:

SELECT Filed2 FROM Table1 WHERE Filed1<>''

If 'no data' means NULL value, you need use

SELECT Filed2 FROM Table1 WHERE NOT (Filed2 IS NULL)

Upvotes: 0

Frank Schmitt
Frank Schmitt

Reputation: 30775

Sure (this works in Oracle and SQLite):

select 
  field1,
  (case 
     when field1 is null then null
     else field2
   end) field2_wrapped
from my_table

Upvotes: 0

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

It can be done using a case statement. (At least in SQL Server)

select case when Field1 <> '' 
            then Field2  
       end as Field2
from YourTable

Upvotes: 2

Related Questions