Say I have created a table like this:
CREATE TABLE table_1(column_1 UNIQUE, column_2 NOT NULL);
Now after I have inserted lots of data, for some reason I need to remove UNIQUE constraint from the first column, that's column_1. Is it possible? If yes, how?
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows these alterations of an existing table: it can be renamed; a column can be renamed; a column can be added to it; or a column can be dropped from it.
Only the RENAME TABLE, ADD COLUMN, RENAME COLUMN, and DROP COLUMN variants of the ALTER TABLE command are supported. Other kinds of ALTER TABLE operations such as ALTER COLUMN, ADD CONSTRAINT, and so forth are omitted.
Introduction to SQLite UPDATE statement First, specify the table where you want to update after the UPDATE clause. Second, set new value for each column of the table in the SET clause. Third, specify rows to update using a condition in the WHERE clause. The WHERE clause is optional.
SQLite only allows normal file access permissions. It does not support GRANT and REVOKE commands as SQLite reads and writes to the disk files. In SQLite, using the ALTER table statement, you can only add a column or rename a table. SQLite doesn't support FOR EACH STATEMENT triggers.
Summary. Use the ALTER TABLE statement to modify the structure of an existing table. Use ALTER TABLE table_name RENAME TO new_name statement to rename a table. Use ALTER TABLE table_name ADD COLUMN column_definition statement to add a column to a table.
Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. Constraints could be column level or table level.
ALTER TABLE
in sqlite is very limited.
You can however, to a limited extent, change some contraints using CREATE INDEX
and CREATE TRIGGER
.
You could, eg:
CREATE TABLE table_1(column_1, column_2);
-- No constrains in table_1
CREATE UNIQUE INDEX t1_c1_1 ON table_1 (column_1);
-- From now, column_1 must be UNIQUE
CREATE TRIGGER t1_c2_1i BEFORE INSERT ON table_1 WHEN column_2 IS NULL BEGIN
SELECT RAISE(ABORT, 'column_2 can not be NULL');
END;
CREATE TRIGGER t1_c2_1u BEFORE UPDATE ON table_1 WHEN column_2 IS NULL BEGIN
SELECT RAISE(ABORT, 'column_2 can not be NULL');
END;
-- From now, NULL column_2 update/insert will fail
DROP TRIGGER t1_c1_1;
-- Now column_1 doesn't need to be UNIQUE
DROP TRIGGER t1_c2_1i;
DROP TRIGGER t1_c2_1u;
-- Now column_2 may be NULL
Note:
Another workaround is duplicating existing table removing constraints:
CREATE TEMP TABLE table_1 AS SELECT * FROM MAIN.table_1;
DROP TABLE table_1;
CREATE TABLE table_1 AS SELECT * FROM TEMP.table1;
-- table_1 is now a copy from initial table_1, but without constraints
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With