You are on page 1of 28

MySQL Functions

•Definition:
• A function is a special types
of command that performs
some operation and returns a
single value as a result.
• Functions operate on zero,
one , two or more values
provided to them .
(parameters or arguments)
Working with • All the functions
are categorized into
Functions following two types

• The difference is number of


rows they act upon
 Scalar or single row Functions:
 String Functions
 Numeric Functions
 Date & Time Function
Multi row or aggregate functions
 Count()
 Min()
 Max()
 Sum()
 AVG()
This function returns the character for each integer passed.
Syntax:
char(value1 [, value2…])
For version 8.x use SELECT CHAR(65 USING utf8mb4);
Example:
write a query to create a string from the ASCII values 70, 65,
67, 69
CHAR() Select char(70, 65, 67, 69);
Output: FACE
Ascii Values
• Upper case A- 65
• Lower case a-97
• Number 0- 48
This function concatenates two strings.
Syntax:
concat (string1, string2, …)

CONCAT Example:
1. Select concat(“CHIREC”, “SCHOOL”)
2. Select concat(fname, lname) as name from
students;
This function converts a string into lowercase

Syntax: Lower(str);
LOWER/ Lcase(str);
LCASE Example:
select lower(“Rahul”);
select lcase(“RamyA”);
This function converts a string into Uppercase

Syntax: upper(str);
UPPER/ ucase(str);
UCASE Example:
select upper(“Ramya”);
select ucase(“rahul”);
This function extracts
a substring from a
given string

substr(str, m [, n])
substr(str from m [for n])
Returns a portion of str, beginning at character m,n
characters long
SUBSTR 1. If m is positive, MySQL counts from the beginning of
the string to find the first character
2. If m is negative, MySQL counts backwards from the end
of string .
3. If m is 0, it is treated as 1
4. If n is omitted, MySQL returns all characters to the end
of string .
5. If n is less than 1, a null is returned
• SELECT SUBSTRING('MySQL
SUBSTRING',1,5); result : MySQL
• SELECT SUBSTRING('MYSQL
SUBSTRING',7); result : SUBSTRING
• SELECT SUBSTRING('MYSQL SUBSTRING',
Examples 0); result : empty string
• SELECT SUBSTRING('MySQL SUBSTRING',-
15,5); result: MYSQL
• SELECT SUBSTRING('MySQL SUBSTRING',-
10); result : SUBSTRING
• SELECT SUBSTRING('MYSQL SUBSTRING',
3,-1); result: empty string (null) because n is -1
• This function removes leading spaces ie., spaces from
the left of given string.
Syntax:
LTRIM (str);
Example:
Select ltrim(‘ abcdef rdbms Mysql ‘)
LTRIM
• This function removes trailing spaces
i.e., spaces from the right of the given
string.
Syntax:
RTRIM RTRIM (str);
Example:
Select rtrim(‘ abcdef rdbms
Mysql ‘)
• This function removes leading and trailing spaces from the string.
Syntax: TRIM([{BOTH | LEADING | TRAILING} [remstr]
FROM] str)
Returns a string str with all remstr prefixes or suffixed removed
Example:
• Select trim(‘ abcdef rdbms Mysql ‘)
• Select trim (leading ‘a ‘ from ‘ abcdef ‘);

TRIM • Select trim (‘a ‘ from ‘ abcdef ‘);


• SELECT TRIM(BOTH '123' FROM '123Tech123');Result: 'Tech'
• SELECT TRIM(LEADING '0' FROM '0001230'); Result: '1230'
• SELECT TRIM(TRAILING '0' FROM '0001230'); Result: '000123'
• SELECT TRIM('w' FROM ' welcomechirecw
‘);Result:elcomechirec // trims w
• SELECT TRIM(' welcomechirec '); Result:welcomechirec // trims
space
• Select trim(leading 'a' from ename) from student
INSTR
• This function searches for given second string into the given first string.
Syntax:
INSTR (str1, str2)
returns an integer which indicates the position of the first occurrence of the
substring within the string
Example:
Select instr(‘CORPORATE FLOOR‘, ‘OR’) as Instring
Select job, instr(job, ‘LE’) as “LE in Job” from emp;
Note : If the sub sting is not present, then It will return 0
• This function returns the length of a given
string in bytes
Syntax:
LENGTH (str)
Example:
1. Select LENGTH(‘CORPORATE
LENGTH FLOOR‘) as “No. of characters”;

2. Select job, length(ename) from emp where


empno=8900;
LEFT
• This function returns the leftmost number of
characters as specified.
Syntax:
LEFT (str, len)
Example:
Select LEFT(‘CORPORATE FLOOR‘, 3);
• Display random code which is the combination of 3 chars of ename in
uppercase followed by length of the name and last two chars of dob
• This function returns the leftmost number of
RIGHT characters as specified.
Syntax:
RIGHT (str, len)
Example:
Select RIGHT(‘CORPORATE FLOOR‘, 3);
• This function returns a substring stating from
the specified position. This is same as substr
function.
Syntax:
MID (str, pos, len)
MID Example:
Select MID(‘CORPORATE FLOOR‘, 3, 4);
Select substr(‘CORPORATE FLOOR‘, 3, 4);
SUBSTRING( string, start_position, [ length ] )
The position for extraction. The first position in the string is
always 1.
Optional. It is the number of characters to extract. If this
parameter is omitted, the SUBSTRING function will return the
entire remaining string.
If start_position is a negative number, then the SUBSTRING
function starts from the end of the string and counts backwards.
Select substring(“welcome”,-6,5) --- elcom
String Functions
MySQL string functions can manipulate the strings
Numeric Functions
 These functions may accept some numeric values and performing
required operation, returns numeric values as result.

Name Purpose Example


MOD (M, N) Returns remainder of M divide by N Select MOD(11,4) ;
3
POWER (M, N) POW Returns MN Select POWER(3,2);
(M, N) 9
ROUND (N [,M]) Returns a number rounded off up to M Select ROUND(15.193,1);
place. If M is -1, it rounds nearest 10. 15.2

SIGN (N) Returns sign of N. Select SIGN(-15);


-1 if N<0,  -1
1 if N>0 and 0 if N=0
SQRT (N) Returns square root of N Select SQRT(25);  5

TRUNCATE(N,M) Returns number after truncating M Select TRUNCATE(15.79,1)


decimal place.  15.7
• Round function(n[,m]): Returns value of argument n rounded to m places
right of the decimal point. M can be negative to round off digits left of the
decimal point.
SELECT ROUND(1.23456789123456789, 8) ; Result:1.23456789
SELECT ROUND(125.315); Result: 125
SELECT ROUND(125.315, 0); Result: 125
SELECT ROUND(125.315, 1); Result: 125.3
select round(125.355,1);Result 125.4
SELECT ROUND(125.315, 2); Result: 125.32
SELECT ROUND(125.315, -1); Result: 130
SELECT ROUND(125.315, -2); Result: 100
SELECT ROUND(125.315, -3); Result: 0
SELECT ROUND(-125.315); Result: -125
• Truncate : returns a number with some digits truncated
• Syntax: truncate(n, m)
• Returns a value of argument n truncated to argument m decimal places
• If m is given as 0 places removes all values from the right of decimal place.
• If m is negative , truncates m digits left of the decimal point.
Date & Time Functions
Name Purpose Example
CURDATE() | Returns the current date Select CURDATE();
CURRENT_DATE()  2010-10-02

SYSDATE() Returns the current date & Time as YYYY- Select NOW();
MM-DD HH:MM:SS  2010-10-02 11:30:02
SYSDATE() Returns the current date & Time as YYYY- Select SYSDATE();
MM-DD HH:MM:SS  2010-10-02 11:30:10
DATE() Returns the date part of a date time Select DATE(SYSDATE());
expression.  2010-10-02
MONTH() / Returns the Month/Year from given date Select MONTH(CURDATE());
YEAR() argument.  10

DAYNAME() Returns the name of the weekday Select DAYNAME(CURDATE());


 SUNDAY
DAYOFMONTH() Returns the day of month (1-31). Select DAYOFMONTH(CURDATE());

DAYOFWEEK() Returns the day of week (1-7). Select DAYOFWEEK(CURDATE());

DAYOFYEAR() Returns the day of year(1-366). Select DAYOFYEAR(CURDATE());


count()
• The COUNT() function is an aggregate function that returns the number of
rows in a table.
• The COUNT() function has three forms: COUNT(*), COUNT(col_name) and
COUNT(DISTINCT col_name).
Demo table( id and val)
Implementing Foreign Key Constraints
 A Foreign key is non-key column in a table whose value is derived from
Primary key of some other table.
 Each time when record is inserted/updated the other table is referenced. This
constraints is also called Referential Integrity Constraints.
 This constraints requires two tables in which Reference table
(having Primary key) called Parent table and table having Foreign key is
called Child table.

EMPLOYEE DEPARTMENT Primary


EmpID DeptNo key
Name City DeptName
Foreign
Sal DeptNo Head Location
Key

Parent Table
Child Table
Implementing Foreign Key Cont..
Parent table
CREATE TABLE Department should be
created
( DeptNo char(2) NOT NULL PRIMARY KEY,
first.
DeptName char(10) NOT NULL, Head
char(30) );

CREATE TABLE Employee Foreign key as


( EmpNo char(3) NOT NULL PRIMARY KEY, table level
Name char(30) NOT NULL, constraints…
City char(20), written after all
Sal decimal(8,2), columns.
DeptNo char(2),
FOREGIN KEY (DeptNo) REFERENCES Departmet (DeptNo));

Alternatively, it can applied in front of column itself… without using


Foreign Key keyword.

DeptNo char(2) REFERENCES Departmet (DeptNo),


Implementing Foreign Key Cont..
 Other options with FOREIGN KEY
 What will happen, when a primary key value is deleted or updated in parent table, which
is being referred in child table?
 We can set the following options with FOREIGN KEY
ON DELETE CASCADE / RESTRICT/ SET NULL/ NO ACTION ON UPDATE CASCADE / RESTRICT/ SET NULL/
NO ACTION
 CASCADE:
The values of Foreign key in child table, will be updated or referenced record will be deleted
automatically.
 RESTRICT:
This option will reject any Delete or Update operation on Primary key of Parent table.
 SET NULL:
This option will set NULL value in referenced records of Foreign key in child table.
 NO ACTION:
No any action will be taken when any Delete/Update operation is carried in Primary key of Parent table.

CREATE TABLE Employee ( ……….,


FOREIGN KEY DeptNo REFERENCE Department (DeptNo) ON DELETE CASCADE
ON UPDATE CASCADE );

You might also like