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

SQL Set and Join Operators Explained

The document provides an overview of advanced SQL concepts including relational set operators such as UNION, INTERSECT, and MINUS, as well as various join types like Cross Join and Outer Join. It also covers subqueries, correlated queries, and SQL functions for date, numeric, string manipulation, and data type conversion. Each section includes syntax examples and explanations to illustrate the use of these SQL features.
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)
209 views14 pages

SQL Set and Join Operators Explained

The document provides an overview of advanced SQL concepts including relational set operators such as UNION, INTERSECT, and MINUS, as well as various join types like Cross Join and Outer Join. It also covers subqueries, correlated queries, and SQL functions for date, numeric, string manipulation, and data type conversion. Each section includes syntax examples and explanations to illustrate the use of these SQL features.
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

Advanced SQL:Relational SET Operators: UNION –UNION ALL – INTERSECT - MINUS.

SQL
Join Operators: Cross Join – Natural Join – Join USING Clause – JOIN ON Clause – Outer Join.
Sub Queries and Correlated Queries: WHERE – IN – HAVING – ANY and ALL – FROM. SQL
Functions: Date and Time Function – Numeric Function – String Function – Conversion
Function

Relational Set Operators in RDBMS

Introduction

In Relational Database Management Systems (RDBMS), set operators are used to


combine the results of two or more queries into a single result.
They work just like set operations in mathematics (Union, Intersection, Difference, etc.).

 They operate on rows (tuples) returned by SELECT queries.

 The queries involved must have:

1. Same number of columns.


2. Same data type for corresponding columns.
3. Same order of columns.
Types of Relational Set Operators

(a) UNION

 Combines the results of two queries and removes duplicates.


 Similar to mathematical union.
Syntax:

SELECT column_list FROM table1

UNION

SELECT column_list FROM table2;

Example:

CREATE TABLE Department_A ( student_id NUMBER, name VARCHAR2(30));

CREATE TABLE Department_B (student_id NUMBER, name VARCHAR2(30));

-- Department A

INSERT INTO Department_A VALUES (101, 'Ravi');

INSERT INTO Department_A VALUES (102, 'Meena');

INSERT INTO Department_A VALUES (103, 'Arjun');

-- Department B
INSERT INTO Department_B VALUES (102, 'Meena');

INSERT INTO Department_B VALUES (103, 'Arjun');

INSERT INTO Department_B VALUES (104, 'Kiran');

SELECT * FROM Department_A ORDER BY student_id;

STUDENT_ID NAME
101 Ravi
102 Meena
103 Arjun
SELECT * FROM Department_B ORDER BY student_id;

STUDENT_ID NAME
102 Meena
103 Arjun
104 Kiran
SELECT student_id FROM Department_A

UNION

SELECT student_id FROM Department_B;

STUDENT_ID
101
102
103
104
👉 This returns the list of students present in either Department_A or Department_B (no
duplicates).

(b) UNION ALL

 Same as UNION, but does not remove duplicates.


 Faster than UNION since no duplicate check is performed.
Example:

SELECT student_id FROM Department_A

UNION ALL SELECT student_id FROM Department_B;

STUDENT_ID
101
102
102
103
103
104
👉 This returns all students from both departments including duplicates.
(c) INTERSECT

 Returns only the common rows between two queries.


 Similar to mathematical intersection.
Example:

SELECT student_id FROM Department_A

INTERSECT

SELECT student_id FROM Department_B;

STUDENT_ID
102
103
👉 This returns only those students who are enrolled in both departments.

(d) MINUS / EXCEPT (DBMS dependent)

 Returns rows from the first query that are not present in the second query.
 Known as MINUS in Oracle and EXCEPT in SQL Server/PostgreSQL.
Example (Oracle): in A but not in B

SELECT student_id FROM Department_A

MINUS

SELECT student_id FROM Department_B;

STUDENT_ID
101
👉 This returns students who are only in Department_A but not in Department_B.

SQL Join Operators: Cross Join

Introduction

A Cross Join is a type of SQL join that returns the Cartesian product of two tables.

 That means every row from the first table is paired with all rows from the second
table.
 It does not require a join condition.
 If the first table has m rows and the second table has n rows, then the result will
contain m × n rows.
Cross Join is usually not used in real-time queries unless it is specifically required, because
it can produce a very large result set.

Syntax:

SELECT column_list
FROM table1

CROSS JOIN table2;

Example

Students Table

Student_ID Name City

1 Selva Chennai

2 Kumar Vellore

Subjects Table

Subject_ID Subject_Name

101 Math

102 Science

Query

SELECT s.Student_ID, [Link], sub.Subject_ID, sub.Subject_Name

FROM Students s

CROSS JOIN Subjects sub;

Result (Cartesian Product)

Student_ID Name Subject_ID Subject_Name

