0

I need to count how many empty fields a row contains in an SELECT COUNT(*) statement

My row holds 11 fields and i only need to count in 4 of them. In two of the columns i need to count if they are empty (NOT NULL), and in two i need to count if they hold the value 0

My statement so far:

SELECT COUNT(*) AS subjectcount FROM Tabel WHERE (col1 OR col2) =0 OR (col3 OR col4) = '' AND id=1

Lets say that
col1 = 0
col2 = 1
col3=' '
col4='something'
my sum should then be 2, since two of the fields holds the value im searching for.

2 Answers 2

1

MySQL has a neat way of treating booleans as ones or zeroes (for true and false values, respectively) when used in a numeric context. So you could do something like this:

SELECT (col1 = 0) + (col2 = 0) + (col3 = '') + (col4 = '')
FROM   tabel
Sign up to request clarification or add additional context in comments.

2 Comments

And then GROUP BY id to get this count for each row.
@ethan no group by is needed - just need to remove the sum call to get a result per row (edited in, thanks!)
0
WHERE 0 in (col1, col2)
  OR '' in (col3, col4)

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.