Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace nulls values in sql using select statement in mysql?

Tags:

sql

mysql

Ho to do this? What query can be written by using select statement where all nulls should be replaced with 123?

I know we can do this y using, update tablename set fieldname = "123" where fieldname is null;

but can't do it using select statement.

like image 281
Thompson Avatar asked Mar 26 '12 18:03

Thompson


People also ask

How do you replace NULL values in SQL?

The ISNULL Function is a built-in function to replace nulls with specified replacement values. To use this function, all you need to do is pass the column name in the first parameter and in the second parameter pass the value with which you want to replace the null value.

How do I change NULL to zero in MySQL?

Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0. Insert some records in the table using insert command. Display all records from the table using select statement.

Can we UPDATE NULL value in SQL?

Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them.

What function is used to replace NULL values?

We can replace NULL values with a specific value using the SQL Server ISNULL Function. The syntax for the SQL ISNULL function is as follow. The SQL Server ISNULL function returns the replacement value if the first parameter expression evaluates to NULL.


2 Answers

You have a lot of options for substituting NULL values in MySQL:

CASE

select case 
    when fieldname is null then '123' 
    else fieldname end as fieldname 
from tablename 

COALESCE

select coalesce(fieldname, '123') as fieldname 
from tablename 

IFNULL

select ifnull(fieldname, '123') as fieldname 
from tablename 
like image 172
D'Arcy Rittich Avatar answered Sep 30 '22 19:09

D'Arcy Rittich


There is a statement called IFNULL, which takes all the input values and returns the first non NULL value.

example:

select IFNULL(column, 1) FROM table;

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull

like image 27
Dave Halter Avatar answered Sep 30 '22 20:09

Dave Halter