How to Know Which Function to Use:
You can use these functions to transform data, calculate values, or extract specific information in your queries.
Let’s go through some examples that clarify how to use different functions in SQL.
Example 1: String Functions - Formatting Names
Let’s say you want to format employee names, ensuring the first letter of their first and last names is
SELECT
CONCAT(UPPER(SUBSTRING(e.first_name, 1, 1)), LOWER(SUBSTRING(e.first_name, 2))) AS formatted_first_name,
CONCAT(UPPER(SUBSTRING(e.last_name, 1, 1)), LOWER(SUBSTRING(e.last_name, 2))) AS formatted_last_name
FROM Employees e;
Explanation:
UPPER()
andLOWER()
are string functions used to make the first letter uppercase and the rest of the name lowercase.CONCAT()
is used to join the modified first and last names together.
hire_date
, you can use the DATEDIFF()
function:Explanation:
DATEDIFF(CURDATE(), e.hire_date)
calculates the number of days between today (CURDATE()
) and the employee’shire_date
.- Dividing the number of days by 365 gives an approximate number of years the employee has been with the company.
AVG()
function:Explanation:
AVG(e.salary)
calculates the average salary of employees in each department.GROUP BY
groups the employees by department, so the aggregation happens for each department separately.
Example 4: Mathematical Functions - Rounding Salaries
Suppose you want to round employee salaries to the nearest thousand for a report: