SQL functions are powerful tools that allow you to perform various operations on data within
your database. They can be categorized into different types: aggregate functions, scalar
functions, string functions, date functions, and others.
Here are some commonly used SQL functions:
Aggregate Functions
These functions perform a calculation on a set of values and return a single value.
AVG(): Returns the average value.
sql
Copy code
SELECT AVG(column_name) FROM table_name;
COUNT(): Returns the number of rows.
sql
Copy code
SELECT COUNT(*) FROM table_name;
MAX(): Returns the maximum value.
sql
Copy code
SELECT MAX(column_name) FROM table_name;
MIN(): Returns the minimum value.
sql
Copy code
SELECT MIN(column_name) FROM table_name;
SUM(): Returns the sum of values.
sql
Copy code
SELECT SUM(column_name) FROM table_name;
Scalar Functions
These functions operate on individual values and return a single value for each input value.
UCASE() / UPPER(): Converts a string to uppercase.
sql
Copy code
SELECT UPPER(column_name) FROM table_name;
LCASE() / LOWER(): Converts a string to lowercase.
sql
Copy code
SELECT LOWER(column_name) FROM table_name;
ROUND(): Rounds a number to a specified number of decimal places.
sql
Copy code
SELECT ROUND(column_name, 2) FROM table_name;
LEN() / LENGTH(): Returns the length of a string.
sql
Copy code
SELECT LENGTH(column_name) FROM table_name;
String Functions
These functions perform operations on string values.
CONCAT(): Concatenates two or more strings.
sql
Copy code
SELECT CONCAT(string1, string2) FROM table_name;
SUBSTRING() / SUBSTR(): Extracts a substring from a string.
sql
Copy code
SELECT SUBSTRING(column_name, start, length) FROM table_name;
TRIM(): Removes leading and trailing spaces from a string.
sql
Copy code
SELECT TRIM(column_name) FROM table_name;
REPLACE(): Replaces all occurrences of a specified string with another string.
sql
Copy code
SELECT REPLACE(column_name, 'old_string', 'new_string') FROM
table_name;
Date Functions
These functions perform operations on date values.
NOW(): Returns the current date and time.
sql
Copy code
SELECT NOW();
CURDATE(): Returns the current date.
sql
Copy code
SELECT CURDATE();
CURTIME(): Returns the current time.
sql
Copy code
SELECT CURTIME();
DATE_ADD(): Adds a specified time interval to a date.
sql
Copy code
SELECT DATE_ADD(date_column, INTERVAL 10 DAY) FROM table_name;
DATEDIFF(): Returns the difference between two dates.
sql
Copy code
SELECT DATEDIFF(date1, date2) FROM table_name;
Other Useful Functions
COALESCE(): Returns the first non-null value in a list.
sql
Copy code
SELECT COALESCE(column1, column2, 'default_value') FROM table_name;
IFNULL(): Returns a specified value if the column value is NULL.
sql
Copy code
SELECT IFNULL(column_name, 'default_value') FROM table_name;
These functions can be used in various combinations to perform complex queries and data
manipulations within your SQL database.
4o