0% found this document useful (0 votes)
3 views44 pages

Functions

The document provides an overview of advanced SQL functions, including numeric, string, and date functions, along with examples of their syntax and output. It also covers handling NULL values with IFNULL and COALESCE functions, as well as control flow with the IF function and the CASE operator. Each function is explained with its purpose, syntax, and example outputs to illustrate their use in SQL queries.

Uploaded by

Toni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views44 pages

Functions

The document provides an overview of advanced SQL functions, including numeric, string, and date functions, along with examples of their syntax and output. It also covers handling NULL values with IFNULL and COALESCE functions, as well as control flow with the IF function and the CASE operator. Each function is explained with its purpose, syntax, and example outputs to illustrate their use in SQL queries.

Uploaded by

Toni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Advance Database Systems

Functions

Prepared By: Viñas, Murillo And Montederamos


Advanced SQL
Functions
Numeric Functions
Are used to perform operations on numbers and return
numbers.
ABS(): It returns the absolute value of a number.
Syntax: SELECT ABS(-243.5); Output: 243.5

ACOS(): It returns the cosine of a number, in radians.


Syntax: SELECT ACOS(0.25); Output: 1.318116071652818

ASIN(): It returns the arc sine of a number, in radians.


Syntax: SELECT ASIN(0.25); Output: 0.25268025514207865

ATAN(): It returns the arc tangent of a number, in radians.


Syntax: SELECT ATAN(2.5); Output: 1.1902899496825317

CEIL(): It returns the smallest integer value that is greater than or equal to a number.

Syntax: SELECT CEIL(25.75); Output: 26


CEILING(): It returns the smallest integer value that is greater than or equal to a number.

Syntax: SELECT CEILING(25.75); Output: 26


COS(): It returns the cosine of a number, in radians.

Syntax: SELECT COS(30); Output: 0.15425144988758405


COT(): It returns the cotangent of a number, in radians.
Syntax: SELECT COT(6); Output: -3.436353004180128

DEGREES(): It converts a radian value into degrees.

Syntax: SELECT DEGREES(1.5); Output: 85.94366926962348


DIV(): It is used for integer division.
Syntax: SELECT 10 DIV 5; Output: 2
EXP(): It returns e raised to the power of a number.
Syntax: SELECT EXP(1); Output: 2.718281828459045

FLOOR(): It returns the largest integer value that is less than or equal to a number.

Syntax: SELECT FLOOR(25.75); Output: 25


GREATEST(): It returns the greatest value in a list of expressions.
Syntax: SELECT GREATEST(30, 2, 36, 81, 125); Output: 125

LEAST(): It returns the smallest value in a list of expressions.

Syntax: SELECT LEAST(30, 2, 36, 81, 125); Output: 2


LN(): It returns the natural logarithm of a number.

Syntax: SELECT LN(2); Output: 0.6931471805599453


LOG10(): It returns the base-10 logarithm of a number.

Syntax: SELECT LOG(2); Output: 0.6931471805599453


LOG2(): It returns the base-2 logarithm of a number.

Syntax: SELECT LOG2(2); Output: 1

MOD(): It returns the remainder (aka. modulus) of n divided by m.


Syntax: SELECT MOD(18, 4); Output: 2
PI(): It returns the value of Pi and displays 6 decimal places.
Syntax: SELECT PI(); Output: 3.141593
POWER(m, n): It returns m raised to the nth power.
Syntax: SELECT POWER(4, 2); Output: 16

RADIANS(): It converts a value in degrees to radians.


Syntax: SELECT RADIANS(180); Output: 3.141592653589793

RAND(): It returns a random number between 0 (inclusive) and 1 (exclusive).

Syntax: SELECT LOG(2); Output: 0.33623238684258644

ROUND(): It returns a number rounded to a certain number of decimal places.

Syntax: SELECT ROUND(5.553); Output: 6


SIN(): It returns the sine of a number in radians.

Syntax: SELECT SIN(2); Output: 0.9092974268256817


SQRT(): It returns the square root of a number.

Syntax: SELECT SQRT(25); Output: 5

TAN(): It returns the tangent of a number in radians.

Syntax: SELECT TAN(1.75); Output: -5.52037992250933

ATAN2(): It returns the arctangent of the x and y coordinates, as an angle and expressed in
radians.

Syntax: SELECT ATAN2(7); Output: 1.42889927219073

TRUNCATE(): used to truncate a number to a specified number of decimal places.

Syntax: TRUNCATE(number, decimals); Output: 7.53


SQL | String functions
String functions are used to perform an operation on input
string and return an output string. Following are the string
functions defined in SQL:
ASCII()
This function is used to find the ASCII value of a character.

Syntax: SELECT ascii('t');


Output: 116

CONCAT() This function is used to add two words or strings.

