snippetModerate
How to check if the table has rows?
Viewed 0 times
rowsthehashowchecktable
Problem
I am completely new to PL/SQL. I have written the following PL/SQL script. But it doesn't execute and gives compilation error:
Can anyone tell me what is wrong with this?
How can I do this?
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?
Solution
Anonymous PL/SQL blocks don't start with
Try something like this:
Yes, using
Note that both the
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.Code Snippets
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;
/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;
/Context
StackExchange Database Administrators Q#132155, answer score: 15
Revisions (0)
No revisions yet.