- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting presence of a NOT NULL value in MySQL
To count presence of a NOT NULL value, use aggregate function COUNT(yourColumnName). Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, NumberOfQuestion int, NumberOfSolution int ); Query OK, 0 rows affected (0.20 sec)
Insert some records in the table using insert command. Here, some of the values are NULL −
mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,10); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,2); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,NULL); Query OK, 1 row affected (0.03 sec) mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,NULL); Query OK, 1 row affected (0.05 sec) mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(30,19); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(30,1); Query OK, 1 row affected (0.04 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+------------------+------------------+ | Id | NumberOfQuestion | NumberOfSolution | +----+------------------+------------------+ | 1 | 20 | 10 | | 2 | 20 | 2 | | 3 | 20 | NULL | | 4 | 20 | NULL | | 5 | 30 | 19 | | 6 | 30 | 1 | +----+------------------+------------------+ 6 rows in set (0.00 sec)
Following is the query to count presence of value. The same value should be NOT NULL i.e. NULL values won’t be counted −
mysql> SELECT NumberOfQuestion, COUNT(NumberOfSolution) as NumberOfRows FROM DemoTable GROUP BY NumberOfQuestion;
This will produce the following output −
+------------------+--------------+ | NumberOfQuestion | NumberOfRows | +------------------+--------------+ | 20 | 2 | | 30 | 2 | +------------------+--------------+ 2 rows in set (0.00 sec)
Advertisements