0

I'm trying to find a pure MySQL way of doing this to avoid a lot of repeat / similar PHP scripts.

Say I select a single row in my table it could look like this:

| col1 | col2 | col3 | col4 | col5 | col6 |
| abc  |b b a | '%kj |  jh  |      |      |

I want to COUNT how many columns in that row are not empty. So in this example it is 4.

I came up with a solution where I run a count query where col1 is not empty for id=X, and then run this 6 times and add up the results. However I feel this is surely very inefficient and I couldn't think of a better way of doing it.

Does anybody have any idea how I could make that more efficient?

2 Answers 2

2

Try this

SELECT 
COUNT(NULLIF(col1,'')),
COUNT(NULLIF(col2,'')),
COUNT(NULLIF(col3,'')),
COUNT(NULLIF(col4,'')),
COUNT(NULLIF(col5,'')),
COUNT(NULLIF(col6,''))
FROM yourTableName

I tried it in my local phpMyAdmin, works well. :)

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

5 Comments

Perfect! Thank you, I'll accept the answer when I can in 5 minutes :)
Oh just a small one you need to add a comma after the COUNT col5 line to make the syntax correct for anyone that comes here to copy paste
This does not do what you asked for, this counts vertically and you asked to count not null values in the same row.
It worked fine just added a WHERE id=x condition at the end which works well for me
Also the NULLIF is redundant, COUNT does not count null values anyway. And this does not return 4. It returns 1,1,1,1,0,0.
0

To count not null values in each row use:

SELECT 
CASE WHEN col1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN col2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN col3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN col4 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN col5 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN col6 IS NOT NULL THEN 1 ELSE 0 END 
FROM my_table;

Comments

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.