FUNCTION IN SQL
COMPREHENSIVE SQL FUNCTIONS GUIDE WITH DETAILED EXPLANATIONS
String Functions
1. CONCAT()
Purpose: Joins two or more strings into one.
Syntax:
sql
CONCAT(string1, string2, ..., stringN)
Examples:
sql
SELECT CONCAT('Hello', ' ', 'World'); -- Output: 'Hello World'
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
Key Notes:
Works in all major DBMS (MySQL, PostgreSQL, SQL Server, Oracle).
Alternative: || operator in PostgreSQL/Oracle ('Hello' || ' ' || 'World').
2. LENGTH() / LEN()
Purpose: Returns the number of characters in a string.
Syntax Variations:
sql
LENGTH(string) -- MySQL, PostgreSQL, SQLite
LEN(string) -- SQL Server, MS Access
Examples:
sql
SELECT LENGTH('Tax'); -- Output: 3
SELECT LEN('Revenue'); -- Output: 7 (SQL Server)
Key Notes:
Counts spaces as characters.
For byte length: LENGTHB() (Oracle) or DATALENGTH() (SQL Server).
3. LOWER() / UPPER()
Purpose: Converts string case.
Syntax:
sql
LOWER(string) -- Converts to lowercase
UPPER(string) -- Converts to uppercase
Examples:
sql
SELECT LOWER('TAX'); -- Output: 'tax'
SELECT UPPER('rra'); -- Output: 'RRA'
Key Notes:
Non-alphabetic characters remain unchanged.
4. SUBSTRING() / MID()
Purpose: Extracts part of a string.
Syntax:
sql
SUBSTRING(string, start, length) -- Standard
MID(string, start, length) -- MySQL alias
Examples:
sql
SELECT SUBSTRING('Revenue', 1, 3); -- Output: 'Rev'
SELECT MID('Database', 4, 3); -- Output: 'bas' (MySQL)
Key Notes:
Start position is 1-based (not 0).
In Oracle: Use SUBSTR().
5. TRIM() / LTRIM() / RTRIM()
Purpose: Removes leading/trailing spaces.
Syntax:
sql
TRIM(string) -- Removes both sides
LTRIM(string) -- Removes left spaces
RTRIM(string) -- Removes right spaces
Examples:
sql
SELECT TRIM(' tax '); -- Output: 'tax'
SELECT LTRIM(' value'); -- Output: 'value'
Key Notes:
For custom characters: TRIM(LEADING 'x' FROM 'xxTaxxx') (MySQL/PostgreSQL).
6. REPLACE()
Purpose: Replaces all occurrences of a substring.
Syntax:
sql
REPLACE(string, old_substring, new_substring)
Examples:
sql
SELECT REPLACE('TIN Number', 'Number', 'Code'); -- Output: 'TIN Code'
SELECT REPLACE('a-b-c', '-', '/'); -- Output: 'a/b/c'
7. CHARINDEX() / INSTR()
Purpose: Finds the position of a substring.
Syntax Variations:
sql
CHARINDEX('sub', string) -- SQL Server
INSTR(string, 'sub') -- Oracle, MySQL
POSITION('sub' IN string) -- PostgreSQL
Examples:
sql
SELECT CHARINDEX('v', 'Revenue'); -- Output: 4 (SQL Server)
SELECT INSTR('Revenue', 'v'); -- Output: 4 (MySQL)
Numeric Functions
1. ROUND()
Purpose: Rounds a number to specified decimal places.
Syntax:
sql
ROUND(number, decimal_places)
Examples:
sql
SELECT ROUND(123.4567, 2); -- Output: 123.46
SELECT ROUND(123.4567, -1); -- Output: 120 (rounds to tens)
2. CEIL() / FLOOR()
Purpose: Rounds up/down to the nearest integer.
Syntax:
sql
CEIL(number) -- Rounds up
FLOOR(number) -- Rounds down
Examples:
sql
SELECT CEIL(4.3); -- Output: 5
SELECT FLOOR(4.7); -- Output: 4
3. ABS()
Purpose: Returns the absolute value.
Syntax:
sql
ABS(number)
Example:
sql
SELECT ABS(-15); -- Output: 15
4. MOD() / %
Purpose: Returns the remainder of division.
Syntax Variations:
sql
MOD(dividend, divisor) -- Standard
dividend % divisor -- MySQL, PostgreSQL
Examples:
sql
SELECT MOD(10, 3); -- Output: 1
SELECT 10 % 3; -- Output: 1 (MySQL)
5. POWER()
Purpose: Raises a number to a power.
Syntax:
sql
POWER(base, exponent)
Example:
sql
SELECT POWER(2, 3); -- Output: 8
6. RAND()
Purpose: Generates a random number (0 to 1).
Syntax:
sql
RAND() -- Random float
Example:
sql
SELECT RAND(); -- Output: 0.12345...
7. SQRT()
Purpose: Calculates the square root.
Syntax:
sql
SQRT(number)
Example:
sql
SELECT SQRT(16); -- Output: 4
Date/Time Functions
1. NOW() / CURRENT_TIMESTAMP
Purpose: Returns current date and time.
Syntax:
sql
NOW() -- MySQL
CURRENT_TIMESTAMP -- Standard SQL
Example:
sql
SELECT NOW(); -- Output: '2025-07-23 14:30:45'
2. CURDATE() / CURRENT_DATE
Purpose: Returns current date.
Syntax:
sql
CURDATE() -- MySQL
CURRENT_DATE -- Standard SQL
Example:
sql
SELECT CURDATE(); -- Output: '2025-07-23'
3. DATEDIFF()
Purpose: Calculates days between two dates.
Syntax:
sql
DATEDIFF(end_date, start_date)
Example:
sql
SELECT DATEDIFF('2025-12-31', '2025-01-01'); -- Output: 364
Conditional Functions
1. CASE WHEN
Purpose: Conditional logic.
Syntax:
sql
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END
Example:
sql
SELECT
CASE
WHEN salary >= 5000 THEN 'High'
WHEN salary >= 3000 THEN 'Medium'
ELSE 'Low'
END AS salary_level
FROM employees;
2. COALESCE()
Purpose: Returns the first non-NULL value.
Syntax:
sql
COALESCE(val1, val2, ..., valN)
Example:
sql
SELECT COALESCE(NULL, 'Fallback', 'Value'); -- Output: 'Fallback'
Exercises
1. Extract Year:
sql
SELECT YEAR(CURRENT_DATE);
Replace Text:
Sql
SELECT REPLACE('RRA collects tax', 'RRA', 'KRA');
Concatenate Names:
sql
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
Salary Labeling:
sql
4. SELECT
5. CASE
6. WHEN salary >= 5000 THEN 'High'
7. WHEN salary >= 3000 THEN 'Medium'
8. ELSE 'Low'
9. END AS salary_category
10. FROM employees;
Case study:
EMPLOYEE
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
hire_date DATE,
salary DECIMAL(10, 2),
department_id INT
DEPARTMENTS
department_id INT PRIMARY KEY,
department_name VARCHAR(100)
PROJECTS
project_id INT PRIMARY KEY,
project_name VARCHAR(100),
start_date DATE,
end_date DATE
EMPLOYEE_PROJECTS
employee_id INT,
project_id INT,
assigned_date DATE,
PRIMARY KEY (employee_id, project_id)
INSERT INTO departments (department_id, department_name) VALUES
(1, 'Human Resources'),
(2, 'Finance'),
(3, 'Information Technology'),
(4, 'Marketing'),
(5, 'Legal'),
(6, 'Operations'),
(7, 'Customer Service'),
(8, 'Sales'),
(9, 'Research and Development'),
(10, 'Procurement');
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary,
department_id) VALUES
(101, 'Alice', 'Johnson', '[email protected]', '2015-03-15', 4500.00, 1),
(102, 'Bob', 'Smith', '[email protected]', '2018-06-23', 5200.00, 3),
(103, 'Carol', 'Adams', '[email protected]', '2012-09-10', 6700.00, 2),
(104, 'David', 'Lee', '[email protected]', '2020-01-05', 3800.00, 4),
(105, 'Eve', 'Martins', '[email protected]', '2019-12-11', 4000.00, 3),
(106, 'Frank', 'Green', '[email protected]', '2017-07-08', 6000.00, 8),
(107, 'Grace', 'Brown', '[email protected]', '2014-11-02', 4900.00, 5),
(108, 'Hank', 'Wilson', '[email protected]', '2013-02-17', 3100.00, 6),
(109, 'Ivy', 'Clark', '
[email protected]', '2021-08-30', 2700.00, 9),
(110, 'Jake', 'White', '[email protected]', '2022-05-19', 3600.00, 7);
INSERT INTO projects (project_id, project_name, start_date, end_date) VALUES
(201, 'HR Revamp', '2023-01-01', '2023-12-31'),
(202, 'Finance Automation', '2022-05-15', '2023-04-30'),
(203, 'IT Infrastructure Upgrade', '2024-01-01', NULL),
(204, 'Marketing Blitz 2025', '2025-02-01', '2025-06-30'),
(205, 'Legal Compliance', '2023-07-10', '2024-01-10'),
(206, 'Customer Portal', '2021-11-01', '2022-10-31'),
(207, 'Sales Booster', '2022-04-01', '2023-03-31'),
(208, 'R&D Pilot', '2025-01-01', NULL),
(209, 'Procurement Tracker', '2024-03-15', '2024-11-15'),
(210, 'Operations Streamline', '2022-09-01', '2023-09-01');
INSERT INTO employee_projects (employee_id, project_id, assigned_date) VALUES
(101, 201, '2023-01-10'),
(102, 203, '2024-01-05'),
(103, 202, '2022-05-20'),
(104, 204, '2025-02-10'),
(105, 203, '2024-01-07'),
(106, 207, '2022-04-15'),
(107, 205, '2023-07-15'),
(108, 210, '2022-09-10'),
(109, 208, '2025-01-10'),
(110, 206, '2021-11-05');
Exercises
String Function Exercises (15)
1. Concatenate first and last name as full_name.
2. Convert all employee names to lowercase.
3. Extract first 3 letters of the employee's first name.
4. Replace '@company.com' in email with '@org.com'.
5. Trim spaces from a padded string.
6. Count characters in an employee’s full name.
7. Find position of '@' in email using INSTR()/CHARINDEX().
8. Add ‘Mr.’ or ‘Ms.’ before names based on gender (assume gender exists).
9. Format project names to uppercase.
10. Remove any dashes from project names.
11. Create a label like “Emp: John Doe (HR)”.
12. Check email length for each employee.
13. Extract last name only from email (before @).
14. Format: “LASTNAME, Firstname” using UPPER and CONCAT.
15. Add “(Active)” next to employee names who have current projects.
Numeric Function Exercises (10)
16. Round salary to the nearest whole number.
17. Show only even salaries using MOD.
18. Show difference between two project end/start dates using DATEDIFF.
19. Show absolute difference in salaries between two employees.
20. Raise salary by 10% using POWER.
21. Generate a random number for testing IDs.
22. Use CEIL and FLOOR on a floating salary.
23. Use LENGTH() on phone numbers (assume column exists).
24. Categorize salary: High/Medium/Low using CASE.
25. Count digits in salary amount.
Date/Time Function Exercises (10)
26. Show today’s date using CURRENT_DATE.
27. Calculate how many days an employee has worked.
28. Show employees hired in the current year.
29. Display current date and time using NOW().
30. Extract the year, month, and day from hire_date.
31. Show employees hired before 2020.
32. List projects that ended in the last 30 days.
33. Calculate total days between project start and end dates.
34. Format date: ‘2025-07-23’ to ‘July 23, 2025’ (use CONCAT).
35. Add a CASE: if project still active (end_date IS NULL), show ‘Ongoing’.
Conditional Function Exercises (15)
36. Use CASE to label salaries.
37. Use COALESCE to show ‘No Email’ if email is NULL.
38. CASE: If hire_date < 2015, mark as ‘Veteran’.
39. If salary is NULL, default it to 3000 using COALESCE.
40. CASE: Categorize departments (IT, HR, Other).
41. CASE: If employee has no project, mark as ‘Unassigned’.
42. CASE: Show tax band based on salary.
43. Use nested CASE to label project duration.
44. Use CASE with MOD to show even/odd salary IDs.
45. Combine COALESCE + CONCAT for fallback names.
46. CASE with LENGTH(): if name length > 10, label “Long Name”.
47. CASE + UPPER(): if email has ‘TEST’, mark as dummy account.
48. CASE: Show seniority based on hire year (e.g., Junior/Senior).
49. Use CASE to determine salary increment range.
50. Use CASE with CURDATE() to determine anniversary month.
END.