0% found this document useful (0 votes)
4 views

RDBMS UNIT2

This document provides an overview of SQL built-in functions and joins, detailing various operators such as arithmetic, comparison, and logical operators. It explains single row functions including date, numeric, character, and conversion functions, along with their syntax and examples. Additionally, it covers the GROUP BY and HAVING clauses used to aggregate data 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)
4 views

RDBMS UNIT2

This document provides an overview of SQL built-in functions and joins, detailing various operators such as arithmetic, comparison, and logical operators. It explains single row functions including date, numeric, character, and conversion functions, along with their syntax and examples. Additionally, it covers the GROUP BY and HAVING clauses used to aggregate data 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
You are on page 1/ 30

Unit – II

SQL In built functions and Joins

1.1 Operators Arithmetic, Comparison, Logical


SQL Arithmetic Operators
Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.

Operator Description Example


+ It adds the value of both operands. a+b will give
30
- It is used to subtract the right-hand operand from the left-hand operand. a-b will give
10
* It is used to multiply the value of both operands. a*b will give
200
/ It is used to divide the left-hand operand by the right-hand operand. a/b will give 2
% It is used to divide the left-hand operand by the right-hand operand and a%b will give
returns reminder. 0

SQL Comparison Operators:


Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.

Operator Description Example


= It checks if two operands values are equal or not, if the values are equal (a=b) is not
then condition becomes true. true
!= It checks if two operands values are equal or not, if values are not equal, (a!=b) is true
then condition becomes true.
<> It checks if two operands values are equal or not, if values are not equal (a<>b) is true
then condition becomes true.
> It checks if the left operand value is greater than right operand value, if (a>b) is not
yes then condition becomes true. true
< It checks if the left operand value is less than right operand value, if yes (a<b) is true
then condition becomes true.
>= It checks if the left operand value is greater than or equal to the right (a>=b) is not
operand value, if yes then condition becomes true. true
<= It checks if the left operand value is less than or equal to the right (a<=b) is true
operand value, if yes then condition becomes true.
!< It checks if the left operand value is not less than the right operand value, (a!<b) is not
if yes then condition becomes true. true
!> It checks if the left operand value is not greater than the right operand (a!>b) is true
value, if yes then condition becomes true.

SQL Logical Operators


There is the list of logical operator used in SQL:

1
Operator Description
ALL It compares a value to all values in another value set.
AND It allows the existence of multiple conditions in an SQL statement.
ANY It compares the values in the list according to the condition.
BETWEEN It is used to search for values that are within a set of values.
IN It compares a value to that specified list value.
NOT It reverses the meaning of any logical operator.
OR It combines multiple conditions in SQL statements.
EXISTS It is used to search for the presence of a row in a specified table.
LIKE It compares a value to similar values using wildcard operator.

2.2 SQL functions- Single row function

i. Single row function.


Single row functions are the one who work on single row and return one output per row. For
example, length and case conversion functions are single row functions.

Single row functions can be character functions, numeric functions, date functions, and
conversion functions. Note that these functions are used to manipulate data items. These
functions require one or more input arguments and operate on each row, thereby returning one
output value for each row. Argument can be a column, literal or an expression. Single row
functions can be used in SELECT statement, WHERE and ORDER BY clause.

ii. Date functions


add-months
The ADD_MONTHS function returns a date with a specified number of months added.

Syntax:
ADD_MONTHS( date1, number_months )

Parameters
Parameter Description
date1 The starting date (before the n months have been added).
number_months The number of months to add to date1.

Example:
Select add_months (sysdate ,4) "Add_Months" from dual ;

Output:

months-between

2
The Oracle/PLSQL MONTHS_BETWEEN function returns the number of months
between date1 and date2.

Syntax:
MONTHS_BETWEEN( date1, date2 )

Parameters
Parameter Description
date1 The first date used to calculate the number of months between.
date2 The second date used to calculate the number of months
between.

Example:
Select months_between ('02-april-21','02-july-21')"Months_between" from dual;

Output:

Round
The Oracle/PLSQL ROUND function returns a date rounded to a specific unit of measure.

Syntax:
ROUND( date [, format] )

Parameters
Parameter Description
Date The date to round.
format Optional. The unit of measure to apply for rounding. If
the format parameter is omitted, the ROUND function will
round to the nearest day. It can be one of the following values:

Example:
Select ROUND(TO_DATE ('22-july -21'),'YEAR')"Round" from dual;

Output:

Truncate

3
The TRUNC (date) function returns date with the time portion of the day truncated to the unit
specified by the format model fmt.

