0

I have a table that is empty most of the time. Occasionally large amounts of data will be dumped into it and will be need to be processed ASAP.

I have a process that continuously checks the table and processes any data it finds.

What's the quickest/most efficient way of testing for any data in the table?

The obvious solution is ....

SELECT count(*) FROM myTable;

But this can take a while (especially if it's got a few million rows in it). Another solution is

SELECT reltuples AS approximate_row_count FROM pg_class WHERE relname = 'myTable'

But this only gives an approximate value.

Is there a better/quicker solution. NOTE - I'm not looking for an exact row count, I'm looking for simple empty/not empty boolean result.

1 Answer 1

3

You can use an exists condition:

select exists (select * from the_table limit 1) as has_data

The limit 1 isn't really necessary as the EXISTS operator will stop at the first row anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.