SQL Create Database

The CREATE DATABASE statement builds a brand-new, empty database that you can then fill with tables and data.

What CREATE DATABASE does

A database is the top-level container that holds all of your tables, views, indexes, and other objects. Before you can store any data, you need a database to put it in. The CREATE DATABASE statement asks the database server to allocate this container and register it under a name you choose. Once it exists, you can switch into it and start defining tables.

Basic syntax

CREATE DATABASE database_name;

-- Example: a database for a small online shop
CREATE DATABASE shop;

The name you pick should describe what the database is for. Most systems allow letters, digits, and underscores. Avoid spaces and reserved keywords, and keep names lowercase where your platform is case-sensitive so you never have to guess how a name was capitalized.

Note: You usually need administrative or elevated privileges to create a database. On a shared or managed host, this action may be reserved for the account owner or performed through a control panel instead of raw SQL.

Creating a database only if it is missing

Running CREATE DATABASE for a name that already exists raises an error. To make a script safe to run more than once, add the IF NOT EXISTS clause. The server then creates the database only when it is absent and quietly skips the step otherwise.

Guarding against duplicates

CREATE DATABASE IF NOT EXISTS shop;

-- After creating it, switch into the database (MySQL / SQL Server style)
USE shop;
ClausePurpose
CREATE DATABASE nameCreates a new database; fails if the name is taken
IF NOT EXISTSSkips creation instead of erroring when the name exists
USE nameSets the active database for the following statements
  • Pick a short, descriptive, lowercase name with no spaces.
  • Use IF NOT EXISTS in setup scripts so they can rerun safely.
  • Remember that creating a database does not select it; run USE (or reconnect to it) before adding tables.
  • Support for options like character sets and collations varies between database systems, so check your platform's documentation.

Exercise: SQL Create Database

What does the CREATE DATABASE statement do?