
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return value from a row if it is NOT NULL, else return the other row value in another column with MySQL
For this, you can use IFNULL(). Let us first create a table −
mysql> create table DemoTable ( FirstName varchar(100), LastName varchar(100) ); Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John','Doe'); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values(NULL,'Taylor'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('David',NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(NULL,'Miller'); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John | Doe | | NULL | Taylor | | David | NULL | | NULL | Miller | +-----------+----------+ 4 rows in set (0.00 sec)
Following is the query to return value from a row if it is NOT NULL, else return the other row value in another column −
mysql> select ifnull(FirstName,LastName) as Result from DemoTable;
This will produce the following output −
+--------+ | Result | +--------+ | John | | Taylor | | David | | Miller | +--------+ 4 rows in set (0.00 sec)
- Related Questions & Answers
- Write a single MySQL query to return the ID from the corresponding row which is a NOT NULL value
- Sum if all rows are not null else return null in MySQL?
- Insert default into not null column if value is null in MySQL?
- Update a column A if null, else update column B, else if both columns are not null do nothing with MySQL
- Multiplying column with NULL row in MySQL?
- How to check if any value is Null in a MySQL table single row?
- Return only a single row from duplicate rows with MySQL
- Select minimum row value from a column with corresponding duplicate column values in MySQL
- MySQL insert a value to specific row and column
- MySQL stored procedure to return a column value?
- How to do a sum of previous row value with the current row and display the result in another row with MySQL cross join?
- Count the same value of each row in a MySQL column?
- Python Pandas – Find the maximum value of a column and return its corresponding row values
- Select from another column if selected value is '0' in MySQL?
- Update one column data to another column in MySQL if the second column is NOT NULL?
Advertisements