Skip to main content

Overview

The CREATE 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.
From the syntax above:
  • table_name: Name of the table
  • column_1, column_2, column_n: Names of the columns
  • datatype: Data type for each column
  • IF 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:
Once the table is created successfully, you will get the following output

Creating a Table with Values

Below is an example of creating a client table with values:
You can run the following command to verify the completed request:
As a result, we”ll receive a table show below:

Using Quoted names

  1. Creating a table using the query below:
  1. This will fail with an error message:
  1. It happens because “module” is a keyword. To use a keyword as a column name, you need to enclose it in double quotes.
  1. When querying the table, remember to use quotes around the column name:
Note that names enclosed in quotes are case-sensitive. Therefore, this query will fail:

Creating a Table with IF NOT EXISTS

To prevent errors when a table already exists, use the IF NOT EXISTS clause. See the following examples:

Example without IF NOT EXISTS

  1. First, create the table without using the IF NOT EXISTS option:
Output:
  1. Then, create the same table:
Because you attempt to create the table without using IF NOT EXISTS, you will get the following error:

Example with IF NOT EXISTS

Now, create the table using the IF NOT EXISTS option to avoid the error:
Using IF NOT EXISTS allows the query to succeed even if the table already exists.