JournalSQLJoins2 min

For Those Who Do Not Know JOIN

SQL is a very widespread and easy-to-use language because it is characterized by being close to the sentences we speak—close to our language. I will try to simplify the topic for you in general; it is easy, don't worry.

  • JOIN
  • primary key
  • foreign key
  • one-to-many

SQL is a very widespread and easy-to-use language because it is characterized by being close to the sentences we speak—close to our language. I will try to simplify the topic for you in general; it is easy, don't worry. A database contains tables, and these tables have relationships with each other, such as the relationship between an employee and managers, and each table contains columns.

Look at this image:

There is a link between the tables—let's leave that aside for now.

Suppose there is a table called accounts, and I want to extract some data from it such as the name and website, for example. I would write:

SELECT name, website
FROM accounts

Notice that after the SELECT keyword I wrote the names of the columns I want to retrieve, and after the FROM keyword I wrote the name of the table that contains these columns. What if I want to select all of these columns inside the accounts table?

SELECT *
FROM accounts

Notice the asterisk * after SELECT is a shortcut for writing the name of every column inside the accounts table.

When a database designer translates business logic and starts creating tables, they try in one way or another to break down tables into smaller and smaller tables. This breakdown is compensated for by relationships between tables, so that when we retrieve shared data between these tables, it is easy and makes it feel as if the entire database is just one single table. If we want to link the accounts table with the orders table, we must understand the relationship between them, which is:

  • An account has the right to place more than one order.
  • However, an order is placed by one account.

In this case, the "many" relationship belongs to orders, and the "one" relationship belongs to accounts, because an order can only be placed by one account. This relationship is called one-to-many. Where the "one" side has the Primary Key (PK) with unique values, and the "many" side has the Foreign Key (FK) with repeated values. The join between the two tables is done like this:

SELECT *
FROM accounts
JOIN orders
ON accounts.id = orders.account_id

Primary Key = accounts.id Foreign Key = orders.account_id

You can deepen your understanding through more examples and diagrams of join types via this topic.