Monolith-0 has asked for the wisdom of the Perl Monks concerning the following question:

Here's a quick question which I can't seem to find the answer to..
How can you tell if a table in the database is empty? All I could think of was something like the following, but obvoiusly that's not right.
my $query= "SELECT id FROM users LIMIT 1"; my $sth=$dbh->do($query) or DBerror(); if ($sth->fetchrow_array == undef) { ... }

- Monolith

Replies are listed 'Best First'.
Re: Empty Set
by Trimbach (Curate) on Jul 13, 2001 at 07:03 UTC
    Maybe a little simpler (and optimized on many databases) is
    my $query = "SELECT count(*) FROM table";
    This will return true if there are any rows of any kind in the table.

    Gary Blackburn
    Trained Killer

Re: Empty Set
by VSarkiss (Monsignor) on Jul 13, 2001 at 07:16 UTC

    Empty table == no rows. Therefore: my $query = "SELECT count(*) FROM users";Some databases will store the count in the catalog (Informix used to) and will return very quickly. Some will count quickly if you have a clustered index on the table. Some will just count every row....

    HTH

Re: Empty Set
by Monolith-0 (Beadle) on Jul 13, 2001 at 07:21 UTC
    Ah, I didn't remember count(). Thanks, to both of you. :)