Relationships
Course: SQL databases - chapter 10
Relationships let you store data in different tables and relate it with each other.
Relationships in Mongodb
Section titled “Relationships in Mongodb”Since mongodb is a NoSQL database, you can store any shape of data in it.
If I ask you to store a users details along with their address, you can store it in an object that has the address details.

Relationships in SQL
Section titled “Relationships in SQL”Since SQL can not store objects as such, we need to define two different tables to store this data in.

This is called a relationship , which means that the Address table is related to the Users table.
When defining the table, you need to define the relationship
CREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE addresses ( id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, city VARCHAR(100) NOT NULL, country VARCHAR(100) NOT NULL, street VARCHAR(255) NOT NULL, pincode VARCHAR(20), created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE);SQL query
Section titled “SQL query”To insert the address of a user -
INSERT INTO addresses (user_id, city, country, street, pincode)VALUES (1, 'New York', 'USA', '123 Broadway St', '10001');Now if you want to get the address of a user given an id , you can run the following query -
SELECT city, country, street, pincodeFROM addressesWHERE user_id = 1;Extra - Transactions in SQL
Section titled “Extra - Transactions in SQL”💡 Good question to have at this point is what queries are run when the user signs up and sends both their information and their address in a single request. Do we send two SQL queries into the database? What if one of the queries (address query for example) fails? This would require
transactionsin SQL to ensure either both the user information and address goes in, or neither does
SQL Query
BEGIN; -- Start transaction
INSERT INTO users (username, email, password)VALUES ('john_doe', 'john_doe1@example.com', 'securepassword123');
INSERT INTO addresses (user_id, city, country, street, pincode)VALUES (currval('users_id_seq'), 'New York', 'USA', '123 Broadway St', '10001');
COMMIT;Node.js Code
$1b