简体   繁体   中英

Oracle - Select a boolean? SELECT COUNT(*) > 0 FROM MYTABLE

Take the following two SQL statements executed in C# . They return different values depending on if you're using MySQL or Oracle :

//MySQL / MariaDB:
1a. SELECT COUNT(*) FROM MYTABLE //returns long
2a. SELECT COUNT(*) > 0 FROM MYTABLE //returns int (1 if true, 0 if false)

//Oracle:
1b. SELECT COUNT(*) FROM MYTABLE //returns int
2b. SELECT COUNT(*) > 0 FROM MYTABLE //ORA-00923: FROM keyword not found where expected

I would like to know if there was a way to get statement (2b) working with Oracle (selecting a boolean, preferably to mimic MySQL--1 if true, 0 if false).

I'm trying to avoid using database-specific functions like IF, IIF, IFNULL, CASE, etc. I'm trying to write a database-generic statement.

As there's no Boolean datatype in Oracle SQL , you can't really avoid CASE (or DECODE ). So, for an empty table, you'd have something like this:

SQL> select count(*) from test;

  COUNT(*)
----------
         0

SQL> select case when count(*) > 0 then 'true'
  2              else 'false'
  3         end as result
  4  from test;

RESUL
-----
false

SQL>

Note that the result - in this example - is a string , You could have returned something else: for example a number:

SQL> select case when count(*) > 0 then 1
  2              else 0
  3         end as result
  4  from test;

    RESULT
----------
         0

SQL>

But Boolean, as I said, not in SQL (yes in PL/SQL, but that's not what you asked).

SQL> declare
  2    l_cnt      number;
  3    l_result   boolean;         --> this
  4  begin
  5    select count(*) into l_cnt from test;
  6
  7    l_result := l_cnt > 0;
  8  end;
  9  /

PL/SQL procedure successfully completed.

SQL>

You can use a case expression:

select (case when count(*) > 0 then 1 else 0 end)
from mytable;

This will work in both databases. However, it is generally faster to use exists :

select (case when exists (select 1 from mytable) then 1 else 0 end)
from dual;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM