0% found this document useful (0 votes)
41 views12 pages

KKW Unit 3 Interactive SQL and Advanced SQL (Part A)

Uploaded by

thakkarparth793
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
41 views12 pages

KKW Unit 3 Interactive SQL and Advanced SQL (Part A)

Uploaded by

thakkarparth793
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Data Base Management System 2020

Unit 03- Interactive SQL and Advanced SQL


Course Outcomes (COs) / Unit Outcomes (UOs):
Course Outcome (CO 304.1):Design Normalized database on given data
(CO 304.2): Create & manage database using SQL command
Unit Outcomes:
3a)Write the given queries using relevant functions
3b)Write query to combine the given multiple table using Join
3c)Design SQL queries to implement VIEWS on the given table
3d)Apply & drop INDEXES & SYNONYM on the given table
4a)Write simple PL/SQL code using control structure & handle various exceptions in the given situation
4b)Create cursor for retrieving multiple records in the given situation
4c)Create & execute stored procedures & functions in the given situation
4d)Create & apply database trigger using PL/SQL in the given situation

3.1 Inbuilt Functions


There are two types of functions in SQL

A] Scalar function/single row function.

B] Multiple Row Function/group function

A] Scalar Function/Single Row Function.


1. String Functions:These functions take a string as a parameter and return a number or a string.All string
functions are performed on dual table. The dual is a dummy table. The dummy tables are in built in the oracle data
base. String functions are used to manipulate string data and derive some information and analysis from the tables

 UPPER(string):Returns string in all upper case


Syntax : select upper(„statements‟) from <table Name>;
Ex : select upper(„hello‟)from dual;
O/P : HELLO
 LOWER(string):Returns string in all lower case
Syntax : select lower („statements‟)from <table Name>;
Ex : select lower („HELLO‟) from dual;
O/P : hello
 INITCAP(string):Returns string in first letter of each word capitalized
Syntax: select initcap(„statements‟)from <table Name>;
Ex : select initcap(„hello‟)from dual;
O/P : Hello.
 LPAD(string, length, pad):Returns string padded on left to length characters using the pad string as
padding. Pad may be omitted: defaults to single space.
Syntax : Select lpad(char1,length,char2)from<table Name>;
Ex :Select lpad(„hello‟,10,‟*‟)from dual;
O/P :*****hello
 RPAD(string, length, pad)
Returns string padded on right to length characters using the pad string as padding. Pad may be omitted:
defaults to single space.

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 1


Data Base Management System 2020
Syntax : Select rpad(char1,length,char2)from <table Name>;
Ex :Select rpad(„hello‟,10,‟*‟)from dual;
O/P :hello*****
 LTRIM(string, trimlist):Returns string with the leftmost characters that match the characters in trimlist
removed. Trim list may be omitted: defaults to single space.
Syntax :Selectl trim(string, trimlist)from <table Name>;
Ex :select ltrim(„hello‟, „he‟)from dual;
O/P :llo
 RTRIM(string, trimlist): Returns string with rightmost characters that match the characters in trim list
removed
Syntax :Select rtrim(string, trimlist) from <table Name>;
Ex :Select rtrim(„hello‟, „llo‟)from dual;
O/P :he

 REPLACE(string,target,replacement):Returns string with all occurrences of target replaced with replacement.


If replacement is omitted, occurrences are deleted.
Syntax :Select replace(string, target, replacement) from <table Name>;
Ex :Select Replace(„Tick and Tock‟, „T‟, „Cl‟)from dual;
O/P :Click and Clock

 TRANSLATE(string,fromlist,tolist): Returns string with each character in the fromlist replaced with the
corresponding character in the tolist.
Syntax :Selecttranslate(string, from list, to list) from <table Name>;
Ex :Select translate(„Tick ‟, „Ti‟, „Cli‟)from dual;
O/P :Click

 SUBSTR(string, pos, len): Returns the substring of string which begins at pos and is len characters long.
If pos is negative, pos is counted from the end of string. The first position in string is 1 not 0.
Syntax :Select substr(string, pos, len) from <table Name>;
Ex :select substr(„computer‟, 4, 3)from dual;
O/P :put

 length(string): This function is used to find the length of a word


Syntax : Select length(string) from <table Name>;
Ex :select length(„computer‟)from dual;
O/P :8
 Concat(string1||string2): This function is used to add two words or strings.
Syntax : Select concat(string1||string2) from <table Name>;
Ex :select concat(ename||eno)from emp;
O/P :Raj01
Ravi02
 Instr(string, ‘character to find occurrence’):This function is used for finding the occurrence of an
alphabet. It generally displays the first occurrence of the string.

Syntax : Select Instr(string, „character to find occurrence‟) from <table Name>;


Ex :select Instr( „god is great‟, „e‟ ) from dual;
O/P :10

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 2


Data Base Management System 2020

2. Numeric Functions: Numeric Functions accepts the numeric values as the input and it returns the numeric
value as the output

 Abs(n):Returns the absolute value of the n


Syntax : select abs(-n) from <Table Name>;
Ex :select abs(-10)from dual;
O/P :10

 Power(m,n): It returns m raised to the nth power


Syntax : select power(m, n) from <Table Name>;
Ex :select power(2, 3)from dual;
O/P :8

 Mod(m,n): It returns the reminder of m divided by n


Syntax : select mod(m, n) from <Table Name>;
Ex :select mod(4,2 )from dual;
O/P :0
 Sqrt(n): It returns square root of n. n cannot be negative .
Syntax : select sqrt( n) from <Table Name>;
Ex :select sqrt(144)from dual;
O/P :12

 Exp(n) : It returns the e raised to the power of the n


Syntax : select exp( n) from <Table Name>;
Ex :select exp(3)from dual;
O/P :20.08

 Round(n, m) : It returns n rounded to m places right of the decimal point


Syntax : select round( n, m ) from <Table Name>;
Ex :select round(100.256, 2)from dual;
O/P :100.25
 Trunc(n,m): It returns n truncated to m decimal places
Syntax : select trunc(n, m) from <Table Name>;
Ex :select trunc(125.815, 1)from dual;
O/P :125.8
 Ceil(n): It returns the smallest integer that is greater or equal to n
Syntax : select ceil(n) from <Table Name>;
Ex :select ceil(14.3)from dual;
O/P :15
 Floor(n):It returns the largest integer that is equal or less than n
Syntax : select floor(n) from <Table Name>;
Ex :select floor(14.3)from dual;
O/P :14
 Sin(n):It returns sine of the n
Syntax : select sin(n) from <Table Name>;
Ex :select sin(90)from dual;
O/P :1.8939

 Cos(n):It returns cosine of the n


Syntax : select cos(n) from <Table Name>;
Ex :select cos(0)from dual;
O/P :1

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 3


Data Base Management System 2020
 Tan(n): It returns the tangent of the n
Syntax : select tan(n) from <Table Name>;
Ex :select tan(45)from dual;
O/P :1.619
 Greatest(expr,[expr],…): It returns the greatest of the list of expression
Syntax : select Greatest(expr,[expr],…) from <Table Name>;
Ex :select greatest(45, 85,90)from dual;
O/P :90
 Least(expr,[expr],…): It returns the least of the list of expression
Syntax : select least(expr,[expr],…) from <Table Name>;
Ex :select least(45, 85,90)from dual;
O/P :45

3. Date and Time Functions: These functions can be applied to columns with data type data and time.
Sysdate variable stores current date of system

 Months_between(d1,d2): This function finds the number of months between d1 and d2. If d1 is later than
d2 the result is positive. If d1 is earlier than d2 the result is negative
Syntax: Select Months_between(d1, d2) from <table name>;
Ex :Select months_between(‟05-may-2019‟, ‟05-jan-2019‟)from dual;
O/P :4
 Add_months(d,n): It returns the date after adding number of months specified with the function
Syntax: Select add_months(d, n) from <table name>;
Ex :Select add_months(‟05-may-2019‟, 2)from dual;
O/P :05-jul-2019
 Next_day(d, char):It returns the date of the first weekday named „char‟ that is later than the date „d‟
Syntax: Select next_day(d, „char‟) from <table name>;
Ex :Select next_day(‟31-aug-2019‟, „Tuesday‟)from dual;
O/P :03-sep-2019

 Last_day(d): It returns the last day of the month that contain date d. Used to determine how many days left
in the month
Syntax: Select last_day(d) from <table name>;
Ex :Select last_day(‟10-aug-2019‟)from dual;
O/P :31-AUG-2019

B] Multiple Row Function/Group Function


