Curriculum
Course: MYSQL
Login

Curriculum

MYSQL

MySQL References

0/140
Text lesson

MySQL Constraints

Create Constraints

Constraints can be defined during table creation using the CREATE TABLE statement or added later using the ALTER TABLE statement.

Syntax

CREATE TABLE table_name (
    column1 datatype constraint,
    column2 datatype constraint,
    column3 datatype constraint,
    ….
);

MySQL Constraints

SQL constraints define rules for data within a table, ensuring data accuracy and reliability by limiting the types of data that can be entered. If data actions violate a constraint, the action is halted to maintain data integrity.

Constraints in SQL can be categorized as column-level or table-level. Column-level constraints are specific to individual columns, while table-level constraints apply to the entire table.

Commonly used constraints in SQL include:

  • NOT NULL: Ensures a column cannot have a NULL value.
  • UNIQUE: Ensures all values in a column are distinct.
  • PRIMARY KEY: Combines NOT NULL and UNIQUE, uniquely identifying each row in a table.
  • FOREIGN KEY: Prevents actions that would break relationships between tables.
  • CHECK: Ensures values in a column meet a specific condition.
  • DEFAULT: Sets a default value for a column if none is specified.
  • CREATE INDEX: Used to enhance data retrieval speed from the database.