Categories: 資料庫

PostgreSQL 資料庫更改欄位資料類型教學與範例

介紹如何在 PostgreSQL 資料庫中修改資料表的欄位類型。

首先建立示範用的資料表,並插入一些測試的資料:

-- 建立資料表
CREATE TABLE my_table (
  id serial PRIMARY KEY,
  number varchar(10)
);

-- 插入資料
INSERT INTO my_table (number) VALUES ('0102'), ('3029'), ('3921');

查看原始的資料:

-- 查看資料
SELECT * FROM my_table;
 id | number
----+--------
  1 | 0102
  2 | 3029
  3 | 3921
(3 rows)

這裡的 number 欄位原來的資料型態是字串(varchar),若要將 number 欄位改為整數(INT),可以使用 ALTER TABLE 指令:

-- 更改欄位資料類型
ALTER TABLE my_table ALTER COLUMN number TYPE INT USING number::integer;

在更改資料型態時,除了以 TYPE 指定新的資料型態之外,還要加上 USING 來指定舊資料轉換的方式,這裡我們指定轉換的方式就是將原來的 number 資料直接轉換為整數(number::integer)。

接著檢查更改資料型態之後的資料表:

-- 查看資料表
\d my_table
                            Table "public.my_table"
 Column |  Type   | Collation | Nullable |               Default
--------+---------+-----------+----------+--------------------------------------
 id     | integer |           | not null | nextval('my_table_id_seq'::regclass)
 number | integer |           |          |
Indexes:
    "my_table_pkey" PRIMARY KEY, btree (id)

number 已經確實改為 integer 型態了。接著查看轉換之後的資料:

-- 查看資料
SELECT * FROM my_table;
 id | number
----+--------
  1 |    102
  2 |   3029
  3 |   3921
(3 rows)

參考資料:PostgreSQL Tutorial

Share
Published by
Office Guide
Tags: PostgreSQL

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

11 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago