Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is UNIQUE Constraint in MySQL?

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 526
    Comment on it

    In MySQL, the UNIQUE constraint is used to uniquely identify each record in a table.

    UNIQUE Constraint on CREATE TABLE

    The following statement creates a UNIQUE constraint on the "id" column when the "employee" table is created: Example

    CREATE TABLE emplyee
    (
    id int NOT NULL,
    first_name varchar(45) NOT NULL,
    last_name varchar(45),
    country varchar(45),
    UNIQUE (id)
    );
    

    We can also define UNIQUE constraint on multiple column, for this use the below statement:

    CREATE TABLE emplyee
    (
    id int NOT NULL,
    first_name varchar(45) NOT NULL,
    last_name varchar(45),
    country varchar(45),
    CONSTRAINT un_employeeId UNIQUE (id,first_name)
    );
    

    UNIQUE Constraint on ALTER TABLE

    We can also create UNIQUE constraint on a column when the table is already created, for that we use ALTER command.

    Syntax:

    ALTER TABLE table_name
    ADD UNIQUE column_name
    

    Example:

    ALTER TABLE employee
    ADD UNIQUE (id);
    

    Similarly we can define UNIQUE constraint on multiple columns when the table is already created as below:

    ALTER TABLE employee
    ADD CONSTRAINT un_employeeId UNIQUE (id,first_name);
    

    To DROP a UNIQUE Constraint

    We can also drop a UNIQUE constraint. To drop a UNIQUE constraint, use the below statement:

    ALTER TABLE employee
    DROP INDEX un_employeeId;
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: