创建模式

最近更新时间: 2026-03-13 09:03:00

本文介绍如何使用 SQL 语句来创建模式,同时介绍创建模式的前提条件、模式使用的限制和建议等,并提供一些示例。

模式(Schema),一个模式本质上是一个名字空间:它包含命名对象(表、数据类型、函数以及操作符), 对象可以与在其他模式中存在的对象重名。可以通过用模式名作为一个前缀 “限定”命名对象的名称“模式名.对象名”来访问它们,或者通过把要求的模式包括在搜索路径中来访问命名对象。

创建模式

CREATE SCHEMA 语法如下:

CREATE SCHEMA schema_name [ AUTHORIZATION role_specification ] [ schema_element [ ... ] ]
CREATE SCHEMA AUTHORIZATION role_specification [ schema_element [ ... ] ]
CREATE SCHEMA IF NOT EXISTS schema_name [ AUTHORIZATION role_specification ]
CREATE SCHEMA IF NOT EXISTS AUTHORIZATION role_specification

where role_specification can be:

    user_name
  | CURRENT_USER
  | SESSION_USER

参数说明:

  • schema_name:将要创建的模式名称,不建议以pg_开头。
  • user_name:拥有该模式的用户的角色名,默认为执行该命令的用户。
  • schema_element:SQL语句,创建属于该模式的对象。目前,只接受CREATE TABLE、 CREATE VIEW、CREATE INDEX、CREATE SEQUENCE、 CREATE TRIGGER和GRANT子句。其它类型的对象需要在创建完模式之后,使用独立的命令创建。
  • IF NOT EXISTS:如果同名模式已经存在,那么跳过创建操作,通知用户;否则创建模式。使用该选项时,不能指定schema_element子句。

示例

使用默认参数创建模式

tdsql=# create schema tbase_1;
CREATE SCHEMA
tdsql=# \dn tbase_1
List of schemas
 Name  | Owner 
-------+-------
 tbase_1 | tbase
(1 row)

扩展语法,不存在时才创建

tdsql=# create schema if not exists tbase; 
NOTICE:  (42P06) schema "tbase" already exists, skipping
CREATE SCHEMA

创建时指定所属用户

指定所属用户为CURRENT_USER

tdsql=# create user cu with superuser;
CREATE ROLE
tdsql=# set role cu;
SET
tdsql=# create schema tbase_cu AUTHORIZATION current_user;
CREATE SCHEMA
tdsql=# \dn tbase_cu
 List of schemas
   Name   | Owner 
----------+-------
 tbase_cu | cu
(1 row)

指定所属用户为SESSION_USER

tdsql=# create user cu with superuser;
CREATE ROLE
tdsql=# set role cu;
SET
tdsql=# create schema tbase_su AUTHORIZATION session_user;
CREATE SCHEMA
tdsql=# \dn tbase_su
 List of schemas
   Name   | Owner 
----------+-------
 tbase_su | tbase
(1 row)

指定所属用户为当前存在的用户

tdsql=# create user pgxc;
CREATE ROLE
tdsql=# create schema tbase_pgxc AUTHORIZATION pgxc;
CREATE SCHEMA
tdsql=# \dn tbase_pgxc
  List of schemas
    Name    | Owner 
------------+-------
 tbase_pgxc | pgxc
(1 row)

指定schema_element

CREATE SCHEMA hollywood
    CREATE TABLE films (title text, release date, awards text[])
    CREATE VIEW winners AS
        SELECT title, release FROM films WHERE awards IS NOT NULL;
tdsql=# \d hollywood.films
              Table "hollywood.films"
 Column  |  Type  | Collation | Nullable | Default 
---------+--------+-----------+----------+---------
 title   | text   |           |          | 
 release | date   |           |          | 
 awards  | text[] |           |          | 

tdsql=# \d hollywood.winners
            View "hollywood.winners"
 Column  | Type | Collation | Nullable | Default 
---------+------+-----------+----------+---------
 title   | text |           |          | 
 release | date |           |          |