Skip to Main Content
  • Questions
  • A requirement to fetch only one valued row

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Sailesh.

Asked: April 10, 2017 - 3:46 pm UTC

Last updated: April 11, 2017 - 12:44 am UTC

Version: 11

Viewed 1000+ times

You Asked

Hello All

I have a requirement where i need to fetch only one record for the id provided.
If the id is present in the table it will fetch that particular record and if it is not present , it will fetch the NULL valued record

Example
Table-: demo_table

id
----
1
2
3
4
5
(null)

For example if i am passing id as 1 it should return only 1st row, similarly If i am passing id as 4 it should fetch only 4th row but if I am passing id that is not there in the table, it should give me the 6th record i.e. NULL valued record.

I want this to be in Single SQL query. Thanks for your help in advance.
Let me know if you need more information.

and Chris said...

You could fetch the rows that match your search value and the null row. Then sort them ensuring nulls are last and return the first:

set feed on
set null <null>
var v number;

exec :v := 1;

with rws as (
  select rownum x from dual connect by level <= 5
  union all
  select null x from dual
), vals as (
  select * from rws
  where  x = :v or x is null
  order  by x nulls last
)
  select * from vals
  where  rownum = 1;

X  
1  


 1 rows selected
  
exec :v := 6;

with rws as (
  select rownum x from dual connect by level <= 5
  union all
  select null x from dual
), vals as (
  select * from rws
  where  x = :v or x is null
  order  by x nulls last
)
  select * from vals
  where  rownum = 1;
  
X       
<null>  


 1 rows selected 

Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Nice but using with i.e. not in 1 sql and rownum is not suggestible.

Sailesh Arya, April 10, 2017 - 4:42 pm UTC


Chris Saxon
April 10, 2017 - 5:02 pm UTC

Why is "rownum not suggestible"?

Sailesh Arya, April 10, 2017 - 5:05 pm UTC

as per the clients requirement and oracle standards!
I know we can achieve this through rownum , but i was trying for some different approach for the same.
Connor McDonald
April 11, 2017 - 12:44 am UTC

"as per the clients requirement and oracle standards!"

The problem then is not the SQL...the problem there is the client and their standards.