Syntax:
TRUNC(date)

TRUNC(date, fmt)

Parameters
Parameter Description
Date Required. The date/datetime expression to be truncated. It must
be a value of the DATE data type.
format Optional. It specifies the unit to truncate to. If this parameter is
not specified, date will be truncated to the day (DD).

Example:
SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR') "New Year"
FROM DUAL;

Output:

New Year
---------
01-JAN-92

iii. Numeric Functions (abs, ceil, floor, power, mod, round, trunc, sqrt)

abs
The ABS function returns the absolute value of a number.
Syntax
ABS( number )

Parameter
Parameter Description
Number Required. A numeric value

Example
Select abs (-15) "Absolute" from dual;

Output:

4
ceil
The ceil() is a Math function of Oracle. This function returns the smallest value which is greater
than or equal to the given number.

Syntax:
ceil(num)

Parameter
Parameter Description
Num Required. A number

Example:
select ceil(11.5) from dual;

Output:
12

Floor
The floor() is a Math function of Oracle. This function is used to find the greatest integer which
is equal to or less than the given number.

Syntax:
floor(num)

Parameter
Parameter Description
Num Required. A number

Example:
select floor(11.3) from dual;

Output:
11

power
The POWER() function returns the value of a number raised to the power of another number.

Syntax:
POWER(a, b)

Parameter
Parameter Description
A Required. A number (the base)
B Required. A number (the exponent)

Example:
SELECT POWER(4, 3);
5
Output:
64

mod
MOD returns the remainder of n2 divided by n1. Returns n2 if n1 is 0.

Syntax:
MOD(n1, n2)

Parameters
Parameter Description
n1 A number which is divided.
n2 A number.

Example:
select mod(11,4) "modulus" from dual;

Output:

round
The ROUND function returns a number rounded to a certain number of decimal places.

Syntax:
ROUND( number [, decimal_places] )

Parameters
Parameter Description
Number The number to round.
decimal_places Optional. The number of decimal places rounded to. This
value must be an integer. If this parameter is omitted, the
ROUND function will round the number to 0 decimal places.

Example:
Select round (15.19,1)"Round" from dual;

Output:

6
trunc
The TRUNC (number) function returns n1 truncated to n2 decimal places. If n2 is omitted,
then n1 is truncated to 0 places. n2 can be negative to truncate (make zero) n2 digits left of the
decimal point.

Syntax:
TRUNC (number)

Parameters
Parameter Description
Number The number to round.
decimal_places Optional. The number of decimal places rounded to. This
value must be an integer. If this parameter is omitted, the
ROUND function will round the number to 0 decimal places.

Example:
SELECT TRUNC(15.79,1) "Truncate" FROM DUAL;

Output:

Truncate
----------
15.7

sqrt
This function is used to get the square root of a given non-negative number.

Syntax:
SQRT(X)

Parameters
Parameter Description
x A number which you want to get the square root

Example:
SELECT SQRT(25) FROM dual;

Output:

iv. Character Fucntions (initcap, lower, upper, ltrim, rtrim, replace,


substring, instr)

7
initcap

The Oracle/PLSQL INITCAP function sets the first character in each word to uppercase and the
rest to lowercase.

Syntax:
INITCAP( string1 )

Parameters
Parameter Description
string1 The string argument whose first character in each word will be
converted to uppercase and all remaining characters converted to
lowercase.

Example:
Select Initcap ('IVAN BAYROSS') "Capitalize Each Word" From Dual;

Output:

Lower
The Oracle/PLSQL LOWER function converts all letters in the specified string to lowercase. If
there are characters in the string that are not letters, they are unaffected by this function.

Syntax:
LOWER( string1 )

Parameters
Parameter Description
string1 The string to convert to lowercase.

Example:
Select lower ('IVAN BAYROSS') "Lower Case" from dual;
Output:

Upper
The Oracle/PLSQL UPPER function converts all letters in the specified string to uppercase. If
there are characters in the string that are not letters, they are unaffected by this function.

8
Syntax:
UPPER( string1 )

Parameters
Parameter Description
string1 The string to convert to uppercase.

Example:
Select upper ('ivan bayross') "Upper Case" from dual;

Output:

Ltrim
The Oracle/PLSQL LTRIM function removes all specified characters from the left-hand side of a
string.

Syntax:
LTRIM( string1 [, trim_string] )

Parameters
Parameter Description
string1 The string to trim the characters from the left-hand side.
trim_string Optional. The string that will be removed from the left-hand
side of string1. If this parameter is omitted, the LTRIM
function will remove all leading spaces from string1.
Example:
Select ltrim ('NISHA','N') "Ltrim" from dual;

