How to Check if Table Exists in SQLite Database
SQLite is a database management system that is written in C programming language. It isn’t a standalone application; it is a library that developers can use to create a single-file database.
When working with databases, before executing queries, it is important to make sure that the tables we’re querying exist. Otherwise, the database manager or DBMS can throw errors.
Apart from manually verifying the existence of a table, we can check it programmatically. This article will talk about how to do this programmatically.
Check if Table Exists in SQLite Database
We can use the internal table, sqlite_master
, which is a part of all SQLite databases, to check if a table is in the current SQLite database.
It describes a database’s schema - what tables are there, SQL commands used to create them, their names, etc.
We can search this internal table to check if a table exists or not. Refer to the following SQL command.
SELECT COUNT(*) AS "Exists" FROM sqlite_master WHERE type = "table" AND name = "<table-name>";
The SQL statement above checks for all the entries in the sqlite_master
table that are of type table
and have a name as <table-name>
. Since every table has a unique name, it will only return a single entry.
Next, it will count the number of rows. If the required table is found, the count will be 1
; otherwise, 0
. This result can be found under the Exists
column.