Changing primary key of table

We have a table basic profile with following table structure

we don’t want to use it as primary key so first we removed its auto increment the we will remove it from primary key
queries for these are

If you want to make primary key to some other column than we can use following query

above query will not make id1 as auto increment.
to make it a uto incremente we will execute following query insted of above

Now let us check the table description

We can also make composite primary key in existing table for that we use following query

This will make id1 and id2 primary key of table.

Alter table command to add foreign key

We have two tables company and location. First table manages company details and second table stores location detail of company. one company can span in multiple location.
Initially we have created table for company and location as below.

checking the description of both table

Now We find that one company can exists in multiple location so there is one to many relationship between company to location and to access location detail of company we have to create foreign key reference of company to location table.
We have already create location table so without deleted it again we will alter table to add foreign key refrence of company.
For adding new foreign key column we have to first add a column to location table then we will make it foreign key.
Before proceeding lets see the syntax of alter table command

Syntax

Checking location description you will find that a company_id field is added to location table and it is reffeering to company tables

To show detailed description you can use

Drop foreign key constraints

Some times we have to drop the foreign key constraint that already exists, for that we have to first get the foreign key constraint name.
To see detailed description of created table we use following query.

Result of above query is

Here we can see that company_id column is referring company tables id field with the constraint name company_fk_id.

Now we have to drop this constraint for that we use ALTER TABLE as follows

Syntax

Here fk_symbol is foreign key constraint used during table creation here we given company_fk_id. If not given then it is system generated value.

Again checking show create table

So we have successfully removed foreign key reference.

Show mysql create table query

To see created table structure show create table command is used

Syntax

Example

Result

To avoid showing leading and trailing dots we use \G with command syntax is as below

Example

Result
*************************** 1. row ***************************
Table: student
Create Table: CREATE TABLE student (
id int(11) DEFAULT NULL,
first_name varchar(30) DEFAULT NULL,
last_name varchar(30) DEFAULT NULL,
semester varchar(20) DEFAULT NULL,
address varchar(80) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)