【PG】PostgressSql单表备份数据

PostgresSql

备份表/数据,无索引与约束 (CREATE TABLE AS)

CREATE TABLE [if not exists] 新表名 AS table  旧表 [with [no] data]
  • if not exists:判断表是否存在,如果不存在进行创建,存在则不进行创建
  • with data:复制数据
  • with no data:不复制数据
    仅复制表结构,不会复制数据、索引、字段约束(非空约束等)。
create table if not exists employees_20231118 as table employees with no data;

image
image
image

复制表结构和数据,不会复制索引、字段约束(非空约束等)

create table if not exists employees_20231119 as table employees with data;
create table if not exists employees_20231119 as table employees;
SELECT * INTO employees_202311191059 FROM employees;

image
image

有条件的备份数据

create table if not exists employees_20231119 as select * from  employees where id > 30;
SELECT * INTO employees_202311191059 FROM employees WHERE id >= 60;

备份表及数据有索引和约束(CREATE TABLE)

备份表无数据,字段有约束,无索引

CREATE TABLE  employees_202311191058 ( like employees);

image
备份表无数据,字段有约束,有索引

CREATE TABLE  employees_202311191058 ( like employees  INCLUDING indexes );

image
**备份表所有信息 **

CREATE TABLE  employees_202311191058 ( like employees  INCLUDING indexes );
insert INTO employees_202311191058 (select * from employees where ID > 60);
  • CREATE TABLE AS 和 CREATE TABLE 区别
    • CEATE TABLE AS 从一个查询的结果创建一个新表
    • CEATE TABLE 是创建一个新表
  • CREATE TABLE AS 和 SELECT * INTO :CREATE TABLE AS 是被推荐的语法,因为这种形式的SELECT INTO在ECPG 或PL/pgSQL中不可用,因为它们对 INTO子句的解释不同。
  • CREATE TABLE employees_202311191058 ( like employees) 使用时需要注意,原表的建表语句中如果有字段使用 “serial4” 则使用这种方式创建的表是有问题的,原表中会有一个依赖表 employees_id_seq,新建的不会有对应的_id_seq
posted @ 2023-11-19 11:52  此木|西贝  阅读(817)  评论(0)    收藏  举报