EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

MySQL COALESCE

Home » Data Science » Data Science Tutorials » MySQL Tutorial » MySQL COALESCE

MySQL COALESCE

Introduction to MySQL COALESCE

MySQL COALESCE function is used to handle the NULL values in the table columns. Whenever we create a table containing columns that have not been assigned a default value or auto-increment attribute then the values that are inserted in that columns by default is NULL. While retrieving the data from the tables, it is not convenient and appropriate to display the NULL values to the user. Instead of NULL, we should replace the NULL value to some appropriate value depending on the purpose of that column and what type of value is being stored in them. For example, when the name is stored but the column contains default values in them when not specified while inserting then while retrieving the name column we should replace the NULL value with a blank string using coalesce. In this article, we will learn about the syntax and usage of coalesce function using examples.

Syntax

Below is the syntax for MySQL COALESCE:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

COALESCE(expression1,expressions,...);

Explanation: The coalesce function accepts the number of expressions which can be columns or values in the table or other expressions. It returns the first Non-Null value in the supplied comma-separated list as a parameter. But, we have to be careful while using it because if all the values and expressions evaluate to NULL then the returned value is always NULL.

Examples to Implement MySQL COALESCE

Let us consider some examples:

Example #1

Firstly, we will make a list of values that will contain NULL as well as other valued elements:

Code:

SELECT COALESCE(NULL, 1, NULL, 0, true, false );

Output:

mysql coalesce1

Example #2

Now, we will query by using the coalesce in the list that contains only NULL values in it:

Code:

SELECT COALESCE(NULL, NULL, NULL);

Output:

mysql coalesce2

How does MySQL COALESCE work?

Let us see how does this function work:

Coalesce function to substitute NULL values

Step 1: Let us create one table named educba_writers using the following query statement

Code:

CREATE TABLE `educba_writers` (
`id` int(11) NOT NULL,
`firstName` varchar(10) COLLATE latin1_danish_ci NOT NULL,
`rate` decimal(5,2) DEFAULT NULL,
`joining_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci;

Output:

mysql coalesce3

Step 2: Now we will insert some values in it:

Code:

INSERT INTO `educba_writers` (`id`, `firstName`, `rate`, `joining_date`) VALUES
(1, 'Payal', NULL, NULL),
(2, 'Vyankatesh', NULL, NULL),
(5, 'Om Prakash', NULL, NULL),
(6, 'Om Prakash', NULL, NULL);

Output:

mysql coalesce4

Step 3: Let us insert some more rows with non-null rate and joining date value:

Code:

INSERT INTO `educba_writers` (`id`, `firstName`, `rate`, `joining_date`) VALUES
(1, 'Payal', 750, "2020-05-01"),
(2, 'Vyankatesh', 700, "2020-01-01"),
(5, 'Om Prakash', 600, "2020-02-01"),
(6, 'Om Prakash', 800, "2020-06-01");

Popular Course in this category
MySQL Training Program (11 Courses, 10 Projects)11 Online Courses | 10 Hands-on Projects | 92+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (2,982 ratings)
Course Price

View Course

Related Courses
MS SQL Training (13 Courses, 11+ Projects)Oracle Training (14 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)

Output:

mysql coalesce5

Step 4: Now, we will query on educba_writers table to retrieve the values of columns firstName, rate and joining date:

Code:

SELECT firstName,rate,joining_date FROM educba_writers;

Output:

mysql coalesce6

Step 5: Now, we will substitute the value of rate column when it is NULL with 0.00 and joining date column with “1990-01-01” by using the coalesce function by placing the column name in the first element of the list and the value that we have to substitute with when the column value is NULL in the second element in the coalesce list of parameters. Our query for retrieving the records with substituted NULL values as per our requirement will be as follows:

Code:

SELECT firstName,COALESCE(rate,0.00),COALESCE(joining_date,"1990-01-01") FROM educba_writers;

Output:

mysql coalesce7

Explanation: We can see from the resultset that wherever there were any of the NULL values in the rate and joining_date column were replaced with 0.00 and “1990-01-01” values respectively. This is where the coalesce function is used most of the time.

Coalesce function to substitute one column with other value when first is NULL

Step 1: There is one more place where we can use coalesce function besides substituting the null values with specified ones. We can replace the NULL values of column records with some other column values using the coalesce function. Let us create one new table named dictionary that will contain columns such as word, meaning, and description. We will use the following query to create the table:

Code:

CREATE TABLE `dictionary` (
`word` varchar(100) DEFAULT NULL,
`meaning` varchar(5000) DEFAULT NULL,
`description` varchar(5000) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Output:

substitute column

Step 2: Let us insert some values in it:

Code:

INSERT INTO `dictionary` (`word`, `meaning`, `description`) VALUES
('antonym', NULL,'a word that means the opposite of another word'),
('connotation', NULL,'an additional idea or emotion that a word suggests to you'),
('etymology', 'the study of the origins of words; the origins of a particular word','the study of the origins'),
('lexicography', 'the job or skill of writing dictionaries','writing dictionaries'),
('polysemy', NULL,'the fact that some words can have more than one meaning'),
('thesaurus', 'a reference tool which shows groups of words that have similar meanings','representation of groups of words that have similar meanings'),
('knack', 'an acquired or natural skill at doing something.','natural skill'),
('flair', 'stylishness and originality.','originality'),
('panache', 'a tuft or plume of feathers','feather collection');

Output:

insert some values

Step 3: Let us retrieve the records of the table:

Code:

SELECT * FROM  dictionary;

Output:

retrieve the records

Step 4: Now, let us replace the NULL values of the meaning column with description column values for NULL values using the coalesce function. For that, we will use the following query statement:

Code:

SELECT word, COALESCE(meaning,description) as meaning, description FROM dictionary;

Output:

replace the NULL values

Explanation: We can see that the NULL values of the meaning column are replaced with the description column as we have used coalesce with a parameter list containing meaning and description column. The function will go for searching the first non-null value. If the meaning column will contain value other than null then that will be chosen while retrieving else if it is found null then coalesce will search for the corresponding description column value and will display that value if it is not null and will display null if both meaning and description column are null.

IFNULL() function verses Coalesce function

IFNULL() function works similarly as that of coalesce. The only difference between the IFNULL() and COALESCE() function is that IFNULL() function always accepts two values as its parameters while COALESCE() may accept any number of parameters in its parameter list. When COALESCE() function is used with two parameters it works the same as IFNULL() function.

Conclusion

We can use the coalesce function to replace the null values in the column with any of our desired values that can be a constant string or number or even with any of the other column values while retrieving the column values in SELECT query.

Recommended Articles

This is a guide to MySQL COALESCE. Here we discuss an introduction to MySQL COALESCE, syntax, how does it work, examples. You can also go through our other related articles to learn more –

  1. ROLLUP in MySQL
  2. Condition in MySQL
  3. SQL INSTR()
  4. ANY in MySQL

MySQL Training Program (11 Courses, 10 Projects)

11 Online Courses

10 Hands-on Projects

92+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL count()
    • MIN() in MySQL
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • TRUNCATE TABLE MySQL
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL 
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT 
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL COALESCE
    • MySQL Cluster
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • Introduction to MySQL
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • How To Install MySQL
    • MySQL OpenSource
    • MySQL Commands
    • Views in MySQL
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL UUID
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL Transaction
    • MySQL sort_buffer_size
    • MySQL Sync
    • MySQL Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - MySQL Training Program (11 Courses, 10 Projects) Learn More