Wednesday , April 24 2024

Primary Key And Foreign Key In PostgreSQL

In this article, I will make examples by explaining primary key and foreign key on delete and on update.

While creating the personnel table above, we create our table by specifying the table in which PRIMARY KEY is to be put in the table, together with the CONSTRAINT parameter and the PRIMARY KEY command at the end of our table.

While creating our personnel_birth_date table above, we specify that a Foreign key will be created in the CONSTRAINT section, and the ON UPDATE and ON DELETE commands also come into play when specifying this.

ON DELETE CASCADE parameter is used in the personnel_birth_date table.

When the record in the personnel table is deleted with this parameter, it will also delete the relevant record in the personnel_birth_date table.

ON UPDATE and ON DELETE commands can be used by taking the following parameters.

-SET NULL
-SET DEFAULT
-NO ACTION
-CASCADE
-RESTRICT

When the personnel is deleted or updated with the above parameters, it is used to perform operations such as null value in the personnel_birth_date table or the column default value.

Let’s reinforce them with an example.

First, let’s load data into the tables we created.

After inserting our data, let’s delete the record from our personnel table as follows and check whether the personnel has been deleted from the date of birth table as well.

When we query our staff table, we see that the data has been deleted.

As can be seen above, when we check the personnel_date_date table, we see that the second record is deleted from here as well.

Loading

About Faruk Erdem

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories