SQL keys


Primary keys

The primary key constraint uniquely identifies each record in a table.

The primary key must contain a unique value, and cannot contain a null value.


Syntax -

create table table_name (

column1_name data_type (range) not null,

column2_name data_type (range) not null,

column3_name data_type (range) not null,

  ………..,

primary key(column name)

);

sql foreign key

Foreign key

A foreign key is a key used to link two table together.

A foreign key is a field ( or collection of field ) in one table that refer to the  primary key in another table.


Example

Table 1

Customer_id

Customer_name 

Email

1

Nitu

deynitu1998@gmail.com

2

Sumit

10sumitsarkar@gmail.com

3

Hariom

hariomprajapati9097@gmail.com



Table 2

ORDER_ID

ORDER_DATE

AMOUNT

CUSTOMER_ID

1

'2020/5/6'

55

1

2

'2020/06/06'

100

1

3

'2020/03/12'

203

2

4

'2019/05/13'

76

3



Syntax for table 1 -

create table table_name (

column1_name not null auto increment primary key,

……………,

);

 

Syntax for table 2 -

create table  table_name (

column1_name  data_type  not null auto increment primary key,

column2_name  datatype (range),

…………………,

foreign key ( column_name // column name must same as table 1 primary key)

references table1_name (column name // table 1 column name which is primary key)

);

Note:- Create a column with the same name as table1 primary key column name in table 2  and then put it in foreign key(column name).

                                   

Table 1

sql foreign key

                                                 

Table 2

sql foreign key