Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check in SQLite whether a table exists?

Tags:

sqlite

How do I, reliably, check in SQLite, whether a particular user table exists?

I am not asking for unreliable ways like checking if a "select *" on the table returned an error or not (is this even a good idea?).

The reason is like this:

In my program, I need to create and then populate some tables if they do not exist already.

If they do already exist, I need to update some tables.

Should I take some other path instead to signal that the tables in question have already been created - say for example, by creating/putting/setting a certain flag in my program initialization/settings file on disk or something?

Or does my approach make sense?

like image 204
PoorLuzer Avatar asked Oct 21 '09 14:10

PoorLuzer


People also ask

How do you check if a table exists in a schema?

How to check whether a table (or view) exists, and the current user has access to it? SELECT EXISTS ( SELECT FROM information_schema. tables WHERE table_schema = 'schema_name' AND table_name = 'table_name' ); The information schema is mainly useful to stay portable across major versions and across different RDBMS.

How do I find data in SQLite?

To Search for the values define edit text and implement text watcher in database enter a query as shown below: editText. addTextChangedListener(new TextWatcher(){ Cursor cusror; cursor=db. rawQuery("SELECT * FROM "+ DB_NAME + " WHERE " + DB_NAME.id + " = " + DB_NAME.Id + " AND " + DB_NAME.

What is check in SQLite?

The CHECK constraints allow you to define additional data integrity checks beyond UNIQUE or NOT NULL to suit your specific application. SQLite allows you to define a CHECK constraint at the column level or the table level.


2 Answers

I missed that FAQ entry.

Anyway, for future reference, the complete query is:

SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'; 

Where {table_name} is the name of the table to check.

Documentation section for reference: Database File Format. 2.6. Storage Of The SQL Database Schema

  • This will return a list of tables with the name specified; that is, the cursor will have a count of 0 (does not exist) or a count of 1 (does exist)
like image 119
PoorLuzer Avatar answered Sep 22 '22 02:09

PoorLuzer


If you're using SQLite version 3.3+ you can easily create a table with:

create table if not exists TableName (col1 typ1, ..., colN typN) 

In the same way, you can remove a table only if it exists by using:

drop table if exists TableName 
like image 42
arthur johnston Avatar answered Sep 19 '22 02:09

arthur johnston