1

I have this table :

id  col1  col2  col3
 1   ''    ''    bla
 2   ''    bla   bla 
 3   bla    ''    ''

I want to build a query that will retun how much cols are not empty for each id.

so the result would be :

id  sum  
 1   1
 2   2
 3   1

How to do that ?

1 Answer 1

2
select id, ((col1 != '') + (col2 != '') + (col3 != '')) as non_empty_count
from table;

Uses a trick where boolean true=1 and false=0 - so for each column non empty value ads 1 to count. Can be seen in action at http://sqlfiddle.com/#!9/751df2/5

Sign up to request clarification or add additional context in comments.

2 Comments

I like this answer, I didnt know that boolean in Mysql is 0/1
@54l3d yes, nice for "sum(is_active = 1) as active_count" too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.