SQL是结构化查询语句(Structured Query Language)的简称,结构化查询语言是一种数据库查询和程序设计语言,用于存放数据以及查询、更新和管理关系数据库系统。
SQL语句根据其作用的不同,可以分为好几类。其中,DDL(data definition language)数据定义语言,是主要用于创建、删除、修改表,索引等数据库对象的语言。
DDL语句
1、建表语句
建表语句较多,基本的建表语句,命令如下:
create table t1(a int primary key, b text);
pg中,创建表之后使用\d命令可以查看到数据库中存在哪些表,示例如下:
postgres=# \d
List of relations
Schema | Name | Type | Owner
--------+------+-------+----------
public | t1 | table | postgres
(1 row)
可以通过\h create table查看帮助:
postgres=# \h create table
Command: CREATE TABLE
Description: define a new table
Syntax:
CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE [ IF NOT EXISTS ] table_name ( [
{ column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]
| table_constraint
| LIKE source_table [ like_option ... ] }
[, ... ]
] )
未完...
2、修改表
通过alter table语句可以修改表,示例如下:
postgres=# alter table t1 rename a to a_new;
ALTER TABLE
postgres=# \d t1
Table "public.t1"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
a_new | integer | | not null |
b | text | | |
Indexes:
"t1_pkey" PRIMARY KEY, btree (a_new)
同样的,可以使用\h alter table查看帮助:
postgres=# \h alter table
Command: ALTER TABLE
Description: change the definition of a table
Syntax:
ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
action [, ... ]
ALTER TABLE [ IF EXISTS ] [ ONLY ] name [ * ]
RENAME [ COLUMN ] column_name TO new_column_name
未完...
3、删除表
删除表语句比较简单,如下:
postgres=# drop table t1;
DROP TABLE
查看帮助:
postgres=# \h drop table
Command: DROP TABLE
Description: remove a table
Syntax:
DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
URL: https://www.postgresql.org/docs/12/sql-droptable.html
基本的DDL语句就以上三种,更多用法后续更新。