views:

39

answers:

4

I need to display a particular column in my SQL result only if it is not null. If it is null, I don't want that column to appear at all in my result. Is there a way to express this condition in SQL?

+1  A: 

No, it is not...

zerkms
There is no way?
StackOverflowNewbie
Yes, there is no way. Select has always fixed number of columns to return that is unconditional.
zerkms
+1  A: 

SQL doesn't generally let you reason about properties of entire columns. Conditions are on properties of rows. So there's no way to say "if all the values in this set of this column are null...". However, you can trivially restrict yourself to rows that lack the property.

If you want to show a column only when it is not null for every row, you could do a COUNT(*) WHERE ... your general condition ... AND that_column IS NULL and then redo the query, including the column if the first result was 0 and excluding it otherwise. But I'm not sure why you'd want to do such a thing.

Seamus Campbell
+2  A: 

This wouldn't make sense because a query may return multiple rows. One row may have a value for the column in question and the next may not have a value. Then a conditional column would create a structural inconsistency between returned rows.

Greg Harman
+1  A: 

It's not possible, and really unnecessary. You'll need to have a fixed number of columns, there's just no other way. But that isn't really your problem, you don't want that at all!

Queries are just to retrieve the data, not for the representation of the data. You should just retrieve it and hide the column if all the values are null.

GuidoH