1

I have a table with two column like below:

name         marks
  A            15
  B            
  c            20

As is clear from above, column name has 3 non-null values and 1 null value, similarly column marks has 2 null as well 2 non-null values.

What's the query to get this result?

2
  • count(columnname) counts only non-null values. count(*) counts all rows. Now you do the math! Commented May 16, 2019 at 7:28
  • i want to count columnwise null and non null records present in a table Commented May 16, 2019 at 7:29

4 Answers 4

1

count(columnname) counts only non-null values. count(*) counts all rows.

select count(name) as names,
       count(*) - count(name) as null_names,
       count(marks) as marks,
       count(*) - count(marks) as null_marks
from tablenam
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this -

SELECT COUNT(name) AS name_not_null_count, 
       SUM(CASE WHEN name IS NULL THEN 1 ELSE 0 END) AS name_null_count
FROM table

Approach to calculate null count is: mark all the null records with 1 and take SUM.

Comments

0
SELECT COUNT(name) AS name_count, COUNT(marks) AS marks_count FROM table;

Comments

0

This will select number of rows, number of rows with null, and number of rows with non-null value. Repeat the select for each desired column.

 CREATE TABLE #tmp
 (
     i int
 )

 INSERT INTO #tmp values(1)
 INSERT INTO #tmp values(2)
 INSERT INTO #tmp values(3)
 INSERT INTO #tmp values(NULL)

 SELECT COUNT(*) AS Num_Rows
  , COUNT(i) AS Num_Not_Null
  , COUNT(*)-COUNT(i) AS Num_Null 
 FROM #tmp

Num_Rows Num_Not_Null Num_Null


4 3 1

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.