Home > Software design >  Check if table is empty in SQLite
Check if table is empty in SQLite

Time:03-28

I want to know if there is an better way to check if a table of a given database is empty.

My version:

import sqlite3

con = sqlite3.connect('emails.db')
cur = con.cursor()

cur.execute("SELECT count(*) FROM (select 1 from my_table limit 1);")
print(cur.fetchall()[0][0])

con.close()

Output:

0 # If table `my_table' is empty
1 # If table 'my_table' is not empty

CodePudding user response:

Yo can use:

SELECT EXISTS (SELECT 1 FROM my_table);

this will return 1 row with 1 column which will be 0 if the table is empty or 1 if it contains any rows.

EXISTS will return as soon as it finds the 1st row in the table and it will not scan the whole table.

  • Related