Oracle – How to Check if Table Has Rows

oracleplsql

I am completely new to PL/SQL. I have written the following PL/SQL script. But it doesn't execute and gives compilation error:

set serveroutput on SIZE 1000000;
IF EXISTS (select * from my_table)
begin
dbms_output.put_line('has rows');
end;
else
begin
dbms_output.put_line('no rows');
end;

Can anyone tell me what is wrong with this?

How can I do this?

Best Answer

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;