UNIT4_SQL
UNIT4_SQL
Function that act only on one value at a time are called scalar functions.
6 rows selected.
----------
75.1666667
MIN() function: The aggregate function SQL MIN() is used to find the minimum value or
lowest value of a column or expression. This function is useful to determine the smallest of
all selected values of a column.
Syntax : MIN([ALL | DISTINCT] expression )
SQL> select min(marks) "value" from stud_marks;
value
----------
56
MAX() function
The aggregate function SQL MAX() is used to find the maximum value or highest value of a
certain column or expression. This function is useful to determine the largest of all selected
values of a column.
SQL Syntax : MAX ([ALL | DISTINCT] expression
SQL> select max(marks) "value" from stud_marks;
value
----------
92
SUM() function
The SQL AGGREGATE SUM() function returns the sum of all selected column.
SQL Syntax : SUM ([ALL | DISTINCT] expression )
Example : SUM()
SQL> select sum(marks) "value" from stud_marks;
value
----------
451
COUNT() function
The SQL COUNT function returns the number of rows in a table satisfying the criteria
specified in the WHERE clause. It sets on the number of rows or non NULL column values.
SQL Syntax : COUNT(*) , COUNT( [ALL|DISTINCT] expression )
pg. 2
Example : COUNT()
COUNT(*)
----------
SCALAR FUNCTIONS
SQL Server Scalar Functions allow you to perform different calculations on data values.
These functions operate on single rows only and produce one result per row. There are
different types of Scalar Functions, this tutorial covers the following:
String functions
are used to perform an operation on input string and return an output string.
Following are the string functions defined in SQL:
Length
----------
LOWER(): This function is used to convert the upper case string into lower case.
lower
-------
Welcome
1. UPPER(): This function is used to convert the lower case string into upper case.
pg. 3
upper
-------
WELCOME
INITCAP(CHAR): It returns a string with the first letter of each word in uppercase.
initcap
------------
Welcome Home
SUBSTR(): This function is used to find a sub string from the a string from the given position.
sub
----
Ello
LTRIM(): This function is used to cut the given sub string from the original string.
left
-----
IKiTA
RTRIM(): This function is used to cut the given sub string from the original string.
RTRIM
-----
anjal
LPAD(): This function is used to make the given string of the given size by adding the given
symbol.
pg. 4
SQL> select lpad('hello',10,'*') "left pad" from dual;
left pad
----------
*****hello
RPAD(): This function is used to make the given string as long as the given size by adding the
given symbol on the right.
right pad
----------
hello*****
Numeric functions
Numeric Functions are used to perform operations on numbers and return numbers.
CEILING(): It returns the smallest integer value that is greater than or equal to a number.
FLOOR(): It returns the largest integer value that is less than or equal to a number.
TRUNCATE(): This doesn’t work for SQL Server. It returns 7.53635 truncated to 2 places right
of the decimal point.
Example:-
pg. 5
ABS(-15)
----------
15
raised
----------
25
round
----------
round value
-----------
15.2
sqrt
----------
mode
----------
pg. 6
SQL> SELECT POWER(4, 2) "power" from dual;
power
----------
16
least
----------
DATE FUNCTIONS
Add_months(d,n)
It returns the date after adding the number of months specified in the
function.
Output ANS
01-OCT-11
Last_day(d):
Ans
31-aug-2022
Months_between(d1,d2):
months
pg. 7
----------
NEXT_DAY(
---------
08-FEB-98
CURRENT_TIMESTAMP
---------------------------------------------------------------------------
SYSDATE LAST_DAY(
--------- ---------
15-MAR-23 31-MAR-23
ADD_MONTH
---------
15-JUL-23
Conversion Functions
If the programmer wants,they can explicitly convert data types from one to another. There
are SQL functions provided for this express purpose. These SQL functions are −
pg. 8
TO_NUMBER
Converts character value containing a number in the value of the number datatype
TO_NUMBER(SUBSTR('$100',2,3))
--------------------------------------------
100
Here, the value 100 will be added to every products selling price in the product
master table
Number is converted to char values exactly long enough to hold significant digits
char
------------
$012,345
TO_CHAR(SYSDATE,'M
----------------------------
pg. 9
Floor(n) Returns the largest integer value Select Floor(24.8);
that is greater than or equal to a O/P : 24
number.
Power (m,n) Returns m raised to nth power. Select power(3,2);
O/P : 9
Round (n,m) Returns n rounded to m places the Select round(15.91,1);
right of decimal point. O/P : 15.9
Square(n) Returns square of n. Select Square(4);
O/P : 16
Sqrt(n) Returns square root of n. Select sqrt(25);
O/P : 5
Exp(n) Returns e raised to the nth power, Select exp(1); O/P : 1
e=2.17828183.
X%Y Returns reminder of X modulus Y. Select 5%3;
O/P : 2
Pi() Returns the value of pi. Select Pi();
O/P : 3.14159265358979
Sin(n) Returns the sine value of n. Select Sin(0);
O/P : 0
Cos(n) Returns the cosine value of n. Select Cos(0);
O/P : 1
Tan(n) Returns the tangent value of n. Select Tan(0);
O/P : 0
Rand(n) Returns a random decimal number Select Rand();
between 0 and 1. O/P : 0.845610816728278
Log(n) Returns the log value of n having Select Log(1);
base e. O/P : 0
Log10(n) Returns the log value of n having Select Log10(1000);
base 10. O/P : 3
String function
ASCII(x) Returns ASCII value of character. Select ASCII(‘A’);
O/P : 65
Char(x) Returns a character of int ASCII Select CHAR(65);
code. O/P : A
Concat() Concatenates two strings. Select CONCAT(‘great’,’DIET’);
O/P : greatDIET
Len () Returns the number of character in Select LEN(‘DIET’);
x. O/P : 4
Lower() Converts the string to lower case. Select LOWER(‘DIET’);
O/P : diet
Upper() Converts the string to upper case. Select UPPER(‘diet’);
O/P : DIET
Ltrim() Trim blanks from the left of x. Select LTRIM(‘ diet ’);
O/P : diet
Rtrim() Trim blanks from the right of x. Select RTRIM(‘ diet ’);
O/P : diet
Replace() Looks for the string and replace the Select Replace(‘this is college’,’is’,’may
string every time it occurs. be’);
O/P :thmay be may be college
Substring() Returns the part of string Select Substring(‘this is college’,6,7);
O/P : is my c
Left() Returns the specified number of Select Left(‘this is college’,7);
characters from the left. O/P : this is
pg. 10
Right() Returns the specified number of Select Right(‘this is college’,7);
characters from the right. O/P : college
Reverse() Returns the reversed string. Select Reverse(‘DIET’);
O/P : TEID
Space() Returns n number of spaces Select Space(10);
O/P :
Replicate() Returns repeated string for n Select Replicate(‘DIET’,2);
number of times. O/P :DIETDIET
Date function
Getdate() Returns current date and time. Select Getdate();
O/P : 2018-09-08 10:42:02.113
Day() Returns day of a given date. Select Day(‘23/JAN/2018’);
O/P : 23
Month() Returns month of a given date. Select Month(‘23/JAN/2018’);
O/P : 1
Year() Returns year of a given date. Select Year(‘23/JAN/2018’);
O/P : 2018
Isdate() Returns 1 if the expression is a valid Select Isdate(‘31/FEB/2018’);
date, otherwise 0. O/P : 0
Datename() Returns the specified part of a given Select Datename(month,‘1-23-2018’);
date as varchar value. O/P : January
Datepart() Returns the specified part of a given Select Datepart(month,‘1-23-2018’);
date as int value. O/P : 1
Dateadd() Returns datetime after adding n Select Dateadd(day,5,‘23/JAN/2018’);
numbers of datepart to a given O/P : 2018-01-28 00:00:00.000
date.
Datediff() Returns the difference between two Select Datediff(day,5,
date values, based on the interval ‘23/JAN/2018’,’23/FEB/2018’);
specified. O/P : 31
Eomonth() Returns the last day of month. Select Eomonth(’23/FEB/2018’);
O/P : 2018-01-31
Student
Rollno Name SPI
1 Raju 8
2 Hari 9
3 Mahesh 7
4 NULL 9
5 Anil 5
1. Avg() : It returns the average of the
data values.Select Avg(SPI)
FROM Student;
pg. 11
Output: 7
2. Sum() : It returns the addition of the
data values.Select Sum(SPI)
FROM Student;
Output: 38
3. Max() : It returns maximum value for a
column.Select Max(SPI) FROM
Student; Output: 9
4. Min() : It returns Minimum value for a
column.Select Min(SPI) FROM
Student; Output: 5
5. Count() : It returns total number of values in a given
column.Select Count(Name) FROM Student;
Output: 4
6. Count(*) : It returns the number of rows in
a table.Select Count(*) FROM
Student;
Output: 5
Group by and Having Clause
The group by and having clause are parallel to the order by and where clause, except
that they act on record sets, and not on individual records.
The group functions perform an operation on a group of rows and return one result.
When a column is used in GROUP BY clause, the result is sorted in ascending order
by that column by default. i.e., GROUP BY has implied ORDER BY. Still ORDER BY can
be used to explicitly change the implied sorted order.
The having clause is used to give conditions and filter the groups created by group by
clause.
The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(),
MIN(), SUM(), AVG()) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Example:-
CUSTOMER
pg. 12
CID CNAME COUNTRY
---------- -------------------- --------------------
1 nikita india
2 rahul canada
3 siya india
4 anjali india
5 parul chin
6 rahul canada
7 laxman india
Example 1:
select country from con group by country;
COUNTRY
--------------------
chin
india
canada
Example 2:
select count(cid)"country",country from con group by country;
country COUNTRY
-------- --------------------
1 chin
4 india
2 canada
The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:
Example
SQL> select count(cid)"country",country from con group by country having count(cid)=4;
pg. 13
country COUNTRY
---------- --------------------
4 india
The CUBE operators, like the ROLLUP operator produces subtotals and grand totals as
well. But unlike the ROLLUP operator it produces subtotals and grand totals for every
permutation of the columns provided to the CUBE operator.
Example:- (Rollup)
country COUNTRY
---------- --------------------
2 canada
1 chin
4 india
Cube Example:
country COUNTRY
---------- --------------------
1 chin
4 india
2 canada
pg. 14
Subquery:-
The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement
or inside another subquery.
A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.
You can use the comparison operators, such as >, <, or =. The comparison operator
can also be a multiple-row operator, such as IN, ANY, or ALL.
A subquery is also called an inner query or inner select, while the statement
containing a subquery is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an inner
query can be passed to the outer query.
In a subquery, the outer query's result is dependent on the result-set of the inner
subquery. That's why subqueries are also called nested queries.
( SELECT [DISTINCT] subquery_select_parameter
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ] ...]
[HAVING search_conditions] )
1. executes the subquery first; selects minimum age from the Customers table.
2. executes the outer query; selects rows where age is equal to the result of subquery.
Example:- (select)
1 john 31 USA
2 robert 22 USA
3 david 22 UK
4 john 25 UK
5 betty 28 UAE
pg. 15
SQL> select * from cust where age=(select min(age) from cust);
2 robert 22 USA
3 david 22 UK
Example (insert)
Table created
Table created.
pg. 16
where pid in(select pid from product1 where price>1000);
9 rows created.
9 rows selected.
Update subquery: -
where oid=101;
updated.
Delete subquery:-
SQL> delete from order12 where oid in(select pid from product1 where
pro_name='scanner');
1 row deleted.
pg. 17
Types of Subqueries
Single Row Sub Query: Sub query which returns single row output. ...
Multiple row sub query: Sub query returning multiple row output. ...
Correlated Sub Query: Correlated subqueries depend on data provided by the outer
query.
In Multiple row, subquery returns one or more rows to the outer SQL statement.
You may use the IN, ANY, or ALL operator in outer query to handle a subquery that
returns multiple rows.
A correlated subquery is evaluated once for each row processed by the parent
statement.
pg. 18
3. Full Outer Join
Cross join
Self Join
INNER JOIN
It returns records that have matching values in both tables.
Syntax:
SELECT columns
FROM table1 INNER JOIN
table2 ON table1.column =
table2.column;
Example:
Consider the following tables:
Student Result
RNO Name Branch RNO SPI
101 Raju CE 101 8.8
102 Amit CE 102 9.2
103 Sanjay ME 104 8.2
104 Neha EC 105 7
105 Meera EE 107 8.9
106 Mahesh ME
Output:
Inner Join
RNO Name Branch SPI
101 Raju CE 8.8
102 Amit CE 9.2
104 Neha EC 8.2
105 Meera EE 7
The LEFT JOIN keyword returns all records from the left table (table1), and the
matchedrecords from the right table (table2).
The result is NULL from the right side, if there is no match.
Syntax:
SELECT columns
FROM table1 LEFT OUTER
JOIN table2ON table1.column
= table2.column;
pg. 19
Example:
Consider the Student and result tables:
SELECT Student.RNO, Student.Name, Student.Branch,
Result.SPIFROM Student LEFT OUTER JOIN Result
ON Student.RNO = Result.RNO;
Output:
Left Join
RNO Name Branch SPI
101 Raju CE 8.8
102 Amit CE 9.2
103 Sanjay ME NULL
104 Neha EC 8.2
105 Meera EE 7
106 Mahesh ME NULL
The RIGHT JOIN keyword returns all records from the right table (table2), and
thematched records from the left table (table1).
The result is NULL from the left side, if there is no match.
Syntax:
SELECT columns
FROM table1 RIGHT OUTER JOIN
table2ON table1.column =
table2.column;
Example:
Consider the Student and result tables:
SELECT Student.RNO, Student.Name, Student.Branch,
Result.SPIFROM Student RIGHT OUTER JOIN Result
ON Student.RNO = Result.RNO;
Output:
Right Join
RNO Name Branch SPI
101 Raju CE 8.8
102 Amit CE 9.2
104 Neha EC 8.2
105 Meera EE 7
NULL NULL NULL 8.9
pg. 20
JOIN table2ON table1.column
= table2.column;
Example:
Consider the Student and result tables:
SELECT Student.RNO, Student.Name, Student.Branch,
Result.SPIFROM Student FULL OUTER JOIN Result
ON Student.RNO = Result.RNO;
Output:
Full Join
RNO Name Branch SPI
101 Raju CE 8.8
102 Amit CE 9.2
103 Sanjay ME NULL
104 Neha EC 8.2
105 Meera EE 7
106 Mahesh ME NULL
NULL NULL NULL 8.9
CROSS JOIN
When each row of first table is combined with each row from the second table,
knownas Cartesian join or cross join.
SQL CROSS JOIN returns the number of rows in first table multiplied by the
number ofrows in second table.
Syntax:
SELECT columns
FROM table1 CROSS JOIN table2;
Example:
Consider the following tables:
Color Size
Code Name Amount
1 Red Small
2 Blue Large
Output:
Cross Join
Code Name Amount
1 Red Small
2 Blue Small
1 Red Large
2 Blue Large
SELF JOIN
pg. 21
A self join is a regular join, but the table is joined with itself.
Here, we need to use aliases for the same table to set a self join between single
table.
Syntax:
SELECT a.column, b.column
FROM tablename a CROSS JOIN
tablename bWHERE
a.column=b.column;
Example:
Consider the following table:
Employee
EmpNo Name MngrNo
E01 Tarun E02
E02 Rohan E05
E03 Priya E04
E04 Milan NULL
E05 Jay NULL
E06 Anjana E03
Practice
Table created.
Table created.
pg. 22
102 Amit CE
103 Sanjay ME
104 Neha EC
105 Meera EE
106 Mahesh ME
SQL> insert into result values('&rno','&spi');
SQL> select * from result;
RNO SPI
---------- ----------
101 9
102 9
104 8
105 7
107 9
SQL> SELECT Student.RNO, Student.Name, Student.Branch, Result.SPI FROM Student
INNER JOIN Result ON Student.RNO = Result.RNO;
SQL> SELECT Student.RNO, Student.Name, Student.Branch, Result.SPI FROM Student LEFT
OUTER JOIN Result ON Student.RNO = Result.RNO;
SQL> SELECT Student.RNO, Student.Name, Student.Branch, Result.SPI FROM Student RIGHT
OUTER JOIN Result ON Student.RNO = Result.RNO;
SQL> SELECT Student.RNO, Student.Name, Student.Branch, Result.SPI FROM Student FULL
OUTER JOIN Result ON Student.RNO = Result.RNO;
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Practice
SQL> select * from result where
exists(select name from student where
student.rno=result.rno);
SQL> select * from student;
SQL> select * from result where
not exists(select name from student where
student.rno=result.rno);
SQL> select * from student;
pg. 23
Introduction to SQL Set Operators
SQL set operators are used to combine the results obtained from two or more queries into a
single result.
The queries which contain two or more subqueries are known as compounded queries.
Operator
Intersect Returns only the common records obtained from two or more SELECT
statements.
Minus Returns only those records which are exclusive to the first table.
pg. 24
R S RUS
A 1 A 1 A 1
B 2 C 2 B 2
D 3 D 3 C 2
F 4 E 4 D 3
E 5 F 4
E 5
E 4
Intersection
Operation: Selects tuples those are common in both relations.
Symbol : ∩ (Intersection)
Notation : Relation1 ∩ Relation2
Example
R S R∩S
A 1 A 1 A 1
B 2 C 2 D 3
D 3 D 3
F 4 E 4
E 5
pg. 25
Example:
∏Name (Emp) ∩ ∏Name (Cst)
Name
Manisha
Anisha
Difference:-
Operation: Selects tuples those are in first (left) relation but not in second
(right)relation.
Symbol : — (Minus)
Notation : Relation1 — Relation2
Example :
R S R—S
A 1 A 1 B 2
B 2 C 2 F 4
D 3 D 3 E 5
F 4 E 4
E 5
pg. 26