anonymous6
anonymous6

Reputation: 29

Count the number of columns populated in a row

I have a table of this style in sql:

id FirstName LastName Age
1 John Williams 25
2 Anne 23

I want to count the number of columns filled in each row, as shown below.

id FirstName LastName Age PopulatedColumns
1 John Williams 25 4
2 Anne 23 3

Does anyone know how to make a script that does this count in sql? But I didn't want to specify the name of the columns, because I have a very large table and it is not practical to put the name of all the columns. Is there a way to do this agnostic? Without putting names?

Upvotes: 0

Views: 122

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270411

IN MySQL, you can use arithmetic:

select t.*,
       ( (id is not null) + (firstname is not null) + (lastname is not null) + (age is not null)
       ) as populated_columns
from t;

Upvotes: 2

Related Questions