Pages

Tuesday 29 May 2012

Counting null and non-null values in SQL Server


Counting null and non-null values in a single query

--create a table
create table employee(
emp_name varchar(50),
salary int)

--insert data in table
insert into employee values ('Rohit',10000)
insert into employee values ('Rahul',NULL)
insert into employee values ('Ravi',NULL)

--To see the data
select * from employee

--count null and not null value
SELECT count(*) FROM employee WHERE salary IS NULL
UNION ALL
SELECT count(*) FROM employee WHERE salary IS NOT NULL 

************************************************************      
                                            or
************************************************************

SELECT COUNT(*), 'null_tally' AS narrative 
  FROM employee 
 WHERE salary IS NULL 
UNION
SELECT COUNT(*), 'not_null_tally' AS narrative 
  FROM employee 
 WHERE salary IS NOT NULL;

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice Tutorial..
    Can we replace null value with not null and not null value with null ???
    Please reply fast

    ReplyDelete