Create Table
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 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
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.
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
- 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:
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
- First, create the table without using the
IF NOT EXISTS
option:
Output:
- 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.