24

What is the best SQL for a SQLite database to effectively do:

If Database Table Exists then - create table - insert row - insert row (i.e. for startup data) end 
1

3 Answers 3

31

To check that your table exists or not, you can use:

SELECT * FROM sqlite_master WHERE name ='myTable' and type='table'; 
Sign up to request clarification or add additional context in comments.

2 Comments

ok - so you think it best to keep the inserts as separate sql statements I assume? thanks
For TEMP tables, you must look at sqlite_temp_master.
8

You can let Sqlite itself check this out for you:

CREATE TABLE IF NOT EXISTS <table_name> ...; 

Follow link for documentation: https://sqlite.org/lang_createtable.html

3 Comments

This is the way!
Well for the database itself yes but what if I have lot of things to do in the app before even calling this? I can save compute time and resources if I am able to check before.
This is the right answer!
4

Use this code

SELECT name FROM sqlite_master WHERE type='table' AND name='yourTableName'; 

if returning array count is equal to 1 its means table exist else not exist.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.