You are on page 1of 67

Department of CSE

COURSE NAME: DBMS


COURSE CODE:22CS2110 RA
Topic:
Functions and writing SQL Statements
using nested sub queries
Session - 9

CREATED BY K. VICTOR BABU


AIM OF THE SESSION
The aim of the session would be to equip participants with the skills and knowledge necessary to write complex SQL statements
using functions and nested subqueries, allowing them to manipulate data more effectively in their work or projects.

INSTRUCTIONAL
OBJECTIVES
This session is designed to equip learners with the knowledge and skills necessary to write efficient and effective SQL

statements using functions and nested subqueries

LEARNING OUTCOMES

At the end of this session, you should be able to write SQL functions and distinguish between built-in and

user-defined functions. Create user-defined functions in SQL to perform specific calculations on data.

CREATED BY K. VICTOR BABU


SQL FUNCTIONS

• Definition of Function
• T ypes of SQL
Function
• Numeric Function
• String Function
• Conversion Function
• Date Function

CREATED BY K. VICTOR BABU


SQL FUNCTIONS

 Sub program of SQL Lang.

 Used to do Operation on the SQL Expression.

 SQL Functions works on Columns of Table.

 Returns a Value as a Result of the Operation.

 After the Execution of the Function One or


More Values can be returned by the Function.

CREATED BY K. VICTOR BABU


Types of SQL FUNCTIONS

 According to the Processing on the Value of Column Sql


Function can be Classified.
 Two Types of SQL Function
 Group Functions
 “Functions act on Set of Values are known as Group
Function”
 SUM,AVG, MIN, MAX (Aggregate Function)
 Scalar Functions
 “Functions act on only one value at a time known as
Scalar Fn”
 Length, ASCII

CREATED BY K. VICTOR BABU


Types of SQL FUNCTIONS (Contd..)

 According to the SQL Data T ype


 Numeric Functions:
 To processing Number Data type

 String Functions:
 To Processing on String Data type

 Conversion Functions:
 To Convert Data type from one data type to
another

 Date Functions:
 To processing on Date Data T ype

CREATED BY K. VICTOR BABU


AVG Function

 Returns Average of all Row Values for particular Column.


 Null Values are ignored in Calculation.

 Syntax:
 AVG ([DISTINCT | ALL ] column_name);
 Example:
 SELECT AVG(BALANCE) AS AVERAGE _BALANCE
FROM ACCOUNT_MASTER;

CREATED BY K. VICTOR BABU


MIN Function

 Return a minimum Value of Expression

 Syntax:
 MIN ([DISTINCT | ALL] column_name) ;

 Example:
 SELECTMIN(BALANCE) AS Minimum_Balance
FROM ACCOUNT;

CREATED BY K. VICTOR BABU


MAX Function

 Returns Maximum value present in particular column of Data


table.

 Syntax:
 MAX ([ DISTINCT | ALL ] column_name);

 Example:
 SELECT MAX(BALANCE) AS maximum balance
FROM ACCOUNT_MASTER ;

CREATED BY K. VICTOR BABU


COUNT Function

 Returns Number of Rows Present in Particular Column

 Count(*) returns the number of rows in the table including


duplicates and those with nulls.

 Syntax:
 COUNT ( [ DISTINCT | ALL ] column_name) ;

 Example:
 SELECT COUNT(ACCOUNT_NO) AS no. of records
FROM ACCOUNT_MASTER;

CREATED BY K. VICTOR BABU


SUM Function

 Returns Sum of Values present in particular Column

 Syntax:
 SUM( [ DISTINCT | ALL ] column_name) ;

 Example:
 SELECT SUM(BALANCE) AS TOTAL_BALANCE
FROM ACCOUNT_MASTER;

CREATED BY K. VICTOR BABU


Numeric Functions

ABS Function POWER Function

ROUND Function SQRT Function

EXP Function MOD Function

GREATEST Function FLOOR Function

TRUNC Function

CREATED BY K. VICTOR BABU


ABS Function

 Absolute Value Expression returned by this function


 Syntax:
 ABS(n);

 Example :
 Select ABS(-10);
 Output:
 10 Displayed on Postgresql O/P Screen

CREATED BY K. VICTOR BABU


POWER Function

 Returns Power of the Expression.

 Syntax:
 POWER(m,n);

 Example:
 Select POWER(6,2);
 Output:
 36 Displayed on The Postgresql Screen  62

CREATED BY K. VICTOR BABU


ROUND Function

 Used to Get Rounded Value of Expression


 Syntax:
 ROUND (n,m);
 n = Numeric Value with Decimal Point
 m = Rounded Position
 Example:
 Select ROUND(10.29,1);
 Output:
 10.3

CREATED BY K. VICTOR BABU


SQRT Function

 Used to Find out the Square Root of Expression.

 Syntax:
 SQRT (n);
 Returns Square root of n
 n must be Positive if n < 0 then Null will be returned

 Example:
 Select SQRT(25);
 Output:
 5

CREATED BY K. VICTOR BABU


EXPONENT Function

 Returns e raised to nth Power.

 Syntax:
 EXP (n);
 en
 Example:
 Select EXP(5);
 Output:
 148.413159 ( e = 2.71828183 )

CREATED BY K. VICTOR BABU


GREATEST Function

 Used to Find out the Greatest Valued from the


Expression.

 Syntax:
 GREATEST (exp1,exp2,…,expn);
 Example:
 Select GREATEST(21,10,30);
 Output:
 30

CREATED BY K. VICTOR BABU


LEAST Function

 Used to Find out Lowest Value from the Expression

 Syntax:
 LEAST (exp1,exp2,…,expn);

 Example:
 Select LEAST(35,75,25);
 Output:
 25

CREATED BY K. VICTOR BABU


MOD Function

 Used to Find out the Reminder of Division Function

 Syntax:
 MOD (m,n);

 m/n Reminder is a result

 Example:
 Select MOD(18,7);

CREATED BY K. VICTOR BABU


TRUNCATION Function

 Returns Truncated Values after the decimal position

 Syntax:
 TRUNC (number, decimal_Places);

 Example:
 Select TRUNC(17.235,1);
 Output:
 17.2

CREATED BY K. VICTOR BABU


FLOOR Function

 Returns Largest Integer Value of Expression.

 Syntax:
 FLOOR (n)

 Example:
 Select FLOOR(24.18);
 Output:
 24

CREATED BY K. VICTOR BABU


CEIL Function

 Returns Smallest Integer value which is Greater or Equal to the


number.

 Syntax:
 CEIL (n);
 Example:
 Select CEIL(24.83);
 Output:
 25

CREATED BY K. VICTOR BABU


STRING Functions

LOWER Function UPPER Function

INITCAP Function SUBSTRING Function

ASCII Function POSITION Function

TRANSLATE Function LENGTH Function

LTRIM Function RTRIM Function

RPAD Function LPAD Function

CONCAT Function TRIM Function

CREATED BY K. VICTOR BABU


LOWER Function

 Return all character with lowercase letters.


 SYNTAX:
 LOWER(Char);
 EXAMPLE:
 Select LOWER(‘XYZ’) AS Lower;
 OUTPUT:

Lower

xyz

CREATED BY K. VICTOR BABU


UPPER Function

 Return character with Uppercase Letter.


 Syntax:
 UPPER (Char);
 Example:
 Select UPPER(‘xyz’) AS Upper_Case;

 Output:

Upper_Case

XYZ

CREATED BY K. VICTOR BABU


INITCAP Function

 Return First Character of String with Upper Case Letter.


 Syntax:
 INITCAP (Char) ;
 Example:
 Select INITCAP(‘abc’) AS First_Case;
 Output:

First_Case

Abc

CREATED BY K. VICTOR BABU


SUBSTRING Function

 Returns Substring of Main String according to the Specified


position of Characters upto specified length of Characters.
 Syntax:
 SUBSTRING (string, start_position, length) ;
 Example:
 Select SUBSTRING (‘SECURE’, 3,4) AS “Sub_Str”;
 Output:

Sub_Str

CURE

CREATED BY K. VICTOR BABU


ASCII Function

 Returns Ascii value of Specified Character.


 Syntax:
 ASCII (Char) ;
 Example:
 Select ASCII(‘a’) AS “Ascii_Value”;
 Output:

Ascii_Value

97

CREATED BY K. VICTOR BABU


POSITION Function

 Return location of substring in the main string.


 Syntax:
POSITION (search_string in main_string)
 Example:
 Select POSITION (‘our’ in ‘w3resource’) AS “Position”;
 Output:

Position
6

CREATED BY K. VICTOR BABU


LENGTH Function

Returns the length of words in the


string
Syntax:
LENGTH (word) ;
Example:
SelectLENGTH(‘xyz’) AS “Length”;
Output:

Length
3
CREATED BY K. VICTOR BABU
LTRIM Function

Remove Character from left of String.


Syntax:
LTRIM (char, set);
Example:
Selectltrim(‘xyz’,’x’) AS “Ltrim”;
Output:

Ltrim
yz

CREATED BY K. VICTOR BABU


RTRIM Function

Remove character from Right of


String.
Syntax:
RTRIM (char, set);
Example:
Selectrtrim(‘xyz’,’z’) AS “Rtrim”;
Output:

Rtrim
xy

CREATED BY K. VICTOR BABU


LPAD Function

Return String of with specified Character at


left side of string.
Syntax:
LPAD (char1, n,[char2]);
Example:
Selectlpad(‘xyz’ , 5 , ‘*’) AS “Lpad”;
Output:

Lpad
**xyz

CREATED BY K. VICTOR BABU


RPAD Function

Add specified character to the right side of


main string
Syntax:
RPAD (char1, n, [char2]);
Example:
Selectrpad(‘xyz’,6, ‘p’) AS “Rpad”;
Output:

Rpad
xyzppp

CREATED BY K. VICTOR BABU


CONCAT Function

Returns the string that results from


concatenating the arguments.
Syntax:
CONCAT ( argument1, argument2 );
Example:
SelectCONCAT(‘abc’, ‘XYZ’) AS
“CONCAT”;
Output:

CONCAT
abcXYZ
CREATED BY K. VICTOR BABU
NESTED SUB QUERIES

• A Subquery or Inner query or Nested query is a query within


another SQ L query and embedded within the WHERE clause.

• Subqueries (also known as inner queries or nested queries) are


a tool for performing operations in multiple steps.

CREATED BY K. VICTOR BABU


NESTED SUB QUERIES

Example

SELEC T * FRO M t1 WH ERE column1 = (SELEC T column1 FRO M t2);

– O uter query Subquery

CREATED BY K. VICTOR BABU


ADVANTAGES


The main advantages of subqueries are:
– They allow queries that are structured so that it is
possible to isolate each part of a statement.
– They provide alternative ways to perform operations
that would otherwise require complex joins and unions.
– More readable than complex joins or unions.

Indeed, it was the innovation of subqueries that gave
people the original idea of calling the early SQ L
“Structured Q uery Language.”

CREATED BY K. VICTOR BABU


RETURN

● Scalar (a single value)


● Single row
● Single column
● Table

CREATED BY K. VICTOR BABU


MORE INFORMATION

1. Subqueries must be enclosed with parenthesis


2 . A subquery can contain many of the clauses that an
ordinary SELEC T can: D ISTINC T, G RO U P BY, O RD ER BY,
LIMIT, joins, index hints, U NIO N constructs, comments,
functions, and so on.
3 . A subquery's outer statement can be any one of: SELEC
T,INSERT, U PD ATE, D ELETE, SET, or D O .
4. In SQ L, you cannot modify a table and select from the
same table in a subquery

CREATED BY K. VICTOR BABU


TABLE USED FOR EXAMPLE

H istorical series of fertility rate

CREATED BY K. VICTOR BABU


CREATE & UPDATE

C REATE TABLE countries AS (SELEC T D ISTINC T country


from fertility)
• H ow can I get the updated fertility rate for each country?
• SELEC T country, year, fertility FRO M fertility WH ERE year = 2015
G RO U P BY country
• H o w can I updat e my country table using subquery?
• U PD ATE countries c SET
c.fertility = ( SELEC T fertility
FRO M fertility f

WH ERE
YEAR =2015
AND f.country = c.country

G RO U P BY country),
CREATED BY K. VICTOR BABU
ANOTHER EXAMPLE

Two sources of data

CREATED BY K. VICTOR BABU


UPDATE

• H ow to get one column (continent) from the second


source?
• U PD ATE countries c SET c.continent =
(SELEC T continent_ code FRO M countries2 c2
WH ERE c2.name = c.country )

CREATED BY K. VICTOR BABU


DELETE

• H ow to delete countries which has no data


• D ELETE FRO M countries WH ERE country
IN (SELEC T country FRO M fertility G RO U P BY
country H AVING SUM (fertility) IS NU LL) *
• * It might give error on S Q L workbench because of
safe update mode. (Error C ode: 1175) – You must disable
safe mode.

CREATED BY K. VICTOR BABU


THE SUBQUERY AS SCALAR OPERAND

A scalar subquery is a simple operand, and you can use it almost


an ywhere a sin gle column valu e or literal is legal, and you can expect
it to have those characteristics that all operands have: a data type, a
length, an indication that it can be NU LL, and so on. For example:
C REATE TABLE t1 (s1 INT, s2 C H AR(5) NO T NULL);
INS ERT INTO t1
VALU ES (100, 'abcde');
SELEC T (SELEC T s2 FRO M t1);
The subquery in this SELEC T returns a single value ('abcde') that has
a data type of C H AR, a length of 5, a character set and collation
equal to the defaults in ef f ect at C REATE TABLE time, and an
indication that the value in the column can be NU LL.

CREATED BY K. VICTOR BABU


EXAMPLE

• SELEC T (SELEC T AVG (fertility) FRO M countries


WH ERE continent = 'EU '),
(SELEC T AVG (fertility) FRO M countries WH ERE
continent = 'SA')

CREATED BY K. VICTOR BABU


COMPARISIONS USING SUB QUERIES

• = > < >= <= <> != <=>


• What are the countries in South America which have
fertility smaller than Max european fertility?
• SELEC T * FRO M countries
WH ERE fertility < ( SELEC T
MAX (fertility)
FRO M countries
WH ERE continent='EU')
AND continent = 'SA';

CREATED BY K. VICTOR BABU


SUB QUERIES WITH ANY, IN, or SOME

• Which countries in Africa have fertility rate < than any


european country?
• SELEC T * FRO M countries
WH ERE fertility < ANY
(SELEC T fertility FRO M countries WH ERE
continent='EU ')
AND continent = 'AF';
• When used with a subquery, IN is an alias for = A
NY

CREATED BY K. VICTOR BABU


SUB QUERIES WITH ALL

• SELEC T s1 FRO M t1 WH ERE s1 > ALL


(SELEC T s1 FRO M t2);
• Which countries in Africa have the fertility rate bigger
than all countries of Asia and South America
• SELEC T s1 FRO M t1 WH ERE s1 <> ALL
(SELEC T s1 FRO M t2);
• NO T IN is an alias for <> ALL

CREATED BY K. VICTOR BABU


ROW SUB QUERIES

A row subquery is a subquery variant that returns a single


row and can thus return more than one column value
SELEC T * FRO M t1 WH ERE (col1, col2) = (SELEC T col3,
col4 FRO M t2 WH ERE id = 10);
Which countries are on the average of 2015?
SELEC T country, year, fertility FRO M fertility
WH ERE (TRUNC ATE(fertility,1), year) =
(SELEC T TRU NC ATE(AVG (fertility),1), year FRO
M countries);

CREATED BY K. VICTOR BABU


ROW SUB QUERIES (Contd..)

• SELEC T * FRO M t1 WH ERE RO W(col1, col2) = (SELEC T


col3, col4 FRO M t2 WH ERE id = 10);
• The row constructor and the row returned by the subquery
must contain the same number of values.
• The following query answers the request, “f i n d all rows in
table t1 that also exist in table t2”:
• SELEC T column1, column2, column3
FRO M t1
WH ERE (column1, column2, column3) IN
(SELEC T column1, column2, column3 FRO M t2);

CREATED BY K. VICTOR BABU


ROW SUB QUERIES (Contd..)

• Which countries have the same fertility rate than Estonia


(rounding)?
• SELEC T * FRO M fertility
WH ERE RO W(TRU NC ATE(fertility,1), year)
= (SELEC T TRUNC ATE (fertility,1), year
FRO M countries WH ERE country='Estonia');

CREATED BY K. VICTOR BABU


SUB QUERIES WITH EXISTS Or NOT EXISTS


SELEC T column1 FRO M t1 WH ERE EX ISTS (SELEC T * FRO M t2);

What countries exists in my two datasources?
– SELEC T D ISTINC T country FRO M countries c
WH ERE EX ISTS (SELEC T name FRO M countries2 c2 WH ERE
c.country = c2.name);

Now the opposite
– SELEC T D ISTINC T country FRO M countries c
WH ERE NO T EX ISTS (SELEC T name FRO M countries2 c2
WH ERE c.country = c2.name);

CREATED BY K. VICTOR BABU


CORRELATED SUB QUERIES

• A correlated subquery is a subquery that contains a reference to


a table that also appears in the outer query.
• S ELEC T * FRO M t1
WH ERE column1 = ANY (SELEC T column1 FRO M t2
W H ERE t2.column2 = t1.column2);
• In w hich ye ars Estonia h ad fertility rate bigger than it's historical
average.
• SELEC T * FRO M fertility f
WH ERE fertility >
(S ELEC T AVG (fertility) FRO M fertility f2 W H ERE f.country =

f2.country AND f2.country = 'Estonia' G RO U P BY f2.country);

CREATED BY K. VICTOR BABU


CORRELATED SUB QUERIES (Contd..)

In which years Estonia had fertility smaller than average


for 2000 to 2015 (1.53)?
SELEC T * FRO M fertility f
WH ERE fertility <
(SELEC T AVG (fertility)
FRO M fertility f2
WH ERE f.country = f2.country AND f2.country = 'Estonia'
AND f2.year BETWEEN 2000 AND 2015
G RO U P BY f2.country);

CREATED BY K. VICTOR BABU


SUB QUERIES IN THE FROM CLAUSE

• SELEC T ... FRO M (subquery) [AS] name …


• Average of fertility for each continent using historical average
for each country
• SELEC T continent, AVG(avg_ fertility)
FRO M
(SELEC T AVG(fertility) as avg_ fertility, country

FRO M fertility f
WHERE year BETWEEN 2000 AND 2015
GRO UP BY country) AS avgfert
JO IN countries c O N (c.country = avgfert.country)
CREATED BY K. VICTOR BABU
GRO UP BY continent
ACTIVITIES/ CASE STUDIES/ IMPORTANT FACTS RELATED TO
THE SESSION

1. Write a query to display the employee name and hire date for all employees in the same department as Blake. Exclude
Blake.
2. Create a query to display the employee number and name for all employees who earn more than the average salary.
Sort the results in descending order of salary.
3. Display the employee name, department number, and job title for all employees whose department location is Dallas.
4. Write a query to display the name, department number, and salary of any employee whose department number and
salary matches both the department number and salary of any employee who earns a commission.
5. Display the name, department name, and salary of any employee whose salary and commission matches both the salary
and commission of any employee located in Dallas.
6. Create a query to display the name, hire date, and salary for all employees who have both the same salary and
commission as Scott.
7. Create a query to display the employees that earn a salary that is higher than the salary of any of the CLERKS. Sort the
results on salary from highest to lowest.

CREATED BY K. VICTOR BABU


SUMMARY

 Functions and nested subqueries are two powerful features of PostregSQL that can be used to retrieve and manipulate data in
complex ways. Functions are named sets of instructions that can perform calculations on data and return a single value,
while nested subqueries are SQL queries that are embedded within other queries to perform more complex operations, such
as filtering, grouping, and joining data.

 In a session focused on "Functions and Writing SQL Statements Using Nested Subqueries", learners can expect to gain a
comprehensive understanding of these concepts. They will learn how to create user-defined functions in PostregSQL,
understand the differences between built-in and user-defined functions, and be able to apply these functions to perform
specific calculations on data.

 Learners will also learn the syntax of PostregSQL subqueries and differentiate between correlated and non-correlated
subqueries. They will understand how to use nested subqueries to perform complex data retrieval and manipulation
operations and how to construct SQL statements that use functions and nested subqueries efficiently to retrieve and
manipulate data. Additionally, learners will learn how to analyze and optimize existing SQL code that uses functions and
nested subqueries.

 Overall, the goal of a session on Functions and Writing SQL Statements Using Nested Subqueries is to equip learners with
the skills and knowledge necessary to manipulate data effectively using these powerful features of SQL.

CREATED BY K. VICTOR BABU


SELF-ASSESSMENT QUESTIONS

1. Which of the following is a key difference between built-in and user-defined PostregSQL functions?

(a) Built-in functions are created by users, while user-defined functions are pre-existing.
(b) User-defined functions are created by users, while built-in functions are pre-existing.
(c) Built-in functions can only be used with specific data types, while user-defined functions can
be created for any data type.
(d) User-defined functions can only be used with specific data types, while built-in functions can
be used with any data type.

CREATED BY K. VICTOR BABU


SELF-ASSESSMENT QUESTIONS

1. Which of the following is a key difference between built-in and user-defined PostregSQL functions?

(a) Built-in functions are created by users, while user-defined functions are pre-existing.
(b) User-defined functions are created by users, while built-in functions are pre-existing.
(c) Built-in functions can only be used with specific data types, while user-defined functions can
be created for any data type.
(d) User-defined functions can only be used with specific data types, while built-in functions can
be used with any data type.

Answer: d) User-defined functions can only be used with specific data types, while builtin functions can be used with any data type

CREATED BY K. VICTOR BABU


SELF-ASSESSMENT QUESTIONS

2. Which type of subquery is used to perform a calculation or retrieve a single value that is then used in the main query?

(a) Non-correlated subquery


(b) Correlated subquery
(c) Nested subquery
(d) Aggregate subquery

CREATED BY K. VICTOR BABU


SELF-ASSESSMENT QUESTIONS

2. Which type of subquery is used to perform a calculation or retrieve a single value that is then used in the main query?

(a) Non-correlated subquery


(b) Correlated subquery
(c) Nested subquery
(d) Aggregate subquery

Answer: a) Non-correlated subquery

CREATED BY K. VICTOR BABU


TERMINAL QUESTIONS

1. How do you create a user-defined function in PostregSQL, and what are some common use cases for such functions?

2. What is the difference between correlated and non-correlated subqueries, and how do you use each type effectively in
PostregSQL statements?

3.Can you give an example of how nested subqueries can be used to perform a complex data retrieval operation, such as
filtering or grouping data?

4.When should you use built-in PostregSQL functions versus creating your own user-defined functions, and what are
some factors to consider when making this decision?

5.How can you optimize existing PostregSQL code that uses functions and nested subqueries to improve performance
and efficiency?

CREATED BY K. VICTOR BABU


REFERENCES FOR FURTHER LEARNING OF THE
SESSION

Reference Books:
1. Database System Concepts, Sixth Edition, Abraham Silberschatz, Yale University Henry, F. Korth Lehigh
University, S. Sudarshan Indian Institute of Technology, Bombay.
2. Fundamentals of Database Systems, 7th Edition, RamezElmasri, University of Texas at Arlington,
Shamkant B. Navathe, University of Texasat Arlington.
3. An Introduction to Database Systems by Bipin C. Desai

Sites and Web links:


1. https://www.javatpoint.com/postgresql-tutorial
2. https://www.tutorialspoint.com/sql/index.htm
3. https://www.programiz.com/sql /

CREATED BY K. VICTOR BABU


THANK YOU

Team – Database Management System

CREATED BY K. VICTOR BABU

You might also like