Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a record if the query returns one row, or select no record if the query returns more rows?

Tags:

sql

oracle

I require to select a row if there is only one row exists, if there are more rows, it should select 0 rows.

like image 590
Stalin Gino Avatar asked Apr 02 '13 09:04

Stalin Gino


1 Answers

If you're using PL/SQL, then selecting the column using select-into will throw a too_many_rows exception if there's more than one row returned:

declare
  var table.column%type;
begin
  select column
  into   var
  from   table
  where  ...;
end;

If you want to do this just using SQL, then you can do something like:

select *
from
  (select s.*, count(*) over () c
   from
    (select *
     from table
     where ...
     and   rownum <= 2
    ) s
)
where c = 1

UPDATE

As DazzaL says in the comments, the reason for the rownum <= 2 restriction is to short-circuit the query if there's more than 2 rows in the result set. This can give significant performance benefits if the dataset is large.

like image 173
Chris Saxon Avatar answered Oct 05 '22 00:10

Chris Saxon