Overview
TheCREATE TABLE
statement creates a new table in a database. Each table has columns with specific data types like numbers, strings, or dates.
Syntax
To create a table, you should name and define the columns with their data types.table_name
: Name of the tablecolumn_1, column_2, column_n
: Names of the columnsdatatype
: Data type for each columnIF NOT EXISTS
(Optional): Use this to avoid errors if the table already exists
SQL keywords cannot be used for table and column names unless they are quoted. Keep in mind that unquoted names are case-sensitive. For the full list of keywords, please refer to our doc.
Constraints
When creating a table, we can add the NOT NULL constraint to ensure that values in a column cannot be NULL and will always contain a value. In other words, if you don’t define NOT NULL, the column can be empty.Table index
You can add indexes to the table. See here for more details.By default, tables are created in the
public
schema, but you can specify a different schema. For more information, click here.Examples
Creating a Table
Create a sample table with the query below:Creating a Table with Values
Below is an example of creating a client table with values:Using Quoted names
- Creating a table using the query below:
- This will fail with an error message:
- It happens because “module” is a keyword. To use a keyword as a column name, you need to enclose it in double quotes.
- When querying the table, remember to use quotes around the column name:
Creating a Table with IF NOT EXISTS
To prevent errors when a table already exists, use theIF NOT EXISTS
clause. See the following examples:
Example without IF NOT EXISTS
- First, create the table without using the
IF NOT EXISTS
option:
- Then, create the same table:
IF NOT EXISTS
, you will get the following error:
Example with IF NOT EXISTS
Now, create the table using theIF NOT EXISTS
option to avoid the error:
IF NOT EXISTS
allows the query to succeed even if the table already exists.