Output:

Rtrim

The Oracle/PLSQL RTRIM function removes all specified characters from the right-hand side of
a string.

9
Syntax:
RTRIM( string1 [, trim_string ] )

Parameters
Parameter Description
string1 The string to trim the characters from the right-hand side.
trim_string Optional. The string that will be removed from the right-hand
side of string1. If this parameter is omitted, the RTRIM function
will remove all trailing spaces from string1.
Example:
Select rtrim ('SUNITA' , 'A') "Rtrim" from dual;

Output:

Replace
The Oracle/PLSQL REPLACE function replaces a sequence of characters in a string with
another set of characters.

Syntax:
REPLACE( string1, string_to_replace [, replacement_string] )

Parameters
Parameter Description
string1 The string to replace a sequence of characters with another
set of characters.
string_to_replace The string that will be searched for in string1
replacement_string Optional. All occurrences of string_to_replace will be
replaced with replacement_string in string1.If
the replacement_string parameter is omitted, the REPLACE
function simply removes all occurrences
of string_to_replace, and returns the resulting string.
Example:
Select replace('PGDCA College','PGDCA','BCA')AS Replace from dual;

Output:

Substring
The Oracle/PLSQL SUBSTR functions allows you to extract a substring from a string.
10
Syntax
SUBSTR( string, start_position [, length ] )

Parameters
Parameter Description
String The source string.
start_position The starting position for extraction. The first position in the
string is always 1.
length Optional. It is the number of characters to extract. If this
parameter is omitted, the SUBSTR function will return the
entire string.
Example
Select substr ('SECURE', 3,4) "Substring" from dual;

Output

instr

The INSTR() function returns the position of the first occurrence of a string in another string.
This function performs a case-insensitive search.

Syntax
INSTR(string, substring, position, occurrence)

Parameters
Parameter Description
string Required string.
substring Required string it will be search in string.
position position is an nonzero integer indicating the character
of string where Oracle Database begins the search.
If position is negative, then Oracle counts and searches
backward from the end of string.
occurrence occurrence is an integer indicating which occurrence
of string Oracle should search for. The value
of occurrence must be positive.

Example
SELECT INSTR('CORPORATE FLOOR','OR', 3, 2)"Instring" FROM DUAL;

Output

11
v. Conversion Functions (to-char, to-date, to-number)
to_char
The Oracle/PLSQL TO_CHAR function converts a number or date to a string.

Syntax:
TO_CHAR( value [, format_mask])

Parameters
Parameter Description
Value A number or date that will be converted to a string.
format_mask Optional. This is the format that will be used to
convert value to a string.

Example:
Select To_Char(sysdate, 'dd/mm/yyyy') To_Char From Dual;

Output:

To_date
The Oracle/PLSQL TO_DATE function converts a string to a date.

Syntax

TO_DATE( string1 [, format_mask])

Parameters

Parameter Description
string1 The string that will be converted to a date.
format_mask Optional. This is the format that will be used to
convert string1 to a date.

Example

Select TO_DATE('09/07/2021', 'dd/mm/yyyy') To_Date from dual;

12
Output

To_number
TO_NUMBER is one of the vital Conversion functions of Oracle. It is used to convert a string to
a number.

Syntax

TO_NUMBER ( char, format_mask)

Parameters

Parameter Description
char It is used to specify the string to be converted.
format_mask It is an optional parameter which is used to specify the
format to be used for conversion.
Example

select TO_NUMBER( '1342.67', '9999.99') from dual;

Output

2.2 Group by

In Oracle GROUP BY clause is used with SELECT statement to collect data from multiple
records and group the results by one or more columns.

Syntax:

SELECT expression1, expression2, ... expression_n,


aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;

Parameters:

13
expression1, expression2, ... expression_n: It specifies the expressions that are not
encapsulated within aggregate function. These expressions must be included in GROUP BY
clause.

aggregate_function: It specifies the aggregate functions i.e. SUM, COUNT, MIN, MAX or
AVG functions.

aggregate_expression: It specifies the column or expression on that the aggregate function is


based on.

tables: It specifies the table from where you want to retrieve records.

conditions: It specifies the conditions that must be fulfilled for the record to be selected.

Oracle GROUP BY Example: (with SUM function)

Let's take a table "salesdepartment"

Salesdepartment table:

Execute this query:

SELECT item, SUM(sale) AS "Total sales"


FROM salesdepartment
GROUP BY item;

Output

