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

Chapter 3 Database Query Using SQL Functions

SQL functions are statements that accept input parameters and return a result. Functions can return a single value or a table. There are two main types of functions: scalar functions and aggregate functions. Scalar functions operate on scalar/single values and return a single value. Examples include mathematical, text, and date functions. Aggregate functions operate on sets of data and return a value computed from the set, like COUNT, MAX, MIN, SUM, and AVG. Functions provide an alternative to commands and are used as part of SQL queries, typically in the SELECT statement.

Uploaded by

Aditi Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Chapter 3 Database Query Using SQL Functions

SQL functions are statements that accept input parameters and return a result. Functions can return a single value or a table. There are two main types of functions: scalar functions and aggregate functions. Scalar functions operate on scalar/single values and return a single value. Examples include mathematical, text, and date functions. Aggregate functions operate on sets of data and return a value computed from the set, like COUNT, MAX, MIN, SUM, and AVG. Functions provide an alternative to commands and are used as part of SQL queries, typically in the SELECT statement.

Uploaded by

Aditi Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

SQLfunctions statements that accept only

input
it is a set of SQL function can
Dasically,
and return the result. A
parameters, perform actions Functions a r e o t
alternate to
value or a table.
single
returh an only a command(generally
commands but are used as a part of sql
sqi
select command).
Types of Function (System defined) that is,
on scalar values
- -

A scalar function is a function that operates


returns a
values as arguments directly and
it takes one (or more) input
These functions can be applied
value. Maths,text, date functions etc.
over column(s) of a
table to perform relevant operation on value of
each record.
For e.g. select left(name,4) from student;
will display 4 left side letters of each row of name field from student
table.

Created by: Abhay


An aggregate function is a function that operates on aggregate data
that is, it takes a complete set of data as input and returns a value that
is computed from all the values in theset. E.g. max(),
min(), count()
sum(), avg().Generally these are used for report preparation & mostly
used with group by and having clause.

Created by: Abhay


Scalar Functionn:
Mathematical functions:
Perform operation over numeric values.

POWER() :
returns the value of a number raised to the power of
anotheer
power()
number. The synonym of power() is pow().

Syntax pow(m,n)
m A number which is the base of the exponentiation.

n A number which is the exponent of the exponentiation.

Created by: Abhay


mysql> SELECT POW(2,3
+ --
POWC,3)|I

1 row in set (.00 se

mysal sELECT POwER(23);


t-

POWER(2,B) I|

now in set (o.0 se

ROUNDb0
number rounded to a certain number of
The round() function returns a

decimal places.
Syntax - ROUND(column_name,decimals)
The field to round.
column_name: Required
to be returned.
Decimals: Required Specifies the number of decimals
Created by. Abhay
integer ,if its
next right
value is rounded to next
Decimal places position
side number is>=5
if we do not specify
Default decimal place is 0 position
mys1 sELECT OUND(3.72,2)
my sl$ELECT ROUND (36.4) ..-4---
---- ROUND( 36.725 2)
ROUND 36.4)
+-
36 73
36

row in set (.00 sec) 1 row in set (.o0 seq)

mysl$ELECT ROUND ( 36. 7) ; mysl sELECT ROUND( 36.72,2)

ROUND 36.7) IROUND 361723 2)


-
36 72
B7

1 row ih set (9.00 sec) 1 row ih set (.00 sed)

TRUNCATE()
Page 8 Created by: Abhay
The truncate() function returns a number to a certain number of
decimal placesS.
Syntax TRUNCATE(number,decimals)
number : Required The field to round.
Decimals: Required Specifies the number of decimals to be returned.

mysq SLEC TRUNCATE(6.41)


TRUNCATE (36.4,)
36.4
1 row in set (.pe sec)

mysql SELEC TRUNCATE(6 1)


+
TRUNCATE(36.7,1)
36.7
ro inset (0.pe sec)

Created by: Abhay


MOD)
The MOD() function returns the remainder of one number
divided by
function:
another. The following shows the syntax of the MOD()

Syntax MOD(dividend,divisor)
Dividend -

is a literal number or a numeric expression to divide.


Divisor- is a literal number or a numeric expression by which
to divide the dividend.
mysg1> sELECT HOD(11,
MOD(11,3

1 row in set (.00 sed)

mysl>SELECT OD (10.5,3)
MDD ( 10.53)

1 rpu in set (.0e sed)


Created by: Abhay
Text functions
Perform operation over string values.

UPPER(str)
to uppercase.
string str with all characters changed
Returns the
mysql> SELECT UPPER(Tej);
TEJ
UCASE(str)-UCASE() is a synonym for UPPER().

LOWER(str)-
changed to lowercase
Returns the string str with all characters
mysql> SELECT LOWER("'QUADRATICALLY");

Created by: Abhay


'quadratically'
LCASE(str)
LCASE() is a synonym for LOWER().

SUBSTRING(str, pos)
SUBSTRING(str, pos,len)- SUBSTRING(str FROM pos FOR len)
The forms without a len argument return a substring from string str
starting at position pos. The forms with a len argument return a
substring len characters long from string str, starting at position pos.
The forms that use FROM are standard SQL syntax. It is also possible
to use a negative value for pOs. In this case, the beginning of the
substring is pos characters from the end of the string, rather than the
beginning.
mysql> SELECT SUBSTRING('practically',5);

Created by: Abhay


-'tically'
mysql> SELECT SUBSTRING'foofarbar FROM 4)
farbar'
mysql> SELECT SUBSTRING'Quadratically',5,6);
->'ratica'
mysql> SELECT SUBSTRING('Aakila', -3);
->'ila'
mysql> SELECT SUBSTRING('Aakila', -5, 3);
'aki
mysql> SELECT SUBSTRING('Aakila' FROM-4 FOR 2);
'ki'

MID(str,pos,len)
synonym for SUBSTRING(str,pos,len),
substr()
MID(str, pos, len) is a

LENGTH(str)
Created by: Abhay
Returns the length of the string str
mysql> SELECT LENGTH('text);
>4

LEFT(str,len)
the string str, or NULL if any
Returns the leftmost len characters from
argument is NULL.
mysql> SELECT LEFT("Toolbar', 4);
->Tool'

RIGHT(str,len)
Returns the rightmost len characters from the string str, or NULL if
any argument is NULL.
mysql> SELECT RIGHT("Toolbar, 3);
->'bar'
Created by: Abhay
INSTR(str,substr)-
Returns the position of the first occurrencee of substring substr in
string str.
mysql> SELECT INSTR('Toobarbar, 'bar);
->4
mysql> SELECT INSTR('xbar', 'ybar";
->0

LTRIM(str)
Returns the string str with leading space characters removed.
mysql> SELECT LTRIM(' Toolbar");
>Toolbar'

Created by: Abhay


RTRIM(str) characters removed.
Returns the string str with trailing space

mysql> SELECT RTRIM(Toolbar ");


-Toolbar

TRIM(T{BOTH | LEADING | TRAILING} remstr]

FROM] Str) If
str with all remstr prefixes or suffixes removed.
Returns the string BOTH
LEADING, or TRAILING is given ,
n o n e of the specifiers BOTH,
is assumed.
mysql> SELECT TRIM tool ');
->"bar'
'x' FROM 'xxxtooixxx');
mysql> SELECT TRIM(LEADING
->toolxxx'
FROM 'xxxtoolxxx');
mysql> SELECT TRIM(BOTH '*'
->tool'
Created by: Abhay
mysql> SELECT TRIM(TRAILING
->tool' 'xyz' FROM 'toobxxx');

Date functions-
Perform operation over date values.

NOW()
Returns the current date and time as a value in "YYYY-MM-DDb
the
hh:mm:ss' or YYYYMMDDhhmmss format, depending on whether
function is used in string or numeric context.
mysql> SELECT NOW);
->2020-04-0523:50:26'
+0;
mysql> SELECT NOW()
Created by: Abhay
20200415235026.000000D
Here +0 means +0 second

DATE(expr)- datetime expression expr.


Extracts the date part of the date or

mysql> SELECT DATE('2003-12-31 01:02:03');


->2003-12-31'

MONTH(date)-
Dofturns the month for date, in the
December, 0 for dates range 1 to 12 for
or
such as
'0000-00-00' January to
or 2008-00-00'
-00-00' that
Created by: Abhay
have a zero month part.
mysql> SELECT MONTH(2008-02-03);
-2

MONTHNAME(date)-
Returns the full name of the month for date.

mysql> SELECT MONTHNAME(2008-02-03");


->"February'

YEAR(date) in the range 1000 to 9999,


or 0 for the
for date,
Returns the vear

zero" date.
Created by: Abhay
mysql> SELECT YEAR('1987-01-01');
->1987

DAY(date)-
Returns the day of the month for date, in the range 1 to 31, or 0 for
dates such as '0000-00-00' or '2008-00-00' that have a zero day part.
mysql> SELECT DAYOFMONTH('2007-02-03');
-3

DAYNAME(date)
Returns the name of the weekday for
date.
mysql> SELECT DAYNAME( 2007-02-03'):
-'Saturday'

Created by: Abhay


DAYOFWEEK(date)-
0atturns the
number of the
weekday for date.
mysql> SELECT DAYNAME((2007-02-03'):
-> 'Saturday'

DAYOFYEAR(date)-
date.
number of the day of year for given
Returns the
mysql> SELECT DAYNAME('2007-02-03');

'Saturday'
Created by: Abhay
Aggregate Functions

Aggregate Functions & NULL


Perform operation over set of values Consider a
table llowing
Emp having followino
records as-
SQL Queries
mysql> Select Sum(Sal) from EMP; Emp
12000 Code Name Sal
mysql> Select Min(Sal) from EMP;
E1 Mohak NULL
3500
E2
mysql> Select Max(Sal) from EMP; Anuj 4500
E3
4500
mysql> Select Count(Sal) from EMP; E4
Vijay NULL
Vishal 3500
3
ES Anil 4000
mysql> Select Avg(Sal) from EMP;
4000
mysql> Select Count(*) from EMP; Null values are
5 excluded while
(avg)aggregate function is used
Group with Aggregate Functions
An Aggregate function may applied on a column with DISTINCT or ALL keyword.
If nothing is given ALL is assumed.
Using SUM (<Column>)
This function returns the sum of values in given column or expression.
mysql> Select Sum(Sal) from EMP;
mysql> Select Sum(DISTINCT Sal) from EMP;
mysql> Select Sum (Sal) from EMP where City="Jaipur;
mysql> Select Sum (Sal) from EMP Group By City;
mysql> Select Job, Sum(Sal) from EMP Group By Job;
Using MIN (<column>)
This functions returns the Minimum value in the given column.
mysql> Select Min(Sal) from EMP;
mysql> Select Min(Sal) from EMP Group By City;
mysql> Select Job, Min(Sal) from EMP Group By Job;

Created by: Abhay


Using MAX (<Column>) coIumn.

returns the Maximum value in given


n i s Tunction

mysql> Select Max(Sal) from EMIP;


where City="Jaipur
mysql> Select Max(Sal) from EMP
mysql> Select Max(Sal) from EMP Group
By City;

Using AVG (<column>)


This functions returns the Average value
in the given column.
mysql> Select AVG(Sall) from EMP;
mysql> Select AVG(Sal) from EMP Group By City;

Using COUNT (<*|column>)


This functions returns the number of rows in the given column.
mysql> Select Count(*) from EMP;
mysql> Select Count($al) from EMP Group By City:
mysgl> Select Count("), Sum($al) from ElMP Groujp By Job:
Aggregate Functions & Conditions
YOu may use any condition on group, if
<condition> required. HAVING
clause is used to apply a condition on a
group.
mysql> Select Job,Sum(Pay) from EMP Group By Job HAVING Sum(Pay)>=8000;
mysql> Select Job, Sum(Pay) from EMP Group By Job HAVING Avg(Pay)>=7000;
mysql> Select Job, Sum(Pay) from EMP Group By Job HAVING Count(*)>=5;

mysql> Select Job, Min(Pay),Max(Pay), Avg(Pay) from EMP Group By Job HAVING
Sum(Pay)>=8000;
mysql> Select Job, Sum(Pay) from EMP Where City="Jaipur
Note:-Where clause works in respect of whole table but Having works on
Group only. If Where and Having both are used then Where will be executed first.

Created by: Abhay


Ordering Query Result-ORDER BY
Clause descending (Z-A)
A query result can be orders in ascending (A-Z) or

order as per any column. Default is Ascending order.

mysql> SELECT
*
FROM Student ORDER BY City;

To get descending order use DESC key word.

mysql> SELECT* FROM Student ORDER BY City DESC;

mysql> SELECT Name, Fname, City FROM Student Where Name LIKE 'R% ORDER
BY Class;

Created by: Abhay

You might also like