SQL 2

Primary Key:

Primary key is used to uniquely identify the each row in the table. Primary key column must contain unique value and can not be null means that column has to contain some value.

If we want to define any column as primary key, we can define a primary key when we create table or modify it.

One table can contain multiple primary key, it is called composite primary key.

Syntax: 
                create table table_name(column1 data type primary key,
                column2 datatype, ...);
                or
                create table table_name(column1 data type,
                column2 datatype, ..., primary key (column1));

Created...




How to add primary key to the existing table:
Syntax:
                alter table table_name add constraint primary key(column_name);
Primary key added...





How to remove primary key from the existing table:
Syntax:
                alter table table_name drop primary key;

Primary key removed...
Verified...






Foreign Key:

In simple, foreign key is used to connect two tables.
A foreign key can be one field or collection of fields in table, that refers to primary key in another table.

Syntax:
            create table table_name(column1 datatype primary key, column2
            datatype, column3 datatype, column4 datatype,
            foreign key (column_name) references
            parent_table_name(primary_key_column_name));

first, let's create parent table (primary key table)

Now, let's create child table (foreign key table)

foreign key table structure


Comments

Popular posts from this blog

SQL

SQL Examples

SQL Commands