SQLite
Database Management
Programming
SQL Commands
Table Existence Check

SQLite: check if a table exists

Codemia Knowledge Hub ·

Query the sqlite_master (or sqlite_schema) table with type = 'table' and the table name. A returned row means the table exists. If you only check so you can create the table, skip the check and use CREATE TABLE IF NOT EXISTS, which does it in one statement with no check-then-act race.

Querying the schema table

sql
1SELECT name
2FROM sqlite_master
3WHERE type = 'table'
4  AND name = 'users';

For a 1 or 0 result:

sql
1SELECT EXISTS (
2    SELECT 1
3    FROM sqlite_master
4    WHERE type = 'table'
5      AND name = 'users'
6);

SQLite 3.33.0 (released August 2020) added sqlite_schema as an alias. Both names work in modern SQLite, but sqlite_master is more portable if you must support older versions.

sql
1-- Modern syntax, equivalent to sqlite_master
2SELECT name
3FROM sqlite_schema
4WHERE type = 'table'
5  AND name = 'users';

Keep the type = 'table' filter. sqlite_master holds every schema object, so without it a view named users would match and you would wrongly conclude the table exists.

Parameterized checks in application code

When the table name comes from a variable, pass it as a parameter to avoid SQL injection.

Python:

python
1import sqlite3
2
3conn = sqlite3.connect("app.db")
4cur = conn.cursor()
5
6table_name = "users"
7cur.execute(
8    """
9    SELECT EXISTS (
10        SELECT 1
11        FROM sqlite_master
12        WHERE type = 'table' AND name = ?
13    )
14    """,
15    (table_name,),
16)
17
18exists = cur.fetchone()[0] == 1
19print(f"Table '{table_name}' exists: {exists}")

JavaScript (better-sqlite3, Node.js):

javascript
1const Database = require('better-sqlite3');
2const db = new Database('app.db');
3
4const tableName = 'users';
5const row = db.prepare(
6  `SELECT EXISTS (
7    SELECT 1 FROM sqlite_master
8    WHERE type = 'table' AND name = ?
9  ) AS table_exists`
10).get(tableName);
11
12console.log(`Table '${tableName}' exists:`, row.table_exists === 1);

Java (JDBC):

java
1String tableName = "users";
2String sql = "SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?)";
3
4try (PreparedStatement stmt = connection.prepareStatement(sql)) {
5    stmt.setString(1, tableName);
6    ResultSet rs = stmt.executeQuery();
7    boolean exists = rs.next() && rs.getInt(1) == 1;
8    System.out.println("Table exists: " + exists);
9}

PRAGMA table_info for column metadata

sql
PRAGMA table_info(users);

If the table exists, this returns one row per column with its name, type, default value and nullable flag. An empty result means the table does not exist (a table with no columns is not possible in practice).

It is useful when you also need the columns, but it is less direct for a pure existence check, and it cannot be parameterized like a normal query. That makes it unsafe with table names from user input.

CREATE TABLE IF NOT EXISTS

sql
1CREATE TABLE IF NOT EXISTS users (
2    id INTEGER PRIMARY KEY,
3    name TEXT NOT NULL,
4    email TEXT UNIQUE,
5    created_at TEXT DEFAULT (datetime('now'))
6);

This beats checking and then creating because:

  1. It is atomic, so two threads cannot both see "not found" and both try to create the table.
  2. It takes one round trip to the database instead of two.
  3. The code is shorter and harder to get wrong.

If the table already exists, the statement does nothing. It does not check that the existing table has the schema you expect, so a table with the right name but wrong columns passes silently. Use PRAGMA table_info if you need to validate columns.

Views, indexes and other schema objects

The type column can be table, view, index or trigger:

sql
1-- Check for a view
2SELECT name FROM sqlite_master
3WHERE type = 'view' AND name = 'active_users';
4
5-- Check for an index
6SELECT name FROM sqlite_master
7WHERE type = 'index' AND name = 'idx_users_email';
8
9-- List all schema objects
10SELECT type, name FROM sqlite_master ORDER BY type, name;

Temporary tables

Tables created with CREATE TEMP TABLE live in a separate catalog and do not appear in sqlite_master. Query sqlite_temp_master (or sqlite_temp_schema) instead:

sql
1-- Create a temp table
2CREATE TEMP TABLE session_cache (key TEXT PRIMARY KEY, value TEXT);
3
4-- This returns nothing, even though the table exists
5SELECT name FROM sqlite_master
6WHERE type = 'table' AND name = 'session_cache';
7
8-- This finds it
9SELECT name FROM sqlite_temp_master
10WHERE type = 'table' AND name = 'session_cache';

To cover both regular and temporary tables, query both catalogs:

sql
1SELECT name FROM sqlite_master
2WHERE type = 'table' AND name = 'session_cache'
3UNION ALL
4SELECT name FROM sqlite_temp_master
5WHERE type = 'table' AND name = 'session_cache';

Attached databases

An attached database has its own catalog, prefixed with the alias from the ATTACH statement:

sql
1ATTACH DATABASE 'analytics.db' AS analytics;
2
3-- Check for a table in the attached database
4SELECT name FROM analytics.sqlite_master
5WHERE type = 'table' AND name = 'events';

Comparing the methods

MethodReturnsParameterizableFinds Temp TablesBest For
SELECT FROM sqlite_masterRow if existsYesNoGeneral existence check
SELECT EXISTS(...)1 or 0YesNoBoolean result in code
PRAGMA table_info(name)Column metadataNoYesExistence + schema inspection
CREATE TABLE IF NOT EXISTSNothing (DDL)NoN/ASafe table creation
SELECT FROM sqlite_temp_masterRow if existsYesYes (only temp)Temp table checks

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design