mysql primary key

the MySQL primary key  constraint uniquely identifies each record in a database table.

a primary key in MySQL table must contain unique values.it makes searching of record faster.

if the primary key consists of multiple columns,the combination of values in these columns must be unique.

a table has only one primary key.

a primary key column can't contain null values.


mysql primary key  constraint using create table

         create table      users

                            (
                             userid  int      not null,
                             
                             firstname       varchar(255)     not null,
                             
                             lastname       varchar(255),
                             
                             salary            float,  
                             
                             primary key(userid) 
                            );

if you want defining a primary key constraint on multiple columns, use the following mysql syntax :

         create table      users

                            (
                             userid  int      not null   auto_increment,
                             
                             firstname       varchar(255)     not null,
                             
                             lastname       varchar(255),
                             
                             salary            float      not null,  
                             
                             primary key(userid, salary) 
                            );

notea primary key column often has auto_increment attribute that generates a unique sequence for the key automatically.the primary key of the next row is greater than the previous one.


mysql primary key constraints using alter table

to create a primary key constraint on the "userid" column when the table is already created, use the following mysql syntax:

           alter  table   users

                     add   primary key  (userid)

to remove a  primary key  constraint

to remove a primary key constraint, use the following mysql :

         alter   table     persons

                    drop      primary key

you can specify a primary key for the table with the PRIMARY KEY constraint.In a well-designed database schema, a primary key serves as an unchanging unique identifier for each record.If a key is declared as primary, it usually implies the values in it will rarely be modified.

The PRIMARY KEY constraint can best be thought of as a combination of the NOT NULL and UNIQUE constraints because it requires values in the specified field to be neither NULL nor repeated in any other row. PRIMARY KEY constraints can be specified for either a single field or for a composite of multiple fields.