sql constraints

SQL Constraints:
NOT NULL constraint - ensures that a column cannot have a NULL value
default value constraint default - provides the default value when the value of the column is not specified
Unique value constraint unique - ensures that all values ​​in a column are unique
primary key - Uniquely identifies every row/record in a database table
foreign key to create and retrieve data from the database.


sql unique value constraint
add constraint format: alter table add constraint constraint name constraint type (unique, primary key, etc.) (column, can be multiple)

Table already exists, modify id to unique constraint
alter table manager modify id int(10) not null unique;
or:
alter table manager add constraint cmm unique(id,name);

Delete:
alter table manager drop contraint cmm;
if the above sql deletion fails, use the following (my own operation is to set the id as a unique constraint, cmm in the table structure has become an index, and delete it by deleting the index, only name When set as a unique constraint, the above sql executes ok; online, mysql should use the following):
alter table manager drop index cmm;


Create a primary key constraint
: create table manager ( id int(10),name(20),primary key(id,name));
Modify: ALTER TABLE manager add PRIMARY KEY(id); ALTER TABLE manager add CONSTRAINT mana PRIMARY KEY (id ,name);
Delete: alter table manager drop primary key;
Primary key design: 1. No null; 2. No duplication; 3. Cannot be a foreign key to other tables; 4. The table contains a PRIMARY XML index applied to itself


Foreign key constraints
CREATE TABLE manager (id INT(10),NAME varchar(20), sex INT(10),address VARCHAR(20) );
CREATE TABLE staff ( id INT(20),NAME varchar(20),sex INT (10), manaid INT(10) REFERENCES manager(id) )
Modify:
ALTER TABLE staff ADD FOREIGN KEY(manaid) REFERENCES manager(id);
Reason for failure to create or modify: The type length constraints of the two fields are inconsistent, etc.


检查约束
CREATE TABLE staff1 (id INT(10),sex INT (2) NOT NULL ,CHECK (sex<=2))
ALTER TABLE staff ADD CHECK (sex<=1);
alter table staff drop check;


Index
ALTER TABLE manager ADD INDEX INX_SCH (sex) USING BTREE;
Note: It is recommended to add an index to the field that needs to be searched; it will be slower to update a table with an index, and the index itself needs to be updated

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324687261&siteId=291194637