Display a column only if it is not null
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 appea开发者_开发问答r at all in my result.
Is there a way to express this condition in SQL?
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.
No, it is not...
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
.
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.
精彩评论