SQL to create Foreign Keys and join tables

2

Joining tables is an essential part when creating a database. Most newbies make mistake by not creating primary-foreign key relationship between tables. They just assume table column as primary-foreign which leads to many error later on. In this tutorial you will learn the write sql to create foreign keys and join tables.

Creating and joining tables using SQL

Take an inventory system as an example, we will be creating 3 tables viz. category, brands and products.

  • Category – Products can be classified into category like mobiles, tablets etc.
  • Brands – Every product has a particular brand.
  • Products – The main product tables that has product name, price, category and brands assigned to it,

Creating category table and adding some dummy values.

Creating brands table and adding some dummy values.

Creating products table and adding some dummy values. In this table we join category and brands tables also. It will have two column prd_cat_id which is the foreign key to category table and then prd_brd_id which is foreign key to brands table. I have set ON DELETE RESTRICT so no user can delete category/brands if product is present in the table ( Referential Integrity).

Try to delete category/brands value before deleting values from product table. It wont delete the records if any key is present in the products table.

Hope this helps you learn the basics and therefore you can now create advance SQL to create Foreign Keys and join tables in your projects.

Share.
 

About Author

Entrepreneur & Dreamer

I am a passionate Software Professional, love to learn and share my knowledge with others.

Software is the hardware of my life.

2 Comments

  1. hi shahrukh, just want to know that, how much you earned from hostgator affiliate and adsense ?
    please let me know

    thank you 🙂

Leave A Reply

CommentLuv badge

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.