SQLite | テーブル | テーブル名の変更とカラムの追加・削除

既存テーブルの名前を変更し、カラムを追加または削除する方法を説明します。

テーブル名を変更する

既存テーブルの名前を変更するにはALTER TABLEを使います。構文は次のとおりです。

ALTER TABLE テーブル名 RENAME TO 新しいテーブル名;

たとえばtable_oldtable_newへ変更します。

alter table table_old rename to table_new;

.tablesで現在のテーブルを確認します。この例にはcustomercustomer2があります。

sqlite> .table
customer   customer2
sqlite> 

customer2userへ変更します。

alter table customer2 rename to user;
sqlite> 
sqlite> alter table customer2 rename to user;
sqlite> 

再度.tablesを実行し、一覧がcustomeruserになったことを確認します。

sqlite> .table
customer  user    
sqlite> 

カラムを追加する

既存テーブルにカラムを追加するにはALTER TABLEを使います。構文は次のとおりです。

ALTER TABLE テーブル名 ADD COLUMN カラム名 [データ型];

この例で使用しているSQLiteではカラムの追加はできますが、DROP COLUMNは使用できません。

新しいカラムはテーブルの末尾に追加され、次の条件を満たす必要があります。

  1. PRIMARY KEYまたはUNIQUE制約は設定できません。
  2. DEFAULTCURRENT_TIMECURRENT_DATECURRENT_TIMESTAMPは指定できません。
  3. NOT NULLを設定する場合は、NULL以外の既定値が必要です。

たとえばmytablenew_columnを追加します。

alter table mytable add column new_column;

既存のuserテーブルにTEXT型のaddressを追加します。まず.schemaで現在のスキーマを確認します。

.schema user
sqlite> .schema user
CREATE TABLE IF NOT EXISTS "user" (id integer, name text);
sqlite>

useraddressを追加します。

alter table user add column address text;
sqlite> 
sqlite> alter table user add column address text;
sqlite> 

再度.schemaを実行し、addressが追加されたことを確認します。

.schema user
sqlite> .schema user
CREATE TABLE IF NOT EXISTS "user" (id integer, name text, address text);
sqlite> 

カラムを削除する

古いSQLiteではDROP COLUMNを使用できません。代わりにDROP TABLEALTER TABLE RENAMEを使います。

置き換え用のテーブルを作成し、必要なデータを移す方法です。

まず.schemaで現在のuserスキーマを確認します。

sqlite> .schema user
CREATE TABLE IF NOT EXISTS "user" (id integer, name text, address text);
sqlite> 

user2を作成し、userのデータをコピーします。

sqlite> create table user2 (id integer, name text);
sqlite> 
sqlite> insert into user2 (id, name) select id, name from user;

元のuserを削除し、user2userへ変更します。

sqlite> drop table user;
sqlite> 
sqlite> alter table user2 rename to user;

再度.schemaを実行し、addressがなくなったことを確認します。

sqlite> .schema user
CREATE TABLE IF NOT EXISTS "user" (id integer, name text);