Create a Database in SQLite

SQLite uses a different syntax for creating databases to what many other relational database management systems use.

Most of the popular relational database management systems such as MySQL, SQL Server, PostgreSQL, and so on, use the CREATE DATABASE statement to create a database.

When you create a database with SQLite however, you do so by simply providing a filename.

Example

When you connect to SQLite, you have the option of providing a database file name. If such a file exists, it will be opened, if not, a new database file will be created with that name.

So in my case, I can open the Terminal on my Mac and enter the following command:

sqlite3 Pets.db;

That creates a new database file in the current directory called Pets.db.

If it had already existed the file would have been opened.

You can also use the full path to specify a database in another folder. For example:

sqlite3 /Users/Shared/Pets.db

Check that the Database was Created

You can use the .databases command to check that the database was created.

.databases

Result:

main: /Users/Shared/Pets.db

You can also navigate to the file using your computer’s file system.

The .databases command is known as a “dot-command”. These are interpreted by the command-line utility and not by SQLite itself. You don’t need to append a semicolon to dot-commands like you do with SQL statements.

Attach a Database

You can also use ATTACH DATABASE to attach a database and provide a database name. If the file exists it will be attached with your chosen name, otherwise it will be created and attached with your chosen name.

ATTACH DATABASE 'Pets.db' AS Pets;

This example will cause the database to be called Pets instead of main as shown in the previous example.

See How to Attach a Database in SQLite for a more detailed explanation.

Create a Table

Once you’ve created a database, you can go ahead and create your tables using the CREATE TABLE statement.