Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select default value if result is null

Tags:

sql

oracle11g

Hello friends I have been using this query to select some two fields on my Java application.

select distinct STU_LEVEL, STU_STREAM from STUDENT_MASTER_TABLE where STATUS_YEAR !=ACADEMIC_YEAR

Problem is if there is no data, the application is throwing a null pointer Exception. I need it such that if the fields are Null, then they are defaulted to 0. I have tried this with Coalesce but I can't seem to get it like:

select coalesce(distinct (STU_LEVEL,0),  (STU_STREAM, '0')) from STUDENT_MASTER_TABLE where STATUS_YEAR !=ACADEMIC_YEAR

Please help.

like image 538
Stanley Mungai Avatar asked May 08 '26 02:05

Stanley Mungai


1 Answers

You just need to use COALESCE twice like this:

SELECT DISTINCT COALESCE(STU_LEVEL,0), COALESCE(STU_STREAM, '0')
FROM STUDENT_MASTER_TABLE
WHERE STATUS_YEAR !=ACADEMIC_YEAR

This will return 0 for STU_Level if it is NULL and 0 for STU_Stream if it is NULL.

SQL Fiddle Demo

In response to your comment, it looks like you need to use a UNION get your desired results when no records are found:

SELECT DISTINCT COALESCE(STU_LEVEL,0), COALESCE(STU_STREAM, '0')
FROM STUDENT_MASTER_TABLE
WHERE STATUS_YEAR !=ACADEMIC_YEAR
UNION 
SELECT 0,'0' FROM DUAL
WHERE NOT EXISTS (
  SELECT DISTINCT COALESCE(STU_LEVEL,0), COALESCE(STU_STREAM, '0')
  FROM STUDENT_MASTER_TABLE
  WHERE STATUS_YEAR !=ACADEMIC_YEAR
)

And a sample fiddle: http://www.sqlfiddle.com/#!4/29039/1

like image 152
sgeddes Avatar answered May 10 '26 14:05

sgeddes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!