PostgreSQL – How to Create a Table
Below is the syntax to create a table in PostgreSQL.
CREATE TABLE table_name ( column1 datatype1, column2 datatype2, ... );
where table_name
is the name you want to give to the new table.
and column1
, column2
, etc.: specifies the names of the columns you want to create in the table.
and datatype1
, datatype2
, etc.: specifies the data types for each column.
Let’s say you want to create a simple table named employees
with columns for id
, first_name
, last_name
, and email
:
CREATE TABLE employees
(id SERIAL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100) );
- The
id
column is given the data typeSERIAL
, which is an auto-incrementing integer. - The
first_name
andlast_name
columns are given the data typeVARCHAR
(variable-length character strings) with a maximum length of 50 characters. - The
email
column is also given the data typeVARCHAR
, with a maximum length of 100 characters.
you can create a table with constraints:
CREATE TABLE orders
( order_id SERIAL PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10, 2),
CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
Here,
- The
order_id
column is the primary key of the table. - The
customer_id
column is a foreign key that references thecustomer_id
column in thecustomers
table. - The
order_date
column holds dates. - The
total_amount
column holds decimal numbers with a precision of 10 and a scale of 2.