ALTER TABLE命令用于在創(chuàng)建表后更改表。 您可以使用ALTER命令執(zhí)行兩種操作:
語法:
ALTER (TABLE | COLUMNFAMILY) <tablename> <instruction>
您可以使用ALTER命令在表中添加一列。 在添加列時,您必須知道列名稱與現(xiàn)有列名稱不沖突,并且表不使用緊湊存儲選項進(jìn)行定義。
語法:
ALTER TABLE table name
ADD new column datatype;
示例:
現(xiàn)在舉個例子來說明在已經(jīng)創(chuàng)建的名為“student”的表上使用ALTER命令。 這里我們在名為student的表中添加一個名為student_email的文本數(shù)據(jù)類型列。

使用以下命令后:
ALTER TABLE student ADD student_email text;
執(zhí)行上面命令添加一個新列。 您可以使用SELECT命令檢查它。
cqlsh> use yiibai_ks;
cqlsh:yiibai_ks>
cqlsh:yiibai_ks> select * from student;
student_id | student_city | student_fees | student_name | student_phone
------------+--------------+--------------+--------------+---------------
(0 rows)
cqlsh:yiibai_ks> ALTER TABLE student ADD student_email text;
cqlsh:yiibai_ks> select * from student;
student_id | student_city | student_email | student_fees | student_name | student_phone
------------+--------------+---------------+--------------+--------------+---------------
(0 rows)
cqlsh:yiibai_ks>
刪除一列
您還可以使用ALTER命令從表中刪除現(xiàn)有的列。 在從表中刪除列之前,應(yīng)該檢查表是否沒有使用緊湊存儲選項進(jìn)行定義。
語法:
ALTER table name DROP column name;
示例:
讓我們舉個例子,從名為student的表中刪除一個名為student_email的列。
使用以下命令后:
ALTER TABLE student DROP student_email;
現(xiàn)在,您可以看到student表中名為“student_email”的列現(xiàn)在已被刪除。如果要刪除多個列,請使用“,”分隔列名。
cqlsh:yiibai_ks> ALTER TABLE student ADD student_email text;
cqlsh:yiibai_ks> select * from student;
student_id | student_city | student_email | student_fees | student_name | student_phone
------------+--------------+---------------+--------------+--------------+---------------
(0 rows)
cqlsh:yiibai_ks> ALTER TABLE student DROP student_email;
cqlsh:yiibai_ks> select * from student;
student_id | student_city | student_fees | student_name | student_phone
------------+--------------+--------------+--------------+---------------
(0 rows)
cqlsh:yiibai_ks>
看這個例子:
這里我們將刪除以下兩列:student_fees和student_phone。
ALTER TABLE student DROP (student_fees, student_phone);
輸出結(jié)果如下所示 -
cqlsh:yiibai_ks> ALTER TABLE student DROP student_email;
cqlsh:yiibai_ks> select * from student;
student_id | student_city | student_fees | student_name | student_phone
------------+--------------+--------------+--------------+---------------
(0 rows)
cqlsh:yiibai_ks> ALTER TABLE student DROP (student_fees, student_phone);
cqlsh:yiibai_ks> select * from student;
student_id | student_city | student_name
------------+--------------+--------------
(0 rows)
cqlsh:yiibai_ks>