SQL concepts to define entities relationship

SQL concepts to define entities relationship

In SQL database is divided into tables and tables maintain relationship with each other. This relationship help us to minimize data duplicity and even help to connect one table to another logically and even help to utilize them efficiently.

What is a ONE to MANY Relationship?

We will try to explain this concept with respect to our current project.
  • A user can have many todos.
  • todos cannot have multiple users.

Relationship diagram:

Users and Todos table structure for this application:


We need to modify these table a little bit to create relationship between these two tables. To make it possible we need to introduce new column to Todos table which will be Primary key of Users table as Foreign Key of Todos table as named owner[FK].

Logical representation through diagram:

Sample data for testing the scenario:



What is a foreign key?

  • A foreign key (FK) is a column within a relational database table that provides a link between two separate tables.
  • A foreign key references a primary key of another table.
  • Most relational databases need foreign keys to be able to link tables together to present data
  • As you can see it in the current scenario creating one to many relation between users and todos tables.

Foreign Keys

It will help to create joints between two or more tables. As you can see that a user id is attached to todos table for information and in authentication we will authorize the user so this user id will be part of JWT(json WEB Token).
  • Each API request, a user will have their ID attached
    • If we have the user ID attached to each request, we can use the ID to find their todos.

Where SQL queries:

select * from todos where owner = 1;
select * from todos where owner = 2;
Will help to filter the data.





Comments

Popular posts from this blog

CRUD Assignment

Python Variables

API Request Method - Post Todos (create and save todo)