0% found this document useful (0 votes)
13 views14 pages

SQL UNION, JOIN, and Data Management Guide

The document provides an overview of SQL concepts including UNION, JOINs, DELETE, TRUNCATE, and DROP commands, as well as primary and foreign keys. It explains the differences between UNION and JOIN, indexing in SQL, and the use of views, along with examples and real-world applications. Additionally, it covers aggregate functions and their usage in SQL queries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views14 pages

SQL UNION, JOIN, and Data Management Guide

The document provides an overview of SQL concepts including UNION, JOINs, DELETE, TRUNCATE, and DROP commands, as well as primary and foreign keys. It explains the differences between UNION and JOIN, indexing in SQL, and the use of views, along with examples and real-world applications. Additionally, it covers aggregate functions and their usage in SQL queries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

✅ Definition:

UNION and UNION ALL are used to combine the results of two or more SELECT
statements.

🔑 Key Differences:
Feature​ UNION​UNION ALL

Duplicates​ Removes duplicate records​ Includes all records, even duplicates


Performance​ Slower (because it checks for duplicates)​ Faster (no duplicate check)

🧠 Interview-style Explanation:
> "UNION and UNION ALL are used when we want to combine the result sets of multiple
SELECT queries.

UNION removes duplicate rows automatically.

UNION ALL keeps all rows, including duplicates.

Both require that the number and order of columns in the queries must be the same and the
data types should be compatible."

📌 Example:
SELECT city FROM Customers
UNION
SELECT city FROM Suppliers;

> This returns a unique list of cities from both tables.

SELECT city FROM Customers


UNION ALL
SELECT city FROM Suppliers;

> This returns all cities from both tables, including duplicates.

🎯 When to Use:
Use UNION when you want unique results.

Use UNION ALL when you need all records and performance matters.
DELETE

Definition: Deletes specific rows from a table based on a condition. The table structure and
its data can be recovered using a transaction (if supported).

Example:

DELETE FROM Students WHERE marks < 40;

🔹 TRUNCATE
Definition: Removes all rows from a table. It is faster than DELETE and cannot be rolled
back in most databases. The table structure remains.

Example:

TRUNCATE TABLE Students;

🔹 DROP
Definition: Deletes the entire table, including all rows and its structure. The table is
permanently removed from the database.

Example:

DROP TABLE Students;

Primary Key

Definition: A column (or set of columns) in a table that uniquely identifies each row.

Rules:

Cannot have duplicate values.

Cannot contain NULL values.

Purpose: Ensures each record is unique.

Example:

CREATE TABLE Students (


student_id INT PRIMARY KEY,
name VARCHAR(100)
);

Here, student_id is the Primary Key – no two students can have the same ID.

---

🔹 Foreign Key
Definition: A column (or set of columns) that creates a link between two tables by referring to
the Primary Key of another table.

Purpose: Maintains referential integrity between related tables.

Example:

CREATE TABLE Marks (


mark_id INT PRIMARY KEY,
student_id INT,
score INT,
FOREIGN KEY (student_id) REFERENCES Students(student_id)
);

Here, student_id in Marks is a Foreign Key that refers to the student_id in the Students table.

Create the Main Table: Students

CREATE TABLE Students (


student_id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50)
);

student_id is the Primary Key – uniquely identifies each student.

Sample Data Insertion

-- Insert into Students


INSERT INTO Students (student_id, name, department)
VALUES (1, 'Kavya', 'IT'), (2, 'Arun', 'CSE');

🔹 What is SQL?
SQL (Structured Query Language) is a standard language used to store, retrieve, manage,
and manipulate data in a relational database. It allows users to perform operations such as
creating tables, inserting records, querying data, updating existing records, and controlling
access to the database.

🔹 Categories of SQL Commands


Category​ Full Form​ Examples

DDL​ Data Definition Language​ CREATE, ALTER, DROP, TRUNCATE


DML​ Data Manipulation Language​INSERT, UPDATE, DELETE
DQL​ Data Query Language​ SELECT
DCL​ Data Control Language​ GRANT, REVOKE
TCL​ Transaction Control Language​ COMMIT, ROLLBACK, SAVEPOINT

What is a JOIN in SQL?

A JOIN is used to combine rows from two or more tables based on a related column
between them, usually a Primary Key–Foreign Key relationship.

🔹 Types of JOINs in SQL


Type of JOIN​ Description

INNER JOIN​ Returns only matching rows from both tables


LEFT JOIN​ Returns all rows from the left table, and matched rows from the right table
RIGHT JOIN​ Returns all rows from the right table, and matched rows from the left table
FULL JOIN​ Returns all rows when there is a match in one of the tables
CROSS JOIN​ Returns a Cartesian product (all combinations of rows)
SELF JOIN​ Joining a table with itself

🔹 Example Tables
Students Table:

student_id​ name

1​ Kavya
2​ Arun
3​ Divya

Marks Table:

mark_id​ student_id​ subject​score

101​ 1​ Maths​ 90
102​ 2​ Physics​ 85

✅ 1. INNER JOIN
Returns only students who have marks.

SELECT [Link], [Link], [Link]


FROM Students
INNER JOIN Marks ON Students.student_id = Marks.student_id;

Result:

name​ subject​score

Kavya​ Maths​ 90
Arun​ Physics​ 85

✅ 2. LEFT JOIN (or LEFT OUTER JOIN)


Returns all students, even if they have no marks.

SELECT [Link], [Link], [Link]


FROM Students
LEFT JOIN Marks ON Students.student_id = Marks.student_id;

Result:

name​ subject​ score

Kavya​ Maths. ​ 90
Arun​ Physics​ 85
Divya​ NULL​ NULL

---

✅ 3. RIGHT JOIN (or RIGHT OUTER JOIN)


Returns all marks entries, even if student data is missing.

SELECT [Link], [Link], [Link]


FROM Students
RIGHT JOIN Marks ON Students.student_id = Marks.student_id;
Result:

name​ subject​score

Kavya​ Maths​ 90
Arun​ Physics​ 85

---

✅ 4. FULL JOIN (or FULL OUTER JOIN)


Returns all rows from both tables, matched when possible.

SELECT [Link], [Link], [Link]


FROM Students
FULL JOIN Marks ON Students.student_id = Marks.student_id;

Result (varies by DBMS):

name​ subject​score

Kavya​ Maths​ 90
Arun​ Physics​ 85
Divya​ NULL​ NULL

Note: MySQL doesn't support FULL JOIN directly. You can simulate using UNION of LEFT
and RIGHT JOINs.

✅ 5. CROSS JOIN
Returns all possible combinations (Cartesian Product).

SELECT [Link], [Link]


FROM Students
CROSS JOIN Marks;

If there are 3 students and 2 marks, the result will have 3 × 2 = 6 rows.

✅ 6. SELF JOIN
Join a table to itself (useful for comparing rows).
SELECT [Link] AS Student1, [Link] AS Student2
FROM Students A, Students B
WHERE A.student_id < B.student_id;

🔁 Summary of SQL JOINs


JOIN Type​ Returns...

INNER JOIN​ Only matched rows from both tables


LEFT JOIN​ All rows from left table + matched from right
RIGHT JOIN​ All rows from right table + matched from left
FULL JOIN​ All matched and unmatched rows from both tables
CROSS JOIN​ All combinations of rows from both tables
SELF JOIN​ Data joined within the same table

the difference between UNION and JOIN in points:

JOIN combines columns from two or more tables based on related columns (like keys).

UNION combines rows from two or more result sets, stacking them vertically.

JOIN requires a condition to match rows between tables (e.g., ON clause).

UNION just appends rows from multiple queries, no matching needed.

JOIN results in wider tables (more columns).

UNION results in longer tables (more rows).

Tables in JOIN don’t need to have the same number of columns.

Tables in UNION must have the same number of columns with compatible data types.

JOIN keeps related data together in one row.

UNION combines datasets with similar structure but unrelated rows.

“What is indexing in SQL?” in an interview:

---

Answer:

"Indexing in SQL is a technique used to speed up the retrieval of data from a database table.
An index is like a pointer or a lookup table that helps the database engine quickly find the
rows that match a query condition, without scanning the entire table. It works similarly to the
index in a book, where you can quickly locate the page number for a topic instead of reading
the whole book.

Indexes improve query performance, especially for large tables, but they can also slow down
data modification operations like INSERT, UPDATE, and DELETE because the index needs
to be maintained. Common types of indexes include B-tree and hash indexes.”

Summary to say in an interview:

"Indexing is creating a data structure on a column to speed up SELECT queries."

"You can create an index using CREATE INDEX."

"Indexes improve read performance but can slow down write operations because they need
to be updated."

"Primary key and unique constraints automatically create indexes.”

✅ Interview Answer:
"DBMS stands for Database Management System. It is software that is used to store,
manage, and retrieve data efficiently. A DBMS allows users to create databases, insert,
update, and delete data, and perform queries to retrieve specific information. It ensures data
consistency, security, and supports multiple users accessing the data at the same time."

✅ Simple Explanation:
Think of a DBMS like a digital filing system that helps store and manage large amounts of
data.

Instead of managing data manually in files or spreadsheets, DBMS lets you do it in a


structured way using tables.

Real-Life Analogy: "Window View"

Think of a view like a window in a building.


You’re not entering the building (the actual table), but you can see part of what’s inside
through the window (view).

SQL Views
In SQL, views contain rows and columns similar to a table, however, views don't hold the
actual data.

You can think of a view as a virtual table environment that's created from one or more tables
so that it's easier to work with data.

Creating a View in SQL


We can create views in SQL by using the CREATE VIEW command. For example,
CREATE VIEW us_customers AS
SELECT customer_id, first_name
FROM Customers
WHERE Country = 'USA';

Now to select the customers who lives in USA, we can simply run,

SELECT *
FROM us_customers;

Updating a View
It's possible to change or update an existing view using the CREATE OR REPLACE VIEW
command. For example,
CREATE OR REPLACE VIEW us_customers AS
SELECT *
FROM Customers
WHERE Country = 'USA';

Deleting a View
We can delete views using the DROP VIEW command. For example,

DROP VIEW us_customers;

SQL code two table views


CREATE VIEW order_details AS
SELECT Customers.customer_id, Customers.first_name, [Link]
FROM Customers
JOIN Orders
ON Customers.customer_id = Orders.customer_id;

✅ Interview Answer:
"Aggregate functions in SQL are used to perform calculations on a group of rows and return
a single result. They are commonly used with the GROUP BY clause to summarize data,
such as calculating totals, averages, counts, etc."

📊 Common Aggregate Functions in SQL:


Function​ Description​ Example

COUNT()​ Counts the number of rows​ SELECT COUNT(*) FROM Students;


SUM()​ Adds up values in a numeric column​SELECT SUM(Salary) FROM Emp;
AVG()​ Calculates the average value​SELECT AVG(Marks) FROM Students;
MIN()​ Finds the minimum value​ SELECT MIN(Age) FROM Users;
MAX()​ Finds the maximum value​ SELECT MAX(Price) FROM Products;
Second maximum salary
SELECT MAX(Salary) AS SecondHighest
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);

✅ Interview Answer:
"A database is used in real-time scenarios to store, manage, and retrieve large amounts of
data quickly and efficiently. It helps in organizing data, ensuring security, supporting multiple
users, and enabling fast access to critical information in various applications like banking,
e-commerce, healthcare, education, and more."

💡 Real-Time Scenarios with Examples:


1. 🏦 Banking Systems

Storing customer details, account balances, and transaction histories.

Example Query:

SELECT * FROM Transactions WHERE AccountID = 1234;

2. 🛒 E-commerce Platforms (like Amazon, Flipkart)


Managing products, orders, user profiles, and payment details.

Example Query:

SELECT ProductName, Price FROM Products WHERE Category = 'Mobiles';

3. 🏥 Hospitals & Healthcare


Storing patient records, doctor appointments, prescriptions.

Example Query:

SELECT * FROM Patients WHERE Diagnosis = 'Diabetes';

4. 🎓 Educational Portals
Maintaining student info, marks, attendance, and course materials.

Example Query:

SELECT AVG(Marks) FROM Students WHERE Subject = 'Math';


5. 🚕 Cab Services (like Ola, Uber)
Managing ride details, driver info, user ratings, and GPS locations.

Example Query:

SELECT * FROM Rides WHERE DriverID = 567 AND Status = 'Completed';

T COUNT(*) FROM Posts WHERE UserID = 89;

✅ What is a View in SQL?


> A view is a virtual table in SQL that shows data from one or more real tables based on a
SELECT query.
It does not store data physically, but behaves like a table when queried.

Syntax:

CREATE VIEW view_name AS


SELECT column1, column2
FROM table_name
WHERE condition;

🔄 Real-Time Usage of Views


1. 🔒 Security: Restrict Column Access

Hide sensitive info like salary or passwords.

HR team sees only name & department, not salary.

2. 📊 Simplifying Complex Joins


Instead of writing long joins repeatedly, create a view once and reuse it.

CREATE VIEW OrderSummary AS


SELECT [Link], [Link], [Link]
FROM Customers c
JOIN Orders o ON [Link] = [Link];

📌 Real-Life Examples:
Industry​ Use of Views

Banking​ Show customer name & balance, but hide account number or credit score.
E-Commerce​ Display only available products to users with stock > 0.
Education​ Show students with high attendance or top performance in specific subjects.
Healthcare​ Create views for doctors to see patient history but hide billing info.

✅ What is INNER JOIN in SQL?


> An INNER JOIN is used to retrieve matching records from two or more tables based on a
common column

It only returns rows where there is a match in both tables.

🔤 Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;

Write a query for the aggregate function


SELECT SUM(Salary) AS TotalSalary
FROM Employees;

Explanation:

SUM(Salary) adds up all the values in the Salary column.

AS TotalSalary gives a name (alias) to the result column.

how you delete records from a table in SQL:

Basic syntax to delete all records from a table:

DELETE FROM table_name;

Example: Delete all employees from the Employees table

DELETE FROM Employees;

Delete specific records using a condition:

DELETE FROM table_name


WHERE condition;

Example: Delete employees with Salary less than 30000

DELETE FROM Employees


WHERE Salary < 30000;

⚠️ Warning:
If you forget the WHERE clause, all records will be deleted!

✅ What is Indexing in SQL?


> Indexing is a technique to speed up data retrieval from a database table.
It works like an index in a book, helping the database find rows faster without scanning the
entire table.

Why is indexing important?

Makes SELECT queries much faster.

Improves performance on large tables.

Especially useful on columns used in WHERE clauses, JOINs, or ORDER BY.

How to create an index?

Syntax:

CREATE INDEX index_name


ON table_name (column_name);

You might also like