Để tạo bảng CSDL trong PostgreSQL chúng ta sử dụng SQL Command là “CREATE TABLE”
Syntax:
CREATE TABLE table_name ( column_name TYPE column_constraint, table_constraint table_constraint ) INHERITS existing_table_name;
Với
- column_name TYPE column_constraint: Danh sách các cột trong bảng bao gồm tên, kiểu dữ liệu, length,…
- table_constraint table_constraint: Mối quan hệ với các bảng khác
- INHERITS existing_table_name: Kế thừa từ 1 bảng khác trong CSDL
VD: Tạo 2 bảng CSDL Users và Groups:

Lệnh SQL để tạo bảng Groups:
-- Table: public.groups
-- DROP TABLE public.groups;
CREATE TABLE public.groups
(
group_id integer NOT NULL,
group_name character varying COLLATE pg_catalog."default" NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone,
deleted_at timestamp without time zone,
CONSTRAINT groups_pkey PRIMARY KEY (group_id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.groups
OWNER to postgres;
Kết quả:

Lệnh SQL để tạo bảng users:
-- Table: public.users
-- DROP TABLE public.users;
CREATE TABLE public.users
(
user_id integer NOT NULL,
group_id integer NOT NULL,
username character varying COLLATE pg_catalog."default" NOT NULL,
password character varying COLLATE pg_catalog."default" NOT NULL,
email character varying COLLATE pg_catalog."default",
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone,
deleted_at timestamp without time zone,
CONSTRAINT users_pkey PRIMARY KEY (user_id),
CONSTRAINT fk_group_id FOREIGN KEY (group_id)
REFERENCES public.groups (group_id) MATCH SIMPLE
ON UPDATE CASCADE
ON DELETE CASCADE
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.users
OWNER to postgres;
Với fk_group_id là foreign key liên kết giữa 2 bảng users và groups thông qua cột group_id
Kết quả:
