Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Database Query

Using SQL

4.1 INTRODUCTION

Class XI. We now know that


We have
studied in detail the concepts of database and sQL in
for accessing and manipulating databases.
sOL (Structured Query Language) is a standard language Database
from Relational
are used to create, transform and retrieve information
SOL commands using SQL
user and database. By
Management Systems (RDBMS) and to create an interface between
for any data in the database and perform
other functions like creating
commands, one can search In this chapter, we will
records, modifying data, removing rows, dropping table, etc.
tables, adding
functions (math, string and date), group by
clause and other important SQL concepts.
learn aggregate
is a unified, non-procedural language used for creating,
CTM: SQL (Structured Query Language)
data in relational databases.
accessing, handling and managing
Let us begin with functions in SQL.

4.2 FUNCTIONS IN MySQL


used
Functions are apowerful and extensively MySQL
is
feature of SQL. In MySQL, data manipulation
Functions
done by using queries with functions. A function Input Output
canbe defined as a predefined set of commandsS Function
certain operations to
that helps in performing
Obtain either a sigle value or a result set. Function performns
arg1 action
collection of in-built
provides a large arg 2
that Re sulf
Tunctions, also called library functions,
for value
Can be used
directly with SQL statements
performing calculations on data. Using these
of values stored in
arg n
CEIOns, we can find sum
Functions
d Column or convert all characters of a name to
to
Fig. 4.1: MysQL
w e r case or round off salaries in a column
The values that
to manipulate data.
MySQL supports many functions
ecimal places and so on.
or P a r a m e t e r s .
S e d to functions are known as Arguments

called, performs certain


commands which, when
CTM: A Tunction can be defined as a set of predefined
Operations and returns a single value.
The syntax to use a function in the sELECT statement is given as under:

Syntax:
SELECT <function>(colunmn_name) FROM <table_name>;
While working with standard library functions, the following points must be keat in
(a) The
kept
in mind
name of the column on which the function is to be executed must be
parentheses. closed within
enclosed .

(b) Only one column can be specified within one set of


parentheses.
(c) To use more than one function with the same select
one after the other
statement, functions are writ,
separated by a comma. tten
(d) If the same function is required to be used for more
than one Column,
function name has to be then agajin the
repeated in the select statement.
Functions in MySQL are classified into two types:
Single Row (or Scalar) Functions
Multiple Row (or Group or
Aggregate) Functions

Functions

Single Row
Functions Multiple Row
Functions
Fig. 4.2: Classification of MySQL Functions
4.3 SINGLE ROW FUNCTIONS
Single row functions operate on a
single row to return a single
value per row as the
output,IThey can accept one or more
arguments but return
only one result per row. These are also
known asScalar Functions. When Scalar Function

return a single result for


applied to a table, they
every row or the queried tad1E. 1
can be used with
SELECT, WHERE and ORDER BY clause. hey Fig. 4.3(a): Single Row/Scalar
Function
They are further categorized into:
1. Mathematical/Numeric functions
2. String functions

3 Date and Time functions

4.3.1 Mathematical/Numeric Functions


Mathematical functions perform mathematical
used mathematical functions are
operations on numeric values. The most
POWO, MODO, ROUNDO, ABS), commonly
Let us discuss these functions first.
TRUNCATE), etc
(a) POWO: Returns the argument raised to the specitied power POWERQ works the same way.
Tts syntax is:
SELECT POW (m,n)/ POWER(m, n);
raised to number 'm.
is the power to be
number and
n
the
m
is Result: 16
Here,

SELECT POW (2,4);


F o re x a m p l e ,
) Result: 0.25

(i)
SELECT POW(2,-2);
Result: -8
(ii) SELECT POW(-2,3);

45); Result: 19.6282.


(iv) SELECT POW (2.37,3. ROUND(x, d)
whereas
to the 0 decimal place
rounds the argument number rounded
ROUND(X) function r e t u r n s a
pQlIND): decimal places. The ROUND()
R to d
b argument
Onds the decimal places.
number of
certain
to a
SELECT
ROUND (x, d);
Syntax:
value to be rounded off.)
or
is the field
X Required (It to be returned.)
(Specifies
the number of decimals
d- Required
to be rounded
454.352-Value

1 2 3 Decimal places
-2-1 0 of values
different sets
function for
behaviour of ROUND0
the
below exhibit
The situations
given
If the
result is a n integer.
for x and d: decimal and the
rounded up to 0 digits of n u m b e r is
i n c r e a s e d by
1.
x is
Ifd is not specified:
>5, then the integer
() decimal value is 5 or
the
first digit after For example,
nothing is specified.
0 if
Default decimal place is Result: 2
.58);
mysql>SELECT
ROUND (1 Result:-1
mysql>SELECT ROUND( - 1 . 2 3 ) ;
result is an integer value
decimal and the

rounded up to
0 digits of
If d is 0: x is
ii
Result: 1
For example,
(1.298, 0);
m y s q l > S E L E C T
ROUND
Result: -6
mysql>SELECT ROUND(-5.898, 0);
(d+1)th digit;
after the decimal by checking
d digits
up to float.
the result is
rounded a
is
by 1 and
x
integer:
positive increased

ii) Ifd is a
dth digit is
then the
if it is 5 or > 5,
Result: 3.799
For example, 3);
(3.79867,,
ROUND
checking the
m y s q l > S E L E C T

before the decimal by


digits
rounded up to d all trailing dth digits
are

integer:
x is
is
increased by 1,
If d is a negative
then the
(d-1)" digit s e c o n d argument
is negative,
(iv) >5, value. So, if the
is 5 or
integer
dth digit; if it the resultis
an
-1000 respectively.
ero
and
the
nearest 10, 100,
converted to off to
rounds
then it
-3,
i.e., -1, -2,
For example,
Result: 20
-1);
(23.298,
Mysql>SELECT
ROUND Result: 40000
(36567.78,
-4);
Mysql>SELECT
ROUND

Database Query using SQL 4.3


aysqls SELECT ROUNDE.s9)3
ROUND(1.58) 1

1 row in set (0.00 sec)


mysql SELECT ROUND(-1.23)

ROUND(-1.23)

1 row in set (0.00 sec)

mysql SELECT ROUND(1.298, 0);


-******-+

| ROUND(1.298, 0)

row in set (0.00 sec)

mysql> SELECT ROUND(-s.898, 0)

ROUND(-5.898, 0)
-6

row in set (0.00 sec)

mysql> SELECT ROUND(3.79867, 3);


t------------4
ROUND(3.79867, 3) 1
- --

3.799
- ---*-+

row in set (0.00 sec)


mysql SELECT ROUND(23.298, -1)
- ---*--+
ROUND(23.298, -1)
20

row in set (0.00 sec)

mysql> SELECT
ROUND(36567.78, -4);
-------

ROUND (36567.78,-4) - -

40000

in set
row
(0.00 sec)
mysql>

(c) TRUNCATEO: Truncates the argument to


is the
specified number of decimal
places. The following
syntax of the
TRUNCATE) function:
Syntax: SELECT TRUNCATE(x, d);
X-
Required (It is the field or value to be truncated.)
d Required (Specifies the number
of decimals to be returned.)
The situations given below exhibit the behaviour of
for x and d: TRUNCATE() for different sets of values
.If d is 0, it removes all the decimal values and returns only the
If d is a positive number, the function truncates the number x to d integer.
digits right to the decimal
point.
I f d is a negative number, the function truncates the number x to d digits left
point.
of the decimal

4.4 Informatics Practices with Python-XIl


TRUNCATE (7.29,0) Result: 7
reNample, (i) mysql>SELECT Result: 275
mysql>SELECT TRUNCATE (27.59,1);
TRUNCATE (389.23, -2):
) Result 300
(üi) mysql>SELECT

function returns the modulus (remainder) of one number divided by

MOD): TheMOD)
the syntax of the MOD) function
following is
another: The fol
The
ther
M O D [ d i v i d e n d , divisor);
SELECT
Syntax: SEL
Syntax: or a numeric expression to divide
number
Is a literal
dividend- dividend is to he divided
number or a numeric expresSion by which the
ar - Is a literal
divisor
Result: 2
mysql>SELECT MOD (11, 3);
Eorexample, () Result: 1.5
(ii) mysql>SELECTMOD (10.5, 3);
argument
returns the squareroot value of the specified
numeric

SORTO: The SQRT(O function of the SQRT) function


be a positive number. The following is the syntax
Theargument must
Syntax: SELECT SQRT(value);
Result:8
mysql>SELECT SQRT (64) ;
Forexample, (i) Result: 13
ii) mysql>SELECT SQRT (169);
The return

function returns the absolute value ofthe


specified numeric argument.
(f ABS():The ABS) The following is the syntax
of the ABS) function
the type as the argument.
value is of same

Syntax: SELECT ABS(value);


Result: 12
mysql>SELECT ABS (-12) ;
For example, (1) Result: 234.67
mysql>SELECT ABS (-234.67);
ii)

4.3.2 String (Text) Functions functions


also known as text
values and are
used to deal with
the string type LEFT
These functions
LOWER(), UPPER(), LENGTHO,
are
functions are ASCii(),
library
Ihevarious built-in String etc.
RIGHT(), TRIM), LTRIM(), RTRIM),
value of a character.
(a) ASCII): Returns the ASCIl code

Syntax: SELECT ASCI(Character);

For example, Returns 97


DUAL;
sELECT ASCII ('a') FROM
mysql> Returns 65.
DUAL;
sELECT ASCII ('A') FROM
mysql> Returns 49.
FROM DUAL;
SELECT ASCII ('1')
mysqi> Returns 65.
FROM DUAL;
SELECT ASCII
('ABC')
mysql>
characters 'A to "Z' is 65 to 90
case

The ASCII value for upper 7 1s 97 to 122 and for digits O to the
case
characters 'a to
lower
T h e ASCII value for
57.
ASCIl value is 48 to is dummy talble usei for
uses Dual table which a
then SQL
Note: If no table name is specified, value X.
one-row,
one-column Dummy with a

operations. It is
a
performing
data into lower case.

0LowER)/LCASE):
Converts character strings
LOWER(String);
Or LCASE(String);
Syntax: SELECT

For example, TECHNOLOGY")

mysql> SELECT LOWER ("INFORMATION


Keturns-information technology

Database Query using SOL 4.5


(c)UPPER()/UCASE0: Converts character strings data into upper case,
Syntax: SELECT UPPER(String); Or UCASE(String);
For example,
mysql> sELECT UPPER ('informat ion technology ')
Returns INFORMATION TECHNOLOGY

(d) LENGTH(): Returns the length of the character string. It takes spaces
into account for
calculating the total length of the string passed as an between the cs
Syntax: SELECT LENGTH(String); argument to LENOstrings
to LENGTH)

For example,

mysql> SELECT LENGTH ( 'Information


Returns- 22
Technology ');
(e) REPLACE(): Replaces all
occurrences of the second
(string1) with a third string (string3). string (tring2) in the
first strino
Syntax: SELECT
For example,
REPLACE('String1',String2, String3);
mysql> SELECT
REPLACE('INFORMATION TECHNOLOGY',
Returns LATEST TECHNOLOGY 'INFORMATION', 'LATEST');
Returns NULL if any one of the
arguments is NULL.
(f) LEFTO: Returns leftmost
characters from string, passed as an
a
number of characters
counting from left. argument, with the specified
LEFT() function is used to retrieve
Syntax: SELECT LEFT(String, portions of the string.
For example, integer);
mysql> SELECT LEFT
Returns- INFORM
('INFORMATION TECHNOLOGY', 6);
(8) RIGHTO: Returns rightmost characters
specified number of characters from a
string, passed as an
portions of the string. counting from right. RIGHT() argument, with the
function is used to retrieve
Syntax: SELECT
For example,
RIGHT(String, Integer);
mysql> SELECT RIGHT ('STRING FUNCTION',
Returns - FUNCTION 8);
(h) LTRIMO: Returns a string after
string passed as an removing leading spaces/blanks
argument. from the left side of the
Syntax: SELECT LTRIM(String)
For example,

mysql> SELECT
LTRIM ((
Returns- LIBRARY FUNCTION LIBRARY FUNCTION');

6 Informatics Practices with


Python-XII
spaces/blanks from the right side of the
TRIMO: Returns
string after removing trailing
urns a strin

argumeni ent.
as an
passed
string
S y n t a x :S E L E C T R T R I M ( S t r i n g ) ;

F o re x a m p l e ,

FUNCTION
RTRIM("LIBRARY

mysql>
SELE
Returns-LIBRARYFUNCTION

all the
as an argument after removing
functions return the string passed
RIM) and RTRIM()
in between the strings.
CTM L Buttthey do not delete the spaces
spaces.

and trailing trailing spaces


from a string passed
the leading and
leading

after removing
Returns a string
TRIMO:
argument
to it.
as the
Syntax: SELECT TRIM(String);

For example, LIBRARY FUNCTION ')


SELECT
TRIM ('
mysql>
Returns LIBRARY FUNCTION

Returns
reverse of an inputted string.
REVERSE():
k) Syntax: SELECT REVERSE(String);

FUNCTION');
('LIBRARY
REVERSE
SELECT
mysql>
Returns NOITCNUF YRARBIL
number of times.
specified
string for
a
an inputted
REPEAT(O: Repeats
() REPEAT(String,
Integer);
SELECT
Syntax: 3);
('FUNCTION',
REPEAT
sELECT
Returns
mysql> FUNCTIONFUNCTIONFUNCTION SUBSTRING)
A
of inputted string.
an character
Returns part specified
at the
string starting
SUBSTRINGO/MIDO/SUBSTR):

(m) of the given


a portion (length).
retrieves
characters
specified
function
n u m b e r of
to the Length);
(start_index)
S U B S T R I N G ( S t r i n g ,
Startindex,
SELECT
Syntax:

OR Length);
Start_index,
SUBSTR(String,

SELECT

OR Length);
Start_index,

MID(String, FUNCTION',
1, 6);
SELECT
SUBSTRING('STRING

sELECT
mysql>
Returns -STRING FUNCTION',
8, 8);
('STRING
SUBSTR
SELECT

mysql>
Returns - FUNCTION

FUNCTION',
3,4);
('STRING
MID
SELECT

mysql>
Returns- RING

SQL 4.7
Database Query using
of the substrino
INSTRO: Returns the position of the first occurrence
in
(n) the
Returns 0 if the substring is not present in the string giVen
string
Syntax: SELECT INSTR(String, Substring);
mysql> Informa ")
Returns- 6

(o) CONCAT): Returns the string that results from concatenating the
arguments, M.
or more arguments. Returns NULL if any argument is NULL. May have tte
yntax: SELECT CONCAT(String1, String2, String3...String n);
mysql> CTI actices', "Class-XII');
Returns- InformaticsPracticesClass-XII

4.3.3 Date and Time Functions NOTE:- NKITE ALL THE


(a)
CURDATE): Returns the current system UNCTIo IVEN BELow
date. WITH ExAmPLE
For example,
mysql> CELECT CUPDATE ();
Result: '2021-02-03
(b) NOWO: Returns the current date and
time.
For example,
mysql> ELECT NOW (); Result: '2021-02-03 13:58:11'
(c) SYSDATEO: Returns the time at which the function
For example, executes.

mysql> SELECT SYSDATE ()


Result: '2021-02-03 13:59:23
(d) DATE): Extracts the date part of a date
For example,
or date-time expression.
mysql> SELECT DATE ('2021-02-03
01:02:03'); Result: '2021-02-03'
(e)
MONTHO: Returns the month from
the date
For example, passed.
mysql> CELECT MONTH
('2021-02-03' ) Result: 2
(f) YEAR): Returns the year from
the
For example, inputted date.
mysql> r.

(g) YEAR('2021-02-03');
DAYNAME(): Returns the name of the Result: 2021
For example, weekday.
mysql>E AZ11AME ('2021-02-0
(h)
DAYOFMONTHO: Returns the day of the month Result: Wednesday
For example, (0-31).
mysql>E
()
MONTHNAMEQ: AFMITE(2021-02-0'
Returns the name of
the
); Result: 3
For example, month (January, February..-)
mysql> SELECT
MONTHNEME ('2021-02- Result: February
4.8 Informatics Practices with
Python-XII
Returns the weekday index of the argument.
DAYOFWEEK():

For example,
mysql> SELECT D A Y O F W E E K ( ' 2 0 2 1 - 0 2 - 0 3 ) Result: 4 (Sunday is counted as 1)

Returns the day of the year (1-366).


D A Y O F Y E A

(k)
For example, Result: 34
SELECT
DAYOFYEAR ("2021-02-03');
mysql>

You might also like