Syntax: SELECT 'Geeks' || ' ' || 'forGeeks' FROM dual;


Output: ‘Geeks forGeeks’

FIND_IN_SET() This function is used to find a symbol from a set of symbols.

Syntax: SELECT FIND_IN_SET('b', 'a, b, c, d, e, f');


Output: 2
FORMAT() This function is used to display a number in the given format.

Syntax: Format("0.981", "Percent");


Output: ‘98.10%’

INSERT() This function is used to insert the data into a database.

Syntax: INSERT INTO database (geek_id, geek_name)


VALUES (5000, 'abc');
Output: successfully updated

LCASE() This function is used to convert the given string into lower case.

Syntax: LCASE ("GeeksFor Geeks To Learn");


Output: geeksforgeeks to learn
LEFT() This function is used to SELECT a sub string from the left of given size or characters.

Syntax: SELECT LEFT('geeksforgeeks.org', 5);


Output: geeks

LENGTH() This function is used to find the length of a word.

Syntax: LENGTH('GeeksForGeeks');

Output: 13

LPAD() This function is used to make the given string of the given size by adding the given
symbol.
Syntax: LPAD('geeks', 8, '0');
Output: 000geeks
LTRIM() This function is used to cut the given sub string from the original string.

Syntax: LTRIM('123123geeks', '123');


Output: geeks

MID() This function is used to find a word from the given position and of the given
size.
Syntax: Mid ("geeksforgeeks", 6, 2);

Output: for

POSITION() This function is used to find position of the first occurrence of the given alphabet.

Syntax: SELECT POSITION('e' IN 'geeksforgeeks');


Output: 2
REPEAT() This function is used to write the given string again and again till the number of times
mentioned.
Syntax: SELECT REPEAT('geeks', 2);
Output: geeksgeeks

REPLACE() This function is used to cut the given string by removing the given sub string.
Syntax: REPLACE('123geeks123', '123');

Output: geeks

REVERSE() This function is used to reverse a string.

Syntax: SELECT REVERSE('geeksforgeeks.org');


Output: ‘gro.skeegrofskeeg’
RIGHT() This function is used to SELECT a sub string from the right end of the given size.

Syntax: SELECT RIGHT('geeksforgeeks.org', 4);


Output: ‘.org’

RPAD() This function is used to make the given string as long as the given size by
adding the given symbol on the right.
Syntax: RPAD('geeks', 8, '0');

Output: ‘geeks000’

RTRIM() This function is used to cut the given sub string from the original string.

Syntax: RTRIM('geeksxyxzyyy', 'xyz');


Output: ‘geeks’
SPACE() This function is used to write the given number of spaces.

Syntax: SELECT SPACE(7);


Output: ‘ ‘

RPAD() This function is used to make the given string as long as the given size by
adding the given symbol on the right.
Syntax: RPAD('geeks', 8, '0');

Output: ‘geeks000’

TRIM() This function is used to cut the given symbol from the string.

Syntax: TRIM(LEADING '0' FROM '000123');


Output: 123
STRCMP() This function is used to compare 2 strings.

If string1 and string2 are the same, the STRCMP


function will return 0.
If string1 is smaller than string2, the STRCMP
function will return -1.
If string1 is larger than string2, the STRCMP
function will return 1.

Syntax: SELECT STRCMP('google.com', 'geeksforgeeks.com');


Output: -1

SUBSTR() This function is used to find a sub string from the a string from the given position.

Syntax: SUBSTR('geeksforgeeks', 1, 5);


Output: ‘geeks’
SUBSTRING() This function is used to find an alphabet from the mentioned size and the given
string.

Syntax: SELECT SUBSTRING('GeeksForGeeks.org', 9, 1);


Output: ‘G’

SUBSTRING_INDEX() This function is used to find a sub string before the given symbol.

