MySQL provides a rich set of built-in functions that allow users to manipulate data, perform calculations, and work with strings, dates, and numbers efficiently.
Functions in MySQL are pre-defined operations that perform specific tasks on data. They simplify repetitive tasks, enhance query capabilities, and make data manipulation easier.
MySQL functions are divided into the following categories:
Operate on a set of values and return a single value.
Manipulate text data.
Perform operations on numbers.
Work with date and time values.
Implement conditional logic.
Operate on JSON data.
Custom functions created by users.
SELECT SUM(salary) AS total_salary FROM employees;
salary
values in the employees
table.total_salary
.Output: If the salaries are 3000, 4000, 5000
, the result will be:
total_salary
------------
12000
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
first_name
and last_name
with a space in between.full_name
.Output: For first_name = 'John'
and last_name = 'Doe'
:
full_name
---------
John Doe
SELECT ROUND(123.456, 2) AS rounded_value;
123.456
to 2 decimal places.
rounded_value
-------------
123.46
SELECT NOW() AS current_date_time;
current_date_time
------------------
2024-11-12 14:30:45
SELECT
employee_id,
CASE
WHEN salary > 5000 THEN 'High'
WHEN salary > 3000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;
Output: For salaries 6000, 4000, 2000
employee_id salary_category
----------- ----------------
1 High
2 Medium
3 Low
Functions can be used in:
SELECT UPPER(SUBSTRING(name, 1, 5)) AS modified_name FROM employees;
SELECT COUNT(*) AS total_employees, DATE(NOW()) AS current_date FROM employees;
total_employees current_date
--------------- ------------
25 2024-11-12
SELECT JSON_EXTRACT('{"name": "John", "age": 30}', '$.name') AS name;
name
----
John
WHERE
conditions can slow queries.MySQL functions are powerful tools that simplify data manipulation, enhance query flexibility, and streamline database operations. Happy Coding!❤️