How to check if the table has rows?

Anonymous PL/SQL blocks don't start with IF. The above code should be in between a begin and end; at least.

EXISTS is an SQL function, it can't be used in PL/SQL like that.

Try something like this:

set serveroutput on
declare
  c number;
begin
  select count(*) into c from my_table where rownum = 1;
  if c != 0 then
    dbms_output.put_line('has rows');
  else
    dbms_output.put_line('no rows');
  end if;
end;
/

Yes, using EXISTS in the query is also possible:

set serveroutput on
declare
  c varchar2(10);
begin
  select case when exists (select * from my_table) then 'has rows' else 'no rows' end into c from dual;
  dbms_output.put_line(c);
end;
/

Note that both the EXISTS and rownum = 1 version will stop on the first row found, and that's the point, so we don't need to read the whole table/index.


Wrong If syntax. And exists not allowed here. Try this way:

declare
  cnt number;
begin
  select count(*) into cnt from my_table;
  if cnt != 0 then
    dbms_output.put_line('has rows');
  else
    dbms_output.put_line('no rows');
  end if;
end;

Tags:

Oracle

Plsql