Syntax: SELECT SUBSTRING_INDEX('www.geeksforgeeks.or


Output: ‘www’

UCASE() This function is used to make the string in upper case.

Syntax: UCASE ("GeeksForGeeks");


Output: GEEKSFORGEEKS
Date Functions in MySQL
String functions are used to perform an operation on input
string and return an output string. Following are the string
functions defined in SQL:
NOW() Returns the current date and time.

Syntax: SELECT NOW();


Output: 2024-09-17 10:30:45

CURDATE() Returns the current date without the time portion.

Syntax: SELECT CURDATE();


Output: 2024-09-17

CURTIME() Returns the current time.

Syntax: SELECT CURTIME();


Output: 10:30:45
DATE() Extracts the date portion of a datetime or timestamp value.

Syntax: SELECT DATE(NOW());


Output: 2024-09-17

DATE_FORMAT() Formats a date as specified by a format string. Common formats include:


%Y: Year (4 digits)
%m: Month (2 digits)
%d: Day of the month (2 digits)
%H: Hour (00-23)
%i: Minutes (00-59)
%s: Seconds (00-59)

Syntax: SELECT DATE_FORMAT(NOW(), '%W, %M %d, %Y');

Output: Tuesday, September 17, 2024


YEAR(), MONTH(), Extracts the year, month, or day from a date.
DAY()
Syntax: SELECT YEAR(NOW()), MONTH(NOW()), DAY(NOW());

Output: 2024 | 09 | 17

DATEDIFF() Calculates the difference in days between two dates.

Syntax: SELECT DATEDIFF('2024-09-20', '2024-09-17');


Output: 3

TIMESTAMPDIFF() Returns the difference between two timestamps in various units


(e.g., year, month, day, hour, minute, second).

Syntax: SELECT TIMESTAMPDIFF(DAY, '2024-09-01', NOW());


Output: 16
ADDDATE() and Adds or subtracts a specified interval from a date.
SUBDATE()
Syntax: SELECT ADDDATE(NOW(), INTERVAL 7 DAY);
Output: 2024-09-24
Syntax: SELECT SUBDATE(NOW(), INTERVAL 7 DAY);

Output: 2024-09-10

STR_TO_DATE() Converts a string to a date using a format specifier.

Syntax: SELECT STR_TO_DATE('17-09-2024', '%d-%m-%Y');


Output: 2024-09-17

Formatting Date and


Time Together You can format both date and time using DATE_FORMAT().

Syntax: SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s');


Output: 2024-09-17 10:30:45 (formatted current date and time)
Calculating Dates and Times
Calculating Time Intervals
We can use the DATEDIFF function to find the difference between two date-time
values and calculate intervals.

Syntax:
SELECT DATEDIFF(MINUTE, start_time,
end_time) AS duration_minutes
FROM tasks;

The SQL query provided is used to calculate the duration in minutes between two
timestamps, start_time and end_time, for tasks recorded in a tasks table.
The IFNULL and COALESCE
Functions
When working with databases, dealing with missing or unknown data is a common
challenge. In SQL, this is represented by NULL values. Handling NULL values
correctly is crucial for ensuring your data operations are accurate and consistent.

Two key functions that help manage NULL values are COALESCE and IFNULL.
While both functions aim to handle NULL values, they have different features and
uses.
IFNULL()

It is a basic function to determine whether an expression is NULL. The


function returns the replacement_value if the expression is NULL; if not,
it returns the value of the expression.

Syntax:
IFNULL(exp, replacement_value)
COALESCE()

Returns the first non-NULL value from the list of expressions. It is more
flexible as it can handle multiple expressions.

Syntax:
COALESCE(exp1, exp2, …, expN)
Example

Now we created an ‘emplTbl‘ to show the example of IFFNULL and


COALESCE:
Example of IFNULL()
Query:
SELECT
emplTbl empid,
ename,
IFNULL(salary, 0) AS updatedSalary
FROM
emplTbl;

Output:
Example of COALESCE ()
Query:
SELECT
emplTbl empID,
ename,
COALESCE(salary, bonus, 0) AS
updatedSalary
FROM
emplTbl;

Output:
The IF Function
IF( ) Function
The IF() function is a control flow function that returns different values
based on the result of a condition.

The IF() function in MySQL returns a value if the condition is TRUE and
another value if the condition is FALSE. The IF() function can return
values that can be either numeric or strings, depending upon the context
in which the function is used.

The IF() function accepts one parameter, which is the condition to be


evaluated.
Syntax:

IF(condition, true_value, false_value)

Parameters:

condition – It is used to specify the condition to be evaluated.


true_value – It is an optional parameter that is used to specify the
value to be returned if the condition evaluates to be true.
false_value – It is an optional parameter that is used to specify the
value to be returned if the condition evaluates to be false.
Example: Implementing IF() function on a numeric condition and returning a
string value.

products
Query:
SELECT product_id, price,
IF(price > 100, 'Expensive', 'Affordable') AS category
FROM products;

Output:
The CASE Operator
The CASE statement in SQL is a versatile conditional expression that
enables us to incorporate conditional logic directly within our queries. It
is commonly used to generate new columns based on certain conditions
and provide custom values or control the output of our queries.

The CASE statement in SQL is a conditional expression that allows


you to perform conditional logic within a query.
It is commonly used to create new columns based on conditional
logic, provide custom values, or control query outputs based on
certain conditions.
If no condition is true then the ELSE part will be executed. If there is
no ELSE part then it returns NULL.
Syntax:

CASE case_value
WHEN condition THEN result1
WHEN condition THEN result2

Else result
END CASE;
Costumer
Query:
SELECT CustomerName, Age,
CASE
WHEN Country = "India" THEN 'Indian'
ELSE 'Foreign'
END AS Nationality
FROM Customer;

Output:
Reference:
THANK YOU :’>

You might also like