2020年12月5日土曜日

SQLite3 テーブル名を変更する (RENAME TABLE)

概要

SQLite3でテーブル名を変更するDDL。 OracleやMySQLなどとほぼ変わらない。


ALTER TABLE old_name RENAME TO new_name;
                

実行例

環境
  • Windows 10 64bit
  • SQLite3 (3.33.0) Command-Line Shell

sqlite> .tables
product
sqlite> ALTER TABLE product RENAME TO item;
sqlite> .tables
item
                

対象テーブルを参照しているスキーマも一緒に変更される

対象はビュー、トリガー、外部キー制約など

  1. 「total_view」ビューが「product」テーブルを参照している
  2. 「product」を「item」に変更すると「total_view」のスキーマも変更される

sqlite> .tables
product     total_view

sqlite> -- # 1.
sqlite> .schema total_view
CREATE VIEW total_view
as
select
    sum(quantity)
from
    "product"
/* total_view("sum(quantity)") */;

sqlite> -- # 2.
sqlite> ALTER TABLE product RENAME TO item;
sqlite> .tables
item        total_view
sqlite> .schema total_view
CREATE VIEW total_view
AS
SELECT
    sum(quantity)
FROM
    "item"
/* total_view("sum(quantity)") */;
                

参考URL