Sitemap

SQL

7 min readMar 12, 2023

--

Introduction to SQL

SQL — Structured Query Language ( Structured = it has a spreadsheet like structure with Row’s and Column’s ) (Query is the programming part of the language )

SQL is a programming language designed for managing and manipulating relational databases. In the field of Data analysis and Data Science its use case is huge.

A normal SQL query looks like

select * from database

but when all major parts of SQL functions are applied on a query, then it look like this

SELECT DISTINCT column, AGG_FUNC(column_or_expression), …
FROM databsae1 a
JOIN database2 b
ON database1.column = database2.column
WHERE constraint_expression
GROUP BY column
HAVING constraint_expression
ORDER BY column ASC/DESC
LIMIT count OFFSET COUNT

Query order of Execution

  1. From and join’s

The Form clause and Join’s are going to executed first to determine the total data in the dataset that is being queried. Subqueries are also included in this part for execution. And while processing this and joining two or more tables by using joins it creates a new table where previous tables are merged according to the joins.

Joins

There are many kind of joins for merging two / more than two tables

  1. Inner Join
  2. Left Join
  3. Right Join
  4. Self Join
  5. Outer Join

Before going deep into the joins we have to clear about two important concepts of SQL [ 1. Primary key 2. Foreign Key ]

Primary Key-

  1. The Primary key constraints uniquely identifies each record in a table / database.
  2. Primary key must contains unique values in it( means every value in this column can not be repeated it has to be unique ).
  3. It can not contains null values.
  4. In a table / database there can be only 1 Primary Key .
  5. Primary key can consist of single or multiple columns (fields).

SQL PRIMARY KEY on a TABLE

#MS-SQL
CREATE TABLE new (
ID int NOT NULL,
LastName varchar(80) NOT NULL,
FirstName varchar(80),
Age int,
PRIMARY KEY (ID)
);
# you have to mention the primary key column while creating the database

# SQL Server / Oracle / MS Access

CREATE TABLE NEW (
ID int NOT NULL PRIMARY KEY,
LastName varchar(80) NOT NULL,
FirstName varchar(80),
Age int
);

SQL PRIMARY KEY on ALTER TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the following SQL

ALTER TABLE new
ADD PRIMARY KEY (ID);

DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL

ALTER TABLE new
DROP PRIMARY KEY;

Foreign Key-

A FOREIGN KEY is a field or collection of fields in one table, that refers to the Primary Key in another table.

The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.

A foreign key is a column or combination of columns that is used to establish and enforce a link between the data in two tables to control the data that can be stored in the foreign key table.

A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts and it can be duplicated.

Press enter or click to view image in full size
Primary key Table(PERSONS)
Foreign Key Table (ORDER)

The “PersonID” column in the “Persons” table is the PRIMARY KEY in the "Persons" table.

Get Tanmoy Banerjee’s stories in your inbox

Join Medium for free to get updates from this writer.

The “PersonID” column in the “Orders” table is a FOREIGN KEY in the "Orders" table.

SQL FOREIGN KEY on CREATE TABLE

CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

SQL FOREIGN KEY on ALTER TABLE

To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already created

ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint

ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;

Inner Join

Inner Join Back End Process

There are 2 tables A is the primary key of one table and B is foreign key of another table. if they are going to be joined by Inner Join, then the common elements between those 2 columns A & B are going to appear as a result just like the above image.

select * from table_1 a
inner join
table_2 b
on a.column = b.column

Left Join

Left Join Back End Process

Left Join = Inner Join + ( rest of the elements on left side table ). so , to perform left join at first the two tables gonna perform a inner join and take all those common elements between them after that rest of the elements from left table are going to appear in the result.

select * from table_1 a
left join
table_2 b
on a.column = b.column

Right Join

Right Join Backend Process

Right Join = Inner Join + ( rest of the elements on right side table ). so , to perform left join at first the two tables gonna perform a inner join and take all those common elements between them after that rest of the elements from right table are going to appear in the result.

select * from table_1 a
right join
table_2 b
on a.column = b.column

Scenario_1

Manager asks you to make a list of employees with their respective depts.

select
e.employee_name, d.dept_name
from
employee e
inner join / join
department d
on e.employee_id = d.employee_id

Scenario_2

Fetch all employee name and the departments they belongs to.

select
e.employee_name, d.dept_name
from
employee e
left join
department d
on e.employee_id = d.employee_id

( Why left join is used here rather than inner join > on the left table which is employee table has the all the employee name and right table department table has the necessary departments the employees are in.)

Query is fetch all employees with their departments, so all employee name should be their along with which employees whom has the departments with their own.

Scenario_3

Fetch all departments with employees in it

select
e.employee_name, d.dept_name
from
employee e
right join
deparment d
on
e.employee_id = d.employee_id

on the right table department table has the all department name and left table employee table has the necessary employees whom the departments they are in. Query is fetch all departments with their respective employee, so all department name should be their along with which employees are there.

Cross Join

Just think you are having a date with your partner and both of you just landed on a restaurant , now you ordered the menu card and it has 2 sections in it-

i) Meals ii) Drinks & Beverages

Now you can’t decide which to order with that which drinks you should take because you have many options in your hand.

So, from that infinite possibilities the Cross Join appeared. EX:- Table1 = Meals and Table2 = Drinks & Beverages

select 
t1.table1 , t2.table2
from table1
cross join
table2
Cross Join

Full Join

Press enter or click to view image in full size
Full Join Back End Process

“ Imagine your manager comes to you and says “Give me one employee record file where everything is there about employees” , but you know employee table and department table doesn’t have all records parallel to each other …. so for this type of task full join / full outer join is there”

Full Join = ( inner join + rest of the records of left side table + rest of the records from the right side table )

select
e.employee_name, d.dept_name
from
employee e
full join
deparment d
on
e.employee_id = d.employee_id

Combination Joins

“Suppose your manager again comes to you and ask you to “ fetch the details of employees with their corresponding departments “ and now he wants you to add their location with country that to on a new column “.

Previously you have employee table and department table , but now you also have location table ( which has 1 row 1 column ) / ( multi row’ s and multi columns ) but value is all the same cause all of the employees location is same.

For that,

select
e.employee_name, d.dept_name, country l
from
employee e
inner join
deparment d
on
e.employee_id = d.employee_id
cross join
location l

### but if region is different then we can't use cross join then we have to
use left/right join according to the data.

Self Join

Self Join is kind of a join when a table join with itself , it’s a conditional join.

Suppose you have a data that contains emp_id , emp_name, sr_id, salary

Now your manager asks you to give him the data of “ can show which employee is under which sr. employee”

select 
emp_name .jr as jr.emp,
emp_name as sr.emp
from employee jr
self join
employee sr
on jr.emp_id = sr.sr_id

--

--