1 Selva 101 Math

1 Selva 102 Science

2 Kumar 101 Math

2 Kumar 102 Science

Natural Join

Introduction

 A Natural Join is a type of join that automatically matches columns between


two tables with the same name and data type.
 It eliminates duplicate columns from the result.
 Unlike Cross Join, it requires at least one column with the same name in both
tables.
 It is basically like an INNER JOIN with implicit condition on columns having the
same name.
Syntax

SELECT column_list

FROM table1

NATURAL JOIN table2;

Example

Students Table

Student_ID Name City

1 Selva Chennai

2 Kumar Vellore

3 Raja Madurai

Marks Table

Student_ID Subject Mark

1 Math 85

2 Science 78

3 Math 90

Query

SELECT Student_ID, Name, City, Subject, Mark

FROM Students

NATURAL JOIN Marks;

Result

Student_ID Name City Subject Mark

1 Selva Chennai Math 85


Student_ID Name City Subject Mark

2 Kumar Vellore Science 78

3 Raja Madurai Math 90

JOIN with USING Clause

Definition

 The USING clause is used when both tables have a column with the same name.
 It is a shorter way than ON clause when join condition is based on columns with the
same name.
Syntax

SELECT column_list

FROM table1

JOIN table2

USING (common_column);

Example

Students Table

Student_ID Name City

1 Selva Chennai

2 Kumar Vellore

3 Raja Madurai

Marks Table

Student_ID Subject Mark

1 Math 85

2 Science 78

3 Math 90
Query

SELECT Student_ID, Name, City, Subject, Mark

FROM Students

JOIN Marks

USING (Student_ID);

Result

Student_ID Name City Subject Mark

1 Selva Chennai Math 85

2 Kumar Vellore Science 78

3 Raja Madurai Math 90

JOIN with ON Clause

Definition

 The ON clause is more flexible than USING because it allows you to specify any join
condition, even when column names are different.
Syntax

SELECT column_list

FROM table1

JOIN table2

ON [Link] = [Link];

Example

Suppose in the Marks Table, the column name is Stud_ID instead of Student_ID.

Marks Table

Stud_ID Subject Mark

1 Math 85

2 Science 78

3 Math 90
Query

SELECT s.Student_ID, [Link], [Link], [Link], [Link]

FROM Students s

JOIN Marks m

ON s.Student_ID = m.Stud_ID;

Result

Student_ID Name City Subject Mark

1 Selva Chennai Math 85

2 Kumar Vellore Science 78

3 Raja Madurai Math 90

Outer Join

Definition

 Outer Join returns all rows from one table, and the matching rows from the other
table.
 If there is no match, NULL values are returned.
 Types:
o LEFT OUTER JOIN → All rows from left table + matched rows from right.

o RIGHT OUTER JOIN → All rows from right table + matched rows from left.

o FULL OUTER JOIN → All rows from both tables, with NULL where no match
exists.

Example: LEFT OUTER JOIN

Students Table

Student_ID Name City

1 Selva Chennai

2 Kumar Vellore

3 Raja Madurai

4 John Trichy
Marks Table

Student_ID Subject Mark

1 Math 85

2 Science 78

3 Math 90

Query

SELECT s.Student_ID, [Link], [Link], [Link], [Link]

FROM Students s

LEFT OUTER JOIN Marks m

ON s.Student_ID = m.Student_ID;

Result

Student_ID Name City Subject Mark

1 Selva Chennai Math 85

2 Kumar Vellore Science 78

3 Raja Madurai Math 90

4 John Trichy NULL NULL

Subqueries and Correlated Queries

What is a Subquery?

 A subquery is a query inside another query.

 It is enclosed in parentheses (...).

 It can be used in SELECT, FROM, WHERE, or HAVING clauses.

Example (Simple Subquery)

SELECT Name, City

FROM Students

WHERE Student_ID = (SELECT Student_ID FROM Marks WHERE Mark = 90);


2. Correlated Subquery

A correlated subquery depends on the outer query for its values.


It executes row by row for the outer query.
👉 Example (Correlated Subquery)

SELECT [Link], [Link]

FROM Students s

WHERE EXISTS (SELECT 1 FROM Marks m WHERE m.Student_ID = s.Student_ID


AND [Link] > 80);

This query checks each student to see if they have any mark greater than 80.

Subqueries with Different Clauses

A. Subquery with WHERE Clause

 Used to filter rows based on subquery results.


Example

SELECT Name, City

FROM Students

WHERE Student_ID = (SELECT Student_ID FROM Marks WHERE Mark = 90);

✔ Returns the student(s) who scored 90 marks.

B. Subquery with IN Clause

 Used when we want to match against multiple values returned by subquery.


Example

SELECT Name, City

FROM Students

