- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How does COALESCE order results with NULL and NON-NULL values?
The COALESCE() finds the NON-NULL value first If it finds the same in the beginning, then it returns, otherwise moves ahead to check NON-NULL value.
Let us first create a table −
mysql> create table DemoTable ( Number1 int, Number2 int ); Query OK, 0 rows affected (5.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,200); Query OK, 1 row affected (0.40 sec) mysql> insert into DemoTable values(NULL,50); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(10,NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(NULL,NULL); Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+---------+ | Number1 | Number2 | +---------+---------+ | 100 | 200 | | NULL | 50 | | 10 | NULL | | NULL | NULL | +---------+---------+ 4 rows in set (0.00 sec)
Following is the query to order records with COALESCE −
mysql> select coalesce(Number1,Number2) AS NON_NULL_ARGUMENT_FIRST from DemoTable;
This will produce the following output −
+-------------------------+ | NON_NULL_ARGUMENT_FIRST | +-------------------------+ | 100 | | 50 | | 10 | | NULL | +-------------------------+ 4 rows in set (0.00 sec)
- Related Articles
- Display first non-null values with coalesce() in MySQL?
- Fetch maximum value from multiple columns with null and non-null values?
- Perform mathematical calculations in a MySQL table with NULL and NON-NULL values
- Update all the fields in a table with null or non-null values with MySQL
- Return only the non-empty and non-null values from a table and fill the empty and NULL values with the corresponding column values in MySQL?
- Query non-empty values of a row first in ascending order and then display NULL values
- Looping in JavaScript to count non-null and non-empty values
- Python Pandas – Propagate non-null values backward
- Python Pandas – Propagate non-null values forward
- MySQL query to order by NULL values
- Display only NOT NULL values from a column with NULL and NOT NULL records in MySQL
- How to convert MySQL null to 0 using COALESCE() function?
- How to remove null values with PHP?
- MySQL query to order by two fields and NULL values in chronological order?
- Count zero, NULL and distinct values except zero and NULL with a single MySQL query

Advertisements