1. Aggregate Functions: Aggregate functions returns result based on group of rows. Unlike single –row
functions, group functions operate on sets of rows to give one result per group. These sets may be the whole table or
the table split into groups. Aggregate functions are as follows:

Consider the following “product” table

ProductID ProductName SupplierID CategoryID Price


1 CRO 1 1 10
2 PROBE 1 1 10
3 TESTER 1 2 10
4 IC 2 2 22

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 4


Data Base Management System 2020
5 LOGIC PROBE 2 2 20

 Avg(n): It return average value of n ,ignoring null values


Syntax: SELECT avg(column_name)FROM table_name WHERE condition;
Ex: Select avg(Price) from product;
O/P: 14.4
Here , Where condition is optional.
 Max(n) : It returns the maximum value from n , ignoring null values.
Syntax: SELECT max(column_name)FROM table_name WHERE condition;
Ex: Select MAX(Price) from product;
O/P: 22
Here , Where condition is optional.

 Min(n): It returns the minimum value from n ,ignoring null values.


Syntax: SELECT min(column_name)FROM table_name WHERE condition;
Ex: Select min(Price) from product;
O/P: 10
Here , Where condition is optional.

 Sum(n): It returns the sum of n supplied values


Syntax: SELECT sum(column_name)FROM table_name WHERE condition;
Ex: Select sum(Price) from product;
O/P:72
Here , Where condition is optional.

 Count(n) or Count(*): count(n) function count the number of rows of n. count(*) count all rows including
duplicates and rows with nulls.
Syntax: SELECT count(column_name)FROM table_name WHERE condition;
Ex: Select count(Price) from product;
O/P:05
Here , Where condition is optional.

3.2 Clauses in SQL:

Consider the following Table for Performing Clauses

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 5


Data Base Management System 2020

PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120

1. GROUP BY Clause
o SQL GROUP BY statement is used to arrange identical data into groups. The GROUP BY statement is used
with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.
o The GROUP BY statement is used with aggregation function.

Syntax: SELECT column Name, Group Function () FROM <table name >
where <conditions> GROUP BY column name;

Example: SELECT COMPANY, COUNT (QTY) FROM PRODUCT_MAST GROUP BY COMPANY;

Output:
Com1 5
Com2 3
Com3 2

2. HAVING Clause
o HAVING clause is used to specify a search condition for a group or an aggregate.
o Having is used in a GROUP BY clause. If you are not using GROUP BY clause then you can use HAVING
function like a WHERE clause.

Syntax: SELECT column Name, Group Function () FROM <table name >
where <conditions> GROUP BY column name
HAVING conditions ORDER BY column1, column2;

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 6


Data Base Management System 2020

Example:SELECT COMPANY, COUNT (QTY) FROM PRODUCT_MAST GROUP BY COMPANY


HAVING COUNT (QTY) >2 ;

Output:
Com1 5
Com2 3

3. ORDER BY Clause
o The ORDER BY clause sorts the result-set in ascending or descending order.
o It sorts the records in ascending order by default. DESC keyword is used to sort the records in descending
order.

Syntax: SELECT column1, column2 FROM table_name WHERE condition


ORDER BY column1, column2... ASC|DESC;
Where
ASC: It is used to sort the result set in ascending order by expression.
DESC: It sorts the result set in descending order by expression
Consider the following Table of “CUSTOMER”
CUSTOMER NAME ADDRESS
_ID
12 Kathrin US
23 David Bangkok
34 Alina Dubai
45 John UK
56 Harry US
Ex: select * from customer order by name;
Output:
CUSTOMER NAME ADDRESS
_ID
34 Alina Dubai
23 David Bangkok
56 Harry US
45 John UK
12 Kathrin US

Ex: select * from customer order by name desc;


Output:
CUSTOMER NAME ADDRESS
_ID
12 Kathrin US
45 John UK
56 Harry US
23 David Bangkok
34 Alina Dubai

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 7


Data Base Management System 2020

3.3 Joins in SQL:


As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or more
tables". In SQL, JOIN clause is used to combine the records from two or more tables in a database

Types of SQL JOIN:


1. Inner Join
2. Left Outer Join
3. Right Outer Join
4. Full Outer Join

Consider the following table of “Employee” and “Project”

Employee

Emp_Id Emp_Name City Salary Age


1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000

Project
Project_No Emp_Id Department
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as the condition is satisfied. It
returns the combination of all rows from both the tables where the condition satisfies.

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

Ex: Select Employee.Emp_Name, Project.Department From Employee


Inner Join Project On Project.Emp_Id = Employee.Emp_Id;

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 8


Data Base Management System 2020
Output
Emp_Name Department
Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT OUTER JOIN


The SQL left join returns all the values from left table and the matching values from the right table. If there is no
matching join value, it will return NULL.

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

Ex: Select Employee.Emp_Name, Project.Department From Employee Left Outer Join Project
On Project.Emp_Id = Employee.Emp_Id;

Output:
Emp_Name Department
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL

3. RIGHT OUTER JOIN:


In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched values
from the left table. If there is no matching in both tables, it will return NULL.

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

Ex: Select Employee.Emp_Name, Project.Department From Employee Right Outer Join Project
On Project.Emp_Id = Employee.Emp_Id;

Output:
Emp_Name Department
Angelina Testing
Robert Development
Christian Designing

Kristen Development

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 9


Data Base Management System 2020

3. FULL OUTER JOIN:


In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have all the records
from both tables. It puts NULL on the place of matches not found.

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

Ex: Select Employee.Emp_Name, Project.Department From Employee Full Outer Join Project
On Project.Emp_Id = Employee.Emp_Id;

Output:

Emp_Name Department
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL

3.4 SQL Sub Query


A Sub query is a query within another SQL query and embedded within the WHERE clause.
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING
clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators
like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner
query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to
perform the same function as ORDER BY command.

Example
Consider the Employee table have the following records:

Id Name Age Address Salary


1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 10


Data Base Management System 2020

6 Harry 42 China 4500.00

1. Sub queries with the Select Statement:


Syntax:
SELECT column_name FROM table_name WHERE column_name expression operator( SELECT column_name
from table_name WHERE ... );

Ex: Select * From Employee Where Id In (Select Id from Employee Where Salary > 4500);
This would produce the following result:

Output:
Id Name Age Address Salary
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
7 Jackson 25 Mizoram 10000.00

2. Sub queries with the INSERT Statement

o SQL subquery can also be used with the Insert statement. In the insert statement, data returned from the
subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date functions.

Syntax: INSERT INTO table_name (column1, column2, column3....) SELECT * FROM table_name
WHERE VALUE OPERATOR;

Example:

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE. Now use the following syntax to copy the
complete EMPLOYEE table into the EMPLOYEE_BKP table.

Ex: INSERT INTO EMPLOYEE_BKP SELECT * FROM EMPLOYEE WHERE ID IN (SELECT IDFROM EMPLOYEE);

3. Sub queries with the Update Statement

The subquery of SQL can be used in conjunction with the Update statement. When a subquery is used with the
Update statement, then either single or multiple columns in a table can be updated.

Syntax: UPDATE table SET column_name = new_value WHERE VALUE OPERATOR (SELECT COLUMN_NAME
FROM TABLE_NAME WHERE condition);

Example: Let's assume we have an Customers_Bkp table available which is backup of Employee table. The given
example updates the SALARY by .25 times in the EMPLOYEE table for all employee whose AGE is greater than or
equal to 29.

SQL>Update Employee Set Salary = Salary * 0.25 Where Age In (Select Age From
Customers_Bkp Where Age >= 29);

This would impact three rows, and finally, the EMPLOYEE table would have the following records.

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 11


Data Base Management System 2020
Id Name Age Address Salary
1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
4 Alina 29 UK 1625.00
5 Kathrin 34 Bangalore 2125.00
6 Harry 42 China 1125.00
7 Jackson 25 Mizoram 10000.00

4. Sub queries with the Delete Statement

The sub query of SQL can be used in conjunction with the Delete statement just like any other statements mentioned
above.

Syntax: Delete From Table_Name Where Value Operator


(Select Column_Name From Table_Name Where Condition);
Example:
Let's assume we have an Employee_Bkp table available which is backup of Employee table. The given example
deletes the records from the Employee table for all EMPLOYEE whose AGE is greater than or equal to 29.
SQL> Delete From Employee Where Age In (Select Age From Employee_Bkp Where Age >= 29);

This would impact three rows, and finally, the EMPLOYEE table would have the following records.

Id Name Age Address Salary


1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
7 Jackson 25 Mizoram 10000.00

Prepared By: Ms. Y. U. Kadam, Lecturer, KKWP, Nashik Page 12

You might also like