WHERE Student_ID IN (SELECT Student_ID FROM Marks WHERE Subject = 'Math');

✔ Returns all students who have taken Math.

C. Subquery with HAVING Clause

 Used to filter groups after aggregation.


Example

SELECT Subject, AVG(Mark) AS AvgMark

FROM Marks
GROUP BY Subject

HAVING AVG(Mark) > (SELECT AVG(Mark) FROM Marks);

✔ Returns subjects whose average mark is greater than the overall average mark.

D. Subquery with ANY / ALL

 ANY → condition is true if any value in subquery satisfies it.


 ALL → condition is true if all values in subquery satisfy it.
Example with ANY

SELECT Name, City

FROM Students

WHERE Student_ID = ANY (SELECT Student_ID FROM Marks WHERE Mark > 85);

✔ Returns students who scored greater than 85 in any subject.

Example with ALL

SELECT Name, City

FROM Students

WHERE Student_ID = ALL (SELECT Student_ID FROM Marks WHERE Mark > 85);

✔ Returns students who scored greater than 85 in all subjects.

E. Subquery in FROM Clause (Inline View)

 Subquery acts like a temporary table.


Example

SELECT Subject, AvgMark

FROM (SELECT Subject, AVG(Mark) AS AvgMark

FROM Marks

GROUP BY Subject) AS SubMarks

WHERE AvgMark > 80;

✔ Creates a temporary result set of average marks per subject and then filters subjects with
average > 80.
SQL Functions

SQL provides built-in functions to perform operations on data. These functions can be
used in SELECT, WHERE, ORDER BY, or any other SQL clause.

1. Date and Time Functions

Functions that work with dates and times.

Common Functions

 SYSDATE → Returns the current system date and time.


 CURRENT_DATE → Returns the current date.
 EXTRACT → Extracts parts (year, month, day) from a date.
 ADD_MONTHS(date, n) → Adds n months to a date.
 MONTHS_BETWEEN(date1, date2) → Finds difference in months.
Example

SELECT SYSDATE AS Today,

EXTRACT(YEAR FROM SYSDATE) AS CurrentYear,

ADD_MONTHS(SYSDATE, 6) AS AfterSixMonths,

MONTHS_BETWEEN(SYSDATE, TO_DATE('2024-01-01','YYYY-MM-DD')) AS
MonthDiff FROM dual;

Output (example)

Today CurrentYear AfterSixMonths MonthDiff

02-SEP-2025 [Link] 2025 02-MAR-2026 14:30 20

2. Numeric Functions

Functions that perform operations on numbers.

Common Functions

 ROUND(n, d) → Rounds number n to d decimals.


 TRUNC(n, d) → Truncates number n to d decimals.
 MOD(m, n) → Returns remainder of m/n.
 ABS(n) → Returns absolute value of n.
 POWER(m, n) → Returns m^n.
Example

SELECT ROUND(123.456, 2) AS Rounded,

TRUNC(123.456, 1) AS Truncated,

MOD(17, 5) AS Remainder,
ABS(-25) AS Absolute,

POWER(2, 4) AS PowerValue

FROM dual;

Output

Rounded Truncated Remainder Absolute PowerValue

123.46 123.4 2 25 16

3. String Functions

Functions that manipulate text/character values.

Common Functions

 UPPER(str) → Converts to uppercase.


 LOWER(str) → Converts to lowercase.
 INITCAP(str) → Capitalizes first letter of each word.
 LENGTH(str) → Returns length of string.
 SUBSTR(str, start, len) → Extracts substring.
 INSTR(str, substr) → Returns position of substring.
 CONCAT(str1, str2) → Joins two strings.
 LTRIM, RTRIM, TRIM → Removes spaces/characters.
Example

SELECT UPPER('sql functions') AS UpperCase,

LOWER('SQL Functions') AS LowerCase,

INITCAP('sql functions') AS InitCap,

LENGTH('Database') AS Length,

SUBSTR('Database', 1, 4) AS SubString,

INSTR('Database', 'base') AS Position

FROM dual;

Output

UpperCase LowerCase InitCap Length SubString Position

SQL FUNCTIONS sql functions Sql Functions 8 Data 5


4. Conversion Functions

Functions that convert data types.

Common Functions

 TO_CHAR(date/number, format) → Converts to string.


 TO_DATE(string, format) → Converts string to date.
 TO_NUMBER(string) → Converts string to number.
 CAST(expression AS datatype) → Converts explicitly.
Example

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY') AS DateToChar,

TO_DATE('02-09-2025','DD-MM-YYYY') AS StringToDate,

TO_NUMBER('12345') AS StringToNumber,

CAST(123.456 AS INT) AS CastExample

FROM dual;

Output (example)

DateToChar StringToDate StringToNumber CastExample

02-SEP-2025 02-SEP-25 12345 123

You might also like