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

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 392
    Comment on it

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

    Primary key contains UNIQUE values only and the column defined as Primary key column can not be NULL. A table can have only one PRIMARY KEY.

    PRIMARY KEY Constraint on CREATE TABLE

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

    Example

        CREATE TABLE employee
        (
        id int NOT NULL,
        first_name varchar(45) NOT NULL,
        last_name varchar(45),
        country varchar(45),
        PRIMARY KEY (id)
        );
    

    We can also define PRIMARY KEY 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 pk_employeeId PRIMARY KEY (id,first_name)
        );
    

    PRIMARY KEY Constraint on ALTER TABLE

    We can also create PRIMARY KEY constraint on a column when the table is already created, for that we use ALTER command but the column must be declared as NOT NULL (When the table was created).

    Syntax:

        ALTER TABLE table_name
        ADD PRIMARY KEY column_name
    

    Example:

        ALTER TABLE employee
        ADD PRIMARY KEY (id);
    

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

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

    To DROP a PRIMAR KEY Constraint

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

        ALTER TABLE Persons
        DROP PRIMARY KEY;
    

    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: