Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if table is empty in SQLite

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

1 Answers

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.

like image 77
forpas Avatar answered Oct 28 '25 21:10

forpas