Functions
MySQL functions perform specific operations on data, making queries more efficient and flexible. They are categorized into aggregate, string, date, and mathematical functions.
Common Uses of MySQL Functions
- Aggregate Functions: Summarize data (e.g.,
SUM()
). - String Functions: Modify text (e.g.,
CONCAT()
). - Date Functions: Manipulate dates (e.g.,
NOW()
). - Mathematical Functions: Perform calculations (e.g.,
ROUND()
). - JSON Functions: Handle JSON data (e.g.,
JSON_OBJECT()
).
Examples
- Aggregate Function
SELECT AVG(salary) AS average_salary FROM employees;
Explanation: Calculates the average salary of employees.
- String Function
SELECT UPPER(name) AS uppercase_name FROM customers;
Explanation: Converts customer names to uppercase.
- Date Function
SELECT CURDATE() AS today;
Explanation: Retrieves the current date.
- Mathematical Function
SELECT ROUND(price, 2) AS rounded_price FROM products;
Explanation: Rounds the
price
to two decimal places. - JSON Function
SELECT JSON_OBJECT('id', id, 'name', name) AS json_data FROM users;
Explanation: Converts
id
andname
columns into a JSON object.