14
Having
In Oracle, HAVING Clause is used with GROUP BY Clause to restrict the groups of returned
rows where condition is TRUE.

Syntax:

SELECT expression1, expression2, ... expression_n,


aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n
HAVING having_condition;
Parameters:

expression1, expression2, ... expression_n: It specifies the expressions that are not
encapsulated within aggregate function. These expressions must be included in GROUP BY
clause.

aggregate_function: It specifies the aggregate functions i.e. SUM, COUNT, MIN, MAX or
AVG functions.

aggregate_expression: It specifies the column or expression on that the aggregate function is


based on.

tables: It specifies the table from where you want to retrieve records.

conditions: It specifies the conditions that must be fulfilled for the record to be selected.

having_conditions: It specifies the conditions that are applied only to the aggregated results to
restrict the groups of returned rows.

Oracle HAVING Example: (with GROUP BY SUM function)

Let's take a table "salesdepartment"

Salesdepartment table:
15
Execute this query:

SELECT item, SUM(sale) AS "Total sales"


FROM salesdepartment
GROUP BY item
HAVING SUM(sale) < 1000;

Output:

Order by clause
In Oracle, ORDER BY Clause is used to sort or re-arrange the records in the result set. The
ORDER BY clause is only used with SELECT statement.Syntax

SELECT expressions
FROM tables
WHERE conditions
ORDER BY expression [ ASC | DESC ];

Parameters:

expressions: It specifies columns that you want to retrieve.

tables: It specifies the table name from where you want to retrieve records.

16
conditions: It specifies the conditions that must be fulfilled for the records to be selected.

ASC: It is an optional parameter that is used to sort records in ascending order.

DESC: It is also an optional parameter that is used to sort records in descending order.

Oracle ORDER BY Example: (without ASC/DESC attribute)

Let's take a table "supplier"

Supplier table:

Execute this Query:

SELECT *
FROM supplier
ORDER BY last_name;

Output:

2.3 Joins:
Student

17
StudentCourse

Simple
The INNER JOIN keyword selects all rows from both the tables as long as the condition is
satisfied. This keyword will create the result-set by combining all rows from both the tables
where the condition satisfies i.e value of the common field will be the same.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.

18
table2: Second table
matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

Example Queries(INNER JOIN)


This query will show the names and age of students enrolled in different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student


INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

Output:

Equi-join

Table name — Student


In this table, you have I’d, name, class and city are the fields.
Select * from Student;
id name class city
3 Hina 3 Delhi
4 Megha 2 Delhi
6 Gouri 2 Delhi

Table name — Record


In this table, you have I’d, class and city are the fields.
Select * from Record;

19
Id class city
9 3 Delhi
10 2 Delhi
12 2 Delhi

EQUI JOIN creates a JOIN for equality or matching column(s) values of the relative tables.
EQUI JOIN also create JOIN by using JOIN with ON and then providing the names of the
columns with their relative tables to check equality using equal sign (=).
Syntax :
SELECT column_list
FROM table1, table2....
WHERE table1.column_name =
table2.column_name;
Example –
SELECT student.name, student.id, record.class, record.city
FROM student, record
WHERE student.city = record.city;

Output :
Name id class city
Hina 3 3 Delhi
Megha 4 3 Delhi
Gouri 6 3 Delhi
Hina 3 2 Delhi
Megha 4 2 Delhi
Gouri 6 2 Delhi
Hina 3 2 Delhi
Megha 4 2 Delhi
Gouri 6 2 Delhi

Inner join can have equality (=) and other operators (like <,>,<>) in the join condition.
Equi join only have an equality (=) operator in the join condition.
Non-equi
NON EQUI JOIN performs a JOIN using comparison operator other than equal(=) sign like >,
<, >=, <= with conditions.
Syntax:
SELECT column_list
FROM table_name1, table_name2

20
WHERE table_name1.column [> | < | >= | <= ] table_name2.column;
Example –
SELECT student.name, record.id, record.city
FROM student, record
WHERE Student.id < Record.id ;
Output :
Name id city
Hina 9 Delhi
Megha 9 Delhi
Gouri 9 Delhi
Hina 10 Delhi
Megha 10 Delhi
Gouri 10 Delhi
Hina 12 Delhi
Megha 12 Delhi
Gouri 12 Delhi

Self-Joins

As the name signifies, in SELF JOIN a table is joined to itself. That is, each row of the table is
joined with itself and all other rows depending on some conditions. In other words we can say
that it is a join between two copies of the same table.Syntax:
SELECT a.coulmn1 , b.column2
FROM table_name a, table_name b
WHERE some_condition;

table_name: Name of the table.


some_condition: Condition for selecting the rows.

21
Example Queries(SELF JOIN):
SELECT a.ROLL_NO , b.NAME
FROM Student a, Student b
WHERE a.ROLL_NO < b.ROLL_NO;
Output:

Outer-joins
Outer joins are of following three types.

LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows for the
table on the right side of the join. For the rows for which there is no matching row on the right
side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.

22
Example Queries(LEFT JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right
side of the join and matching rows for the table on the left side of the join. For the rows for
which there is no matching row on the left side, the result-set will contain null. RIGHT JOIN is
also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.
23
Example Queries(RIGHT JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN.
The result-set will contain all the rows from both tables. For the rows for which there is no
matching, the result-set will contain NULL values.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1

24
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Example Queries(FULL JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4

2.4 Subqueries - Multiple, Correlated

An SQL Subquery, is a SELECT query within another query. It is also known as Inner
query or Nested query and the query containing it is the outer query.

The outer query can contain the SELECT, INSERT, UPDATE, and DELETE statements. We
can use the subquery as a column expression, as a condition in SQL clauses, and with operators
like =, >, <, >=, <=, IN, BETWEEN, etc.

Subqueries with the SELECT Statement


Subqueries are most frequently used with the SELECT statement. The basic syntax is as
follows −

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name
OPERATOR (SELECT column_name [,column_name ] FROM table1 [, table2 ] [WHERE]);

ID NAME AGE ADDRESS SALARY

25
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

SELECT * FROM CUSTOMERS


WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500);

Subqueries with the INSERT Statement


We can also use the subqueries along with the INSERT statements. The data returned by the
subquery is inserted into another table.

The basic syntax is as follows −

INSERT INTO table_name [ (column1 [, column2 ]) ]


SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

Example
Now to copy the complete records of CUSTOMERS table into the CUSTOMERS_BKP table,
we can use the following query −

INSERT INTO CUSTOMERS_BKP


SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS);

Using the SELECT statement, we can verify whether the records from CUSTOMERS table
have been inserted into CUSTOMERS_BKP table or not –

SELECT * FROM CUSTOMERS_BKP;

Correlated Sub Query


A sub-query becomes correlated when the sub query references a column from a table in the
parent query. A correlated subquery is evaluated once for each row processed by parent
statement, which can be any of SELECT, DELETE or UPDATE.

A correlated subquery is one way of reading every row in a table and comparing values in each
row against related data. It is used whenever a subquery must return a different result for each
candidate row considered by the parent query.

Example

26
List accounts along with the current balance and the branch to which it belongs, having a
balance more than the average balance of the branch to which the account belongs.

SELECT ACCT_NO, CURBAL, BRANCH_NO FROM ACCT_MSTR A WHERE CURBAL


> (SELECT AVG(CURBAL) FROM ACCT_MSTR WHERE BRANCH_NO =
A.BRANCH_NO);

2.5 Implementation of Queries using SQL Set operators: Union, union all,
Intersect, Minus
The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus

Union
The SQL Union operation is used to combine the result of two or more SQL SELECT queries.

In the union operation, all the number of datatype and columns must be same in both the tables
on which UNION operation is being applied.

The union operation eliminates the duplicate rows from its resultset.

Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

Example:

The First table

ID NAME
1 Jack
2 Harry
3 Jackson

The Second table

ID NAME
3 Jackson

27
4 Stephan
5 David

Union SQL query will be:

SELECT * FROM First


UNION
SELECT * FROM Second;

The resultset table will look like:


ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David

union all

Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:

SELECT column_name FROM table1


UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

SELECT * FROM First


UNION ALL
SELECT * FROM Second;

The resultset table will look like:

ID NAME
1 Jack
2 Harry
3 Jackson

28
3 Jackson
4 Stephan
5 David

intersect
It is used to combine two SELECT statements. The Intersect operation returns the common rows
from both the SELECT statements.
In the Intersect operation, the number of datatype and columns must be the same.
It has no duplicates and it arranges the data in ascending order by default.

Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

SELECT * FROM First


INTERSECT
SELECT * FROM Second;

The resultset table will look like:

ID NAME
3 Jackson

minus

It combines the result of two SELECT statements. Minus operator is used to display the rows
which are present in the first query but absent in the second query.

It has no duplicates and data arranged in ascending order by default.

Syntax:
SELECT column_name FROM table1
MINUS

29
SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

SELECT * FROM First


MINUS
SELECT * FROM Second;

The resultset table will look like:

ID NAME
1 Jack
2 Harry

30

You might also like