Introduction
In this tutorial, I shall explain some important functions in MySQL. And, I think every developer and DBA should have an understanding of these MySQL Functions. These functions are very useful for MySQL users. And, knowing these MySQL functions can help to solve some complex tasks and be used in many situations.
The functions allow us to improve the functionality of MySQL. Functions also return a value when applying on a dataset and accept the parameters as an option. MySQL always comes with some built-in functions. They can be classified depending on the usage and datatypes, i.e. Strings, Comparison, Aggregate, DateTime, and Numeric built-in functions.
This tutorial will show you various MySQL Functions including String, Aggregate, Maths, DateTime, and Comparison Functions. This detailed article will cover the following topics as follows.
- Introduction to MySQL Functions
- MySQL String Functions
- MySQL Date Functions
- MySQL Aggregate Functions
- MySQL Comparison Functions
- MySQL Maths Functions
- Conclusion
First, let's create a database with a few tables containing some dummy data. Here, I am providing the database with the tables containing the records, on which I am showing you the various examples. Let's see.
- CREATE DATABASE MySQLFunctions;
- USE MySQLFunctions;
-
- CREATE TABLE StudentDetails (
- StudentNumber INT NOT NULL,
- StudentName VARCHAR(50) NOT NULL,
- contactLastName VARCHAR(50) NOT NULL,
- contactFirstName VARCHAR(50) NOT NULL,
- contactnumber VARCHAR(50) NOT NULL,
- addressLine1 VARCHAR(250) NOT NULL,
- addressLine2 VARCHAR(250) DEFAULT NULL,
- city VARCHAR(50) NOT NULL,
- state VARCHAR(50) DEFAULT NULL,
- postalCode VARCHAR(15) DEFAULT NULL,
- country VARCHAR(50) NOT NULL,
- PRIMARY KEY (StudentNumber)
- );
-
- CREATE TABLE Library (
- BookNumber INT NOT NULL,
- BookCode VARCHAR(15) NOT NULL,
- BookIssue INT NOT NULL,
- CostEach DECIMAL(10,2) NOT NULL,
- PRIMARY KEY (BookCode)
- );
-
- CREATE TABLE Bookorder (
- BookNumber INT NOT NULL,
- orderDate datetime NOT NULL,
- shippedDate DATE DEFAULT NULL,
- Status VARCHAR(50),
- OrderModifiedDate datetime,
- PRIMARY KEY (BookNumber)
- );
A) MySQL String Functions
MySQL String Functions are used to handle the character string data very efficiently. Some of the String Functions are ASCII, CONCAT, INSTR, LENGHT, LTRIM, RTRIM, LEFT, RIGHT, LOWER, UPPER, SUBSTRING. Without wasting time, let's see some common string functions with examples.
ASCII
This function returns the ASCII code value of the leftmost character of the String “str” but returns 0 if the “str” is the empty string. And, it returns NULL if “str” is NULL.
Syntax
ASCII (String);
Example
- SELECT ASCII('0'),
- ASCII('A'),
- ASCII('a'),
- ASCII('Onkar'),
- ASCII(''),
- ASCII(NULL);
CONCAT
The MySQL, CONCAT function takes and concatenates one or more array arguments into a single array or string. The CONCAT function needs one parameter, otherwise, it will cause an error.
Syntax
CONCAT(string1, string2, ...);
Example 1
- SELECT CONCAT('In', 'd', 'ia') AS Name,
- CONCAT('V', 'A', 'T', 'S', 'A') as Name,
- CONCAT('my', NULL, 'ql') as Name,
- CONCAT(10, 3) as String;
Example 2
- SELECT CONCAT(contactfirstname, ' ', contactlastname) AS StudentFUllName,
- CONCAT(addressLine1, ' ', addressLine2) AS CompleteAddress
- FROM StudentDetails;
INSTR
The MySQL, INSTR function is used to get the position of the first character of a substring "substr" in the main string "str". If the "substr" is not found in the main string "str", the MySQL INSTR function will return the zero value.
Syntax
INSTR(str, substr);
Example 1
- SELECT INSTR('VATSA', 'A'),
- INSTR('VATSA', 'O'),
- INSTR('VATSA', NULL);
Example 2
- SELECT StudentName, addressLine1
- FROM StudentDetails
- WHERE INSTR(addressline1,'Vatsa Colony');
LTRIM
In MySQL, the LTRIM function is used to take a string and return an updated string with all the leading space characters deleted from the main string.
Syntax
LTRIM(str);
Example
- SELECT LTRIM(' helloindia') AS String,
- LTRIM(' VATSA ') AS String,
- LTRIM('H E L L O ! V A T S A...') AS String;
RTRIM
In MySQL, the RTRIM function is used to take a string and return an updated string with all the trailing space characters deleted from the main string.
Syntax
RTRIM(str);
Example
- SELECT RTRIM(' Hello!Vatsa '),
- RTRIM('Hello! Vatsa '),
- RTRIM(' B S R ');
LOWER
In MySQL, the LOWER(string) function is used to return the string in the form of lowercase.
Syntax
LOWER(string);
Example
- SELECT LOWER('HELLO!INDIA...'),
- LOWER('VATSA'),
- LOWER('Hello!Vatsa...');
UPPER
In MySQL, the UPPER() function is used to return the uppercase value of the string.
Syntax
UPPER(string);
Example
- SELECT UPPER('helloIndia'),
- UPPER('vatsa'),
- UPPER('Hello! Vatsa...');
SUBSTRING
In MySQL, the function SUBSTRING(string, position) or SUBSTRING(string FROM position) returns a substring from the main string that is started at a certain position, i.e, positive or negative index. Let's understand the concept of a position in a string with the help of the following below figure.
Syntax
SUBSTRING(string, position);
SUBSTRING(string FROM position);
Example
- SELECT SUBSTRING('Hello Vatsa', 7) AS Result,
- SUBSTRING('Hello Vatas', -6) AS Result,
- SUBSTRING('Hello India' FROM 7) AS Result,
- SUBSTRING('Hello India' FROM 7) AS Result,
- SUBSTRING('Hello India', 1, 5) AS Result,
- SUBSTRING('Hello Vatsa', -5, 5) AS Result;
FORMAT
In MySQL, the FORMAT(N, D) function describes that the number "N" is rounded to the decimal places to "D" then, returns the string as a result. But, if the value of D is 0 then, the results don’t have a fractional part.
Syntax
FORMAT(N, D);
Example 1
- SELECT FORMAT(1235.14687, 5) AS FormatResult,
- FORMAT(1235.14687, 4) AS FormatResult,
- FORMAT(1235.14687, 3) AS FormatResult,
- FORMAT(1235.14687, 2) AS FormatResult,
- FORMAT(1235.14687, 1) AS FormatResult,
- FORMAT(1235.14687, 0) AS FormatResult;
Example 2
- SELECT BookNumber, FORMAT(BookIssue * costeach, 2) AS TotalCost
- FROM Library;
B) MySQL Date Functions
In MySQL, the Date Function is used to handle Date and Time very efficiently. Some of the Date Functions are CURDATE, DATEDIFF, NOW, DAYNAME, DAYOFWEEK, MONTH, YEAR. Let's discuss some commonly used Date and Time Functions one by one.
CURDATE
In MySQL, CURDATE function is used to get the current date in the format of "YYYY-MM-DD". This means, it only returns the date. Note that, you can use CURRENT_DATE() or CURRENT_DATE in place of CURDATE(), as they are synonyms of CURDATE() function.
Syntax
CURDATE();
Example
- SELECT CURDATE(),
- CURRENT_DATE,
- CURRENT_DATE();
DATEDIFF
In MySQL, the DATEDIFF function is used to get the difference between two dates or DateTime. This means it is used to calculate the difference between two dates.
Syntax
DATEDIFF(date1, date2);
Example 1
- SELECT DATEDIFF('2020-10-31','2020-10-03') AS Days_Left_To_Complete_this_Month,
- DATEDIFF('2020-11-30','2020-10-03') AS Days_Left_To_Complete_next_Month;
Example 2
- SELECT BookNumber, DATEDIFF(shippeddate, orderdate) AS Time_taken_To_Delivered_the_Book
- FROM BookOrder;
NOW
In MySQL, the NOW() function is used to get the current date and time as a string or a number in the "YYYY-MM-DD HH:MM:SS" format. This means it returns the current date and time in the configured time zone.
Syntax
NOW();
Example
DAYNAME
In MySQL, DAYNAME function is used to return the day on a particular date.
Syntax
DAYNAME(date);
Example 1
- SELECT DAYNAME("2020-10-03") AS Day,
- DAYNAME("2020-10-12") AS Day,
- DAYNAME("1997-01-01") AS Day,
- DAYNAME("1999-01-01") AS Day,
- DAYNAME("2020-11-01") AS Day;
Example 2
- SELECT BookNumber, dayname(shippeddate) AS Delivered_on_Day
- FROM BookOrder;
MONTH
MONTH function is used to return an integer value from a particular date which represents the month for the particular date.
Syntax
MONTH(date);
Example
- SELECT MONTH("2020-10-03"),
- MONTH(NOW()),
- MONTH("2020-11-03");
C) MySQL Aggregate Functions
In MySQL, Aggregate Functions are used to perform a calculation on a set of values in a table and will give a single value to the user. Aggregate functions do not handle NULL values. Aggregate Function performs the operations on a set of values. Some of the Aggregate Functions are SUM, AVG, COUNT, MAX, and MIN.
The user can use aggregate functions with the GROUP BY clause to fetch the data into groups. But, without a GROUP BY clause, the aggregate function gives the result into the summary form. And, with the GROUP BY clause, an aggregate function will give the result in the summary form based on the group. Without wasting time, let's discuss the most common examples of aggregate functions.
Syntax
Function_Name (DISTINCT | ALL Expresion)
MAX() Function
In MySQL, the MAX function is used to get the maximum value in a column from a table.
Syntax
SELECT MAX <Column_name>
FROM <table_name>;
Example
- SELECT MAX(Bookissue) AS MaxBookIssued
- FROM library;
Note:
You can use MAX() aggregate function with the "GROUP BY" clause to get the result in a group form.
Syntax
SELECT col_name, MAX(col_name)
FROM <table_name>
GROUP BY col_name;
Example
- SELECT BookNumber, MAX(Bookissue) AS MaxBookIssued
- FROM library
- GROUP BY BookNumber;
MIN() Function
MIN function returns the minimum value from a table.
Syntax
SELECT MIN(Column_name)
FROM <table_name>;
Example
- SELECT MIN(Bookissue) AS MinBookIssued
- FROM library;
Note:
You can use MIN() aggregate function with the "GROUP BY" clause to get the result in a group form.
Syntax
SELECT col_name, MIN(col_name)
FROM <table_name>
GROUP BY col_name;
Example
- SELECT BookNumber, MIN(Bookissue) AS MinBookIssued
- FROM library
- GROUP BY BookNumber;
AVG() Function
AVG() function is used to calculate the average value and it also ignores the NULL value.
Syntax
SELECT AVG(Column_name)
FROM <table_name>;
Example
- SELECT AVG(BookIssue*CostEach) AS AverageCosta
- FROM library;
Note:
You can use AVG() aggregate function with the "GROUP BY" clause to get the result in a group form.
Syntax
SELECT col_name, AVG(col_name)
FROM <table_name>
GROUP BY col_name;
Example
- SELECT BookNumber, AVG(BookIssue*CostEach) AS AverageCost
- FROM library
- GROUP BY BookNumber;
SUM() Function
SUM function returns the sum of all values in an expression. And, the SUM() functions ignore NULL values.
Syntax
SELECT SUM(Column_name)
FROM <table_name>;
Example
- SELECT SUM(BookIssue*CostEach) AS TotalCost
- FROM library;
Note:
You can use the SUM() aggregate function with the "GROUP BY" clause to get the result in a group form.
Syntax
SELECT col_name, SUM(col_name)
FROM <table_name>
GROUP BY col_name;
Example
- SELECT SUM(BookIssue*CostEach) AS TotalCost
- FROM library;
For more details, read the following articles in which, I have described "Aggregate Functions" in detail in the article on the topic, "
MySQL Aggregate Functions".
D) MySQL Comparison Functions
Some of the MySQL Comparison Functions are COALESCE, GREATEST & LEAST, ISNULL. Let's discuss them, one by one.
GREATEST & LEAST
This function is used to find out the greatest and smallest value from two or more fields respectively.
Syntax
For Greatest
GREATEST(value1, value2, value3, ...);
For Least
LEAST(value1, value2, value3, ...);
Note:
1) Both the functions return "NULL" if they having any "NULL" value in them.
2) If arguments contain the integer values and string values, then it compares them as numbers.
Example
- SELECT GREATEST(80, 90, 100),
- LEAST(100, 90, 80),
- GREATEST(555, null, 101),
- LEAST(101, null , 988);
ISNULL
In MYSQL, ISNULL function is used in queries to test whether the argument is true or not. It takes one argument and returns 1 if the argument is NULL, or if the argument is not NULL, then it will return 0 value.
Syntax
ISNULL(expression);
Example
- SELECT ISNULL(1),
- ISNULL('Yes'),
- ISNULL('Vatsa'),
- ISNULL(100 + NULL),
- ISNULL(NULL);
E) MySQL Maths Functions
Some of the MySQL Maths Functions in MySQL are CEIL(), FLOOR(), MOD(), ROUND(), TRUNCATE(), PI(), POW(). Let's discuss the most commonly used maths functions, one by one.
CEIL()
In MySQL, CEIL() or CEILING() function is used to return the smallest integer value which is greater than or equal to that number.
Syntax
CEIL() or CEILING();
Example 1
- SELECT CEIL(1.55),
- CEIL(1.56),
- CEIL(1.54),
- CEIL(1.01),
- CEIL(10.21),
- CEIL(100.01);
Example 2
- SELECT BookCode, CEILING(BookISsue * CostEach) AS TotalCost
- FROM Library;
FLOOR()
In MySQL, the FLOOR() function is used to return the largest integer value which is smaller than or equal to that number.
Syntax
FLOOR();
Example 1
- SELECT FLOOR(10.50),
- FLOOR(2000.50),
- FLOOR(-10.20),
- FLOOR(10.98),
- FLOOR(2201.11);
Example 2
- SELECT BookCode, FLOOR(BookISsue * CostEach) AS TotalCost
- FROM Library;
ROUND()
In MySQL, the ROUND() function is used to round a number to the mentioned number of decimal places.
Syntax
ROUND(n, [d]);
Example
- SELECT ROUND(10.49),
- ROUND(10.50),
- ROUND(10.51),
- ROUND(-10.5),
- ROUND(10.01);
Conclusion
In this article, we have discussed various MySQL Functions in detail with various examples.
I hope you enjoyed this article. Follow C# Corner to learn more new and amazing things about MySQL.
Thanks for reading.