Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace null values with a text?

Tags:

sql

null

oracle

I need to display Employee last_name and their commission amount from employees table in Oracle SQL, but the condition is if it encounter NULL value I need to print "No Commission".
For the first part I wrote:

select last_name, commission_pct from employees;

But I am unable to get how to replace NULL values with "No Commission".

like image 425
Rishabh Prasad Avatar asked May 01 '15 06:05

Rishabh Prasad


People also ask

Can you change a NULL value?

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. In the example above it replaces them with 0.

How do you replace NULL values in SQL with data?

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 can use case expression:

select last_name
     , case when commision_pct is null then 'No Commission' else commision_pct end    
from employees;

or coalesce:

select last_name
     , coalesce(commision_pct, 'No Commission')
from employees;

or nvl:

 select last_name
     , nvl(commision_pct, 'No Commission')
from employees;

P.S. In case commision_pct's datatype is not varchar you should also use cast or to_char.

like image 181
potashin Avatar answered Oct 14 '22 21:10

potashin


For Oracle

select last_name, nvl(commission_pct,'No Commission')
from employees;

For SQL

select last_name, isnull(commission_pct,"No Commission") as commission_pct
    from employees;
like image 44
Jaimin Soni Avatar answered Oct 14 '22 22:10

Jaimin Soni