-
Hajipur, Bihar, 844101
In MySQL, functions are built-in operations that let you perform calculations, format data, and manipulate strings, numbers, or dates directly within SQL queries. They help you save time and make queries more powerful by allowing you to process data without needing extra application logic.
This tutorial will explain the main categories of MySQL functions, how they work, and how you can use them in real-world queries.
A function in MySQL is a predefined operation that takes input values (called arguments), performs a specific task, and returns a result.
You can use functions in the SELECT, WHERE, GROUP BY, or ORDER BY clauses to process and format data.
For example:
SELECT UPPER('hello');
Output:
HELLO
Here, UPPER() is a MySQL function that converts text to uppercase.
MySQL offers many built-in functions grouped into categories based on the type of operation they perform:
String Functions
Numeric Functions
Date and Time Functions
Aggregate Functions
Control Flow Functions
System Functions
Let’s go through each type in detail with examples.
String functions are used to handle and manipulate text values. You can use them to change case, extract parts of a string, or measure its length.
| Function | Description | Example | Output |
|---|---|---|---|
LENGTH(str) |
Returns length of a string | LENGTH('MySQL') |
5 |
UPPER(str) |
Converts to uppercase | UPPER('database') |
DATABASE |
LOWER(str) |
Converts to lowercase | LOWER('HELLO') |
hello |
CONCAT(str1, str2, …) |
Joins multiple strings | CONCAT('My','SQL') |
MySQL |
SUBSTRING(str, start, length) |
Extracts part of a string | SUBSTRING('Database', 1, 4) |
Data |
REPLACE(str, from_str, to_str) |
Replaces text | REPLACE('MySQL', 'SQL', 'DB') |
MyDB |
TRIM(str) |
Removes spaces from both ends | TRIM(' PHP ') |
PHP |
SELECT CONCAT(UPPER(first_name), ' ', LOWER(last_name)) AS full_name
FROM users;
This query combines first and last names while formatting them in a specific case.
Numeric functions perform mathematical calculations on numeric data. They’re useful in reports, analytics, and calculations like totals or averages.
| Function | Description | Example | Output |
|---|---|---|---|
ABS(x) |
Absolute value | ABS(-7) |
7 |
ROUND(x, d) |
Rounds number to d decimals | ROUND(12.3456, 2) |
12.35 |
CEIL(x) |
Rounds up to nearest integer | CEIL(3.1) |
4 |
FLOOR(x) |
Rounds down | FLOOR(3.9) |
3 |
MOD(x, y) |
Returns remainder | MOD(10, 3) |
1 |
POWER(x, y) |
x raised to y | POWER(2, 3) |
8 |
RAND() |
Returns random number | RAND() |
e.g. 0.583 |
SELECT product_name, ROUND(price * 1.18, 2) AS price_with_tax
FROM products;
This calculates product prices with an 18% tax, rounding the result to two decimals.
Date and time functions let you work with values like dates, times, and timestamps. They help in generating reports, tracking events, or filtering data based on time.
| Function | Description | Example | Output |
|---|---|---|---|
NOW() |
Current date and time | NOW() |
2025-10-23 12:45:00 |
CURDATE() |
Current date | CURDATE() |
2025-10-23 |
CURTIME() |
Current time | CURTIME() |
12:45:00 |
YEAR(date) |
Extracts year | YEAR('2025-10-23') |
2025 |
MONTH(date) |
Extracts month | MONTH('2025-10-23') |
10 |
DAY(date) |
Extracts day | DAY('2025-10-23') |
23 |
DATE_ADD(date, INTERVAL n unit) |
Adds interval | DATE_ADD('2025-10-23', INTERVAL 7 DAY) |
2025-10-30 |
DATEDIFF(date1, date2) |
Difference in days | DATEDIFF('2025-10-30','2025-10-23') |
7 |
SELECT first_name, hire_date, DATEDIFF(CURDATE(), hire_date) AS days_worked
FROM employees;
This query calculates how many days each employee has worked.
Aggregate functions perform calculations on multiple rows and return a single value. They’re used with the GROUP BY clause to summarize data.
| Function | Description | Example |
|---|---|---|
COUNT() |
Counts rows | COUNT(*) |
SUM() |
Adds up values | SUM(salary) |
AVG() |
Average value | AVG(salary) |
MIN() |
Smallest value | MIN(price) |
MAX() |
Largest value | MAX(price) |
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
This query returns the average salary for each department.
Control flow functions add logic to SQL queries, similar to conditions in programming.
| Function | Description | Example | Output |
|---|---|---|---|
IF(condition, true_value, false_value) |
Returns one of two values | IF(10 > 5, 'Yes', 'No') |
Yes |
IFNULL(expr, alt_value) |
Returns alt if expr is NULL | IFNULL(NULL, 'N/A') |
N/A |
NULLIF(expr1, expr2) |
Returns NULL if equal | NULLIF(10,10) |
NULL |
CASE |
Multiple conditions | See example |
SELECT name,
CASE
WHEN marks >= 90 THEN 'A'
WHEN marks >= 75 THEN 'B'
WHEN marks >= 60 THEN 'C'
ELSE 'Fail'
END AS grade
FROM students;
This assigns grades based on marks.
System functions return information about the MySQL server, database, or user.
| Function | Description | Example | Output |
|---|---|---|---|
USER() |
Current user | USER() |
root@localhost |
DATABASE() |
Current database name | DATABASE() |
school_db |
VERSION() |
MySQL version | VERSION() |
8.0.35 |
Example:
SELECT DATABASE(), USER(), VERSION();
You can combine functions to perform complex operations in a single query.
Example:
SELECT UPPER(name) AS student_name,
ROUND(AVG(marks), 2) AS average_marks,
YEAR(admission_date) AS admission_year
FROM students
GROUP BY admission_year;
This query:
Converts names to uppercase
Calculates the average marks
Groups data by admission year
Use aggregate functions with GROUP BY for summaries.
Avoid applying functions directly in the WHERE clause on large datasets (it slows queries).
Always use ROUND() for decimals when displaying results.
Use IFNULL() to handle missing or NULL values gracefully.
Format dates using DATE_FORMAT() when you need readable output.
MySQL functions make it easier to analyze, calculate, and format data directly within SQL.
In this tutorial, you learned about:
String functions for text manipulation
Numeric functions for calculations
Date and time functions for temporal data
Aggregate functions for summaries
Control flow functions for conditional logic
System functions for database info
By combining these, you can write clean, powerful queries that handle data smartly without extra programming.
Create a table named students with columns id, first_name, last_name, and marks. Insert at least 3 records.
Write a query to display the full name of each student by combining first_name and last_name using CONCAT().
Use the UPPER() and LOWER() functions to display all student names in uppercase and lowercase.
Create a table products with columns product_name and price. Write a query to round all prices to 2 decimal places using ROUND().
Write a query to find the total and average price of all products using SUM() and AVG().
Insert a table employees with hire_date column. Write a query to calculate the number of days each employee has worked using DATEDIFF().
Use IF() or CASE to assign grades (A, B, C, Fail) to students based on their marks.
Create a table orders with order_date. Write a query to find orders made in the current month using MONTH() and CURDATE().
Write a query to replace the word “Old” with “New” in a column product_name using REPLACE().
Display the current database, user, and MySQL version using DATABASE(), USER(), and VERSION() functions.