1. 用途定位

特性 template0 template1
设计目的 提供一个“原始、干净”的模板 作为默认模板,支持用户自定义
是否可修改 不可修改(系统保留) 可以被用户修改

2. 内容差异

特性 template0 template1
初始状态 完全干净,无任何用户对象 可能包含用户自定义对象(如表、函数等)
是否可继承内容 不会继承任何用户定义的内容 会继承用户在其中添加的所有对象

3. 灵活性

特性 template0 template1
字符编码/区域设置 支持自定义(可更改) 固定为初始化时的值(不可更改)
适用场景 创建完全独立、无依赖的数据库 复用已有配置或对象的数据库

4. 典型使用场景

  • 使用 template0

    • 需要创建一个全新的、干净的数据库。
    • 需要指定不同于默认的字符编码(如 SQL_ASCII)或区域设置(如 LC_COLLATE = 'C')。
    • 不希望继承任何用户自定义的对象或配置。
  • 使用 template1

    • 希望复用 template1 中已有的配置、扩展或对象。
    • 创建常规数据库,无需特殊编码或区域设置要求。

5. 关键限制

  • 如果需要自定义字符编码(ENCODING)或区域设置(LC_COLLATE/LC_CTYPE),只能使用 template0
  • 使用 template1 时,其编码和区域设置是固定的,无法更改。

总结一句话:

  • template0:干净、灵活,适合创建特殊需求的数据库。
  • template1:默认、可定制,适合复用现有配置的场景。

示例

template1=# create database xx WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'C' LC_CTYPE = 'C';
CREATE DATABASE
template1=# create database xx2 WITH TEMPLATE = template1 ENCODING = 'UTF8' LC_COLLATE = 'C' LC_CTYPE = 'C';
CREATE DATABASE
template1=# \l xx*
                                        List of databases
 Name |  Owner   | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges
------+----------+----------+---------+-------+------------+-----------------+-------------------
 xx   | postgres | UTF8     | C       | C     |            | libc            |
 xx2  | postgres | UTF8     | C       | C     |            | libc            |
(2 rows)

template1=# create database xx3 WITH TEMPLATE = template1 ENCODING = 'SQL_ASCII' LC_COLLATE = 'C' LC_CTYPE = 'C';
ERROR:  new encoding (SQL_ASCII) is incompatible with the encoding of the template database (UTF8)
HINT:  Use the same encoding as in the template database, or use template0 as template.
template1=#
template1=# create database xx3 WITH TEMPLATE = template1 ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF8' LC_CTYPE = 'C';
ERROR:  new collation (en_US.UTF8) is incompatible with the collation of the template database (C)
HINT:  Use the same collation as in the template database, or use template0 as template.
template1=#
template1=#


Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