0

I am trying to write a query on a column in a table. In column "text" I can have values of either 5 or 10 or null. I want to get count of number of rows in the table for 5 or 10 or null. I wrote following query it is not working properly

select COUNT(*) from t_test
select COUNT(text) from t_test where text=5
select COUNT(text) from t_test where text=10
select COUNT(text) from t_test where text=null 

I can get first three select statements values but the last one with null returns zero while there are rows with null in it. How to write this query? Thanks

1
  • 1
    You want text IS null Commented Jul 8, 2013 at 1:16

2 Answers 2

3

You should just use conditional summation:

select count(*),
       sum(case when text = '5' then 1 else 0 end) as Num_5,
       sum(case when text = '10' then 1 else 0 end) as Num_10,
       sum(case when text is null then 1 else 0 end) as Num_Null
from t_test;

This is assuming that a field called text is stored as a character string, so the constants are put in quotes. If it is really a number, first I'd be curious why it is called text. In that case, you can dispense with the single quotes.

In your case, the last one doesn't work because count(text) counts non-null values. But the where clause only keeps NULL values. For that one, you should use count(*). The correct query would be:

select count(*) from t_test where text is null;
Sign up to request clarification or add additional context in comments.

Comments

2

What you need for that final query is:

select COUNT(*) from t_test where text is null

Notice:

  • COUNT(*) rather than COUNT(TEXT) which is null, rendering no values
  • is null rather than =null

Your final set of queries is thus:

select COUNT(*) from t_test
select COUNT(text) from t_test where text=5
select COUNT(text) from t_test where text=10
select COUNT(*) from t_test where text is null

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.