RDBMS UNIT2
RDBMS UNIT2
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.
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.
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:
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
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
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
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
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:
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.
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.
Salesdepartment table:
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:
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.
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.
Salesdepartment table:
15
Execute this query:
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:
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.
DESC: It is also an optional parameter that is used to sort records in descending order.
Supplier table:
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;
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.
Output:
Equi-join
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;
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;
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;
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;
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
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.
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
Example
Now to copy the complete records of CUSTOMERS table into the CUSTOMERS_BKP table,
we can use the following query −
Using the SELECT statement, we can verify whether the records from CUSTOMERS table
have been inserted into CUSTOMERS_BKP table or not –
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.
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.
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:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
27
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:
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:
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.
Syntax:
SELECT column_name FROM table1
MINUS
29
SELECT column_name FROM table2;
Example
ID NAME
1 Jack
2 Harry
30