- 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
Convert MySQL null to 0?
Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0.
The syntax is as follows
SELECT IFNULL(yourColumnName,0) AS anyAliasName FROM yourTableName; The second syntax is as follows: SELECT COALESCE(yourColumnName,0) AS anyAliasName FROM yourTableName;
Let us first create a table. The query to create a table is as follows
mysql> create table convertNullToZeroDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20), -> Salary int -> ); Query OK, 0 rows affected (1.28 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into convertNullToZeroDemo(Name,Salary) values('John',NULL); Query OK, 1 row affected (0.20 sec) mysql> insert into convertNullToZeroDemo(Name,Salary) values('Carol',5610); Query OK, 1 row affected (0.10 sec) mysql> insert into convertNullToZeroDemo(Name,Salary) values('Bob',NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into convertNullToZeroDemo(Name,Salary) values('David',NULL); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from convertNullToZeroDemo;
The following is the output
+----+-------+--------+ | Id | Name | Salary | +----+-------+--------+ | 1 | John | NULL | | 2 | Carol | 5610 | | 3 | Bob | NULL | | 4 | David | NULL | +----+-------+--------+ 4 rows in set (0.05 sec)
Here is your first query to convert MySQL NULL to 0
mysql> select IFNULL(Salary,0) as `CONVERT_NULL _TO_0` from convertNullToZeroDemo;
The following is the output
+--------------------+ | CONVERT_NULL _TO_0 | +--------------------+ | 0 | | 5610 | | 0 | | 0 | +--------------------+ 4 rows in set (0.05 sec)
Here is your second query to convert MySQL NULL to 0
mysql> select coalesce(Salary,0) as `CONVERT_NULL _TO_0` from convertNullToZeroDemo;
The following is the output
+--------------------+ | CONVERT_NULL _TO_0 | +--------------------+ | 0 | | 5610 | | 0 | | 0 | +--------------------+ 4 rows in set (0.00 sec)
Advertisements