Is there a function equivalent to the Oracle's NVL in MySQL?
Asked Answered
B

2

28

I'm selecting the max of a column from a table. But there is one problem: if there are no rows in the table, it returns null.

I want to use a function which will return a certain value if the result is null. For example with Oracle there is the NVL function which gives a certain value if the column is null. Is there an equivalent function in MySQL ?

Bushcraft answered 30/8, 2011 at 6:33 Comment(0)
B
52

Use coalesce:

select coalesce(column_name, 'NULL VALUE') from the_table
Barry answered 30/8, 2011 at 6:34 Comment(3)
That is the SQL standard version of NVL, and works in Oracle, too (since 9i, I believe).Barry
The question asks "But there is one problem: if there are no rows in the table, it returns null." However, coalesce doesn't solve this - if no rows are returned, then no rows are returned. All it does is ensure a non-null value for a certain column given some rows are returned But then, neither does nvl in oracle :)Unprepared
@Adam. The aggregate function max will return a single row (with null in it) even if there are no rows in the table. All the coalesce does (and all the question asked about) is change that null to a default value.Barry
C
0

or you can use IFNULL(expr1,expr2)

If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2.

select IFNULL(column_name, 'NULL VALUE') from the_table;

taken from: https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull

Chilblain answered 3/1, 2023 at 13:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.