在 postgres 中更改列类型
本文展示了如何在 postgres 中将列类型更改为另一种数据类型。
使用 alter table
命令更改 postgres 中的列类型
altertable<table_name>altercolumn<column_name>[setdata]type<new_type>;
使用表名
、列名
和新类型
。例如:
createtablestudent(idserialprimarykey,namevarcharnotnull,admission_datedatenotnull,contact_nointnotnull,descriptiontext);
输出:
postgres=# \d student
table "public.student"
column | type | collation | nullable | default
---------------- ------------------- ----------- ---------- -------------------------------------
id | integer | | not null | nextval('student_id_seq'::regclass)
name | character varying | | not null |
admission_date | date | | not null |
contact_no | integer | | not null |
description | text | | |
indexes:
"student_pkey" primary key, btree (id)
postgres=#
要更改学生联系电话的数据类型并将其更改为 varchar
,联系电话之间可以有
或 -
。
所以改变上列数据类型的命令:
altertablestudentaltercolumncontact_notypevarchar;
表说明:
postgres=# alter table student
postgres-# alter column contact_no type varchar;
alter table
postgres=# \d student;
table "public.student"
column | type | collation | nullable | default
---------------- ------------------- ----------- ---------- -------------------------------------
id | integer | | not null | nextval('student_id_seq'::regclass)
name | character varying | | not null |
admission_date | date | | not null |
contact_no | character varying | | not null |
description | text | | |
indexes:
"student_pkey" primary key, btree (id)
postgres=#
如果表中填充了一些行,并且在 contact_no
列中,你有 varchar
或非数字值。
如果你再次尝试将 contact_no
的数据类型更改为 int
,那么 postgres 将显示一个名为 you may need to specify using
的错误。
使用以下 sql 命令插入一行:
insertintostudent(name,admission_date,contact_no,description)values('john doe','2022-01-01','1212125856 ','lorem ipsum');
运行更改数据类型的语句:
postgres=# alter table student
postgres-# alter column contact_no type int;
error: column "contact_no" cannot be cast automatically to type integer
hint: you might need to specify "using contact_no::integer".
postgres=#
因此,你也需要添加这一行。
altertablestudentaltercolumncontact_notypevarcharusingcontact_no::integer;
现在,上面的 sql 命令将被接受。但是,varchar
可能包含前导或尾部的空白,因此你需要去除空格。
更新后的命令将如下所示:
altertablestudentaltercolumncontact_notypevarcharusing(trim(contact_no)::integer);
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
在一个 postgresql 查询中使用多个 with 语句
发布时间:2023/03/20 浏览次数:337 分类:postgresql
-
在本教程中,我们将学习如何使用多个 with 语句在 postgresql 中使用两个临时表执行查询。
发布时间:2023/03/20 浏览次数:185 分类:postgresql
-
本文介绍如何在 ubuntu 上找到 postgresql 数据库的配置文件。
发布时间:2023/03/20 浏览次数:409 分类:数据库
-
本文解释了如何直接从终端/命令行或 psql shell 运行 sql 文件。为此,你需要指定主机名、端口、用户名和数据库名称。
发布时间:2023/03/20 浏览次数:89 分类:postgresql
-
本文展示了如何列出 postgresql 上的活动连接。
在 postgresql 中使用循环
发布时间:2023/03/20 浏览次数:966 分类:postgresql
-
在 pl/sql 中,你可能需要在 postgres 中使用循环。我们可以使用 for 和 while 语句来创建循环。
发布时间:2023/03/20 浏览次数:141 分类:postgresql
-
本文介绍如何在 postgresql 中仅使用单个查询来重命名列以及更改其类型。
发布时间:2023/03/20 浏览次数:233 分类:postgresql
-
本文介绍如何在 postgresql 中使用 select 方法连接列。
发布时间:2023/03/20 浏览次数:281 分类:postgresql
-
本文展示了如何使用 case 语句并给出了 postgresql 中的示例。