Functions are the measured values and cannot create permanent environment changes to SQL server. SQL functions are used for the following purpose:
- To perform calculations on data
- To modify individual data items
- To manipulate the output
- To format dates and numbers
- To convert data types
The usage of SQL functions in a database is to perform operations on data stored in the database. SQL functions can be broadly categorized into several types, each serving a specific purpose. Here are some common types of SQL functions and their usage:
- Aggregate Functions:
- Examples:
SUM()
,AVG()
,COUNT()
,MIN()
,MAX()
. - Usage: These functions perform calculations on a set of values and return a single result. For instance,
SUM()
calculates the sum of numeric values in a column,AVG()
calculates the average,COUNT()
counts the number of rows, and so on.
- Examples:
- Scalar Functions:
- Examples:
UPPER()
,LOWER()
,LEN()
,CONCAT()
. - Usage: Scalar functions operate on a single value and return a modified or calculated value. For example,
UPPER()
converts a string to uppercase,CONCAT()
concatenates strings, andLEN()
returns the length of a string.
- Examples:
- String Functions:
- Examples:
SUBSTRING()
,LEFT()
,RIGHT()
,CHARINDEX()
. - Usage: String functions are used for manipulating and working with character strings.
SUBSTRING()
extracts a substring from a string,LEFT()
andRIGHT()
return a specified number of characters from the left or right side of a string, andCHARINDEX()
finds the position of a substring within a string.
- Examples:
- Date and Time Functions:
- Examples:
GETDATE()
,DATEDIFF()
,DATEADD()
. - Usage: Date and time functions help manipulate and retrieve information related to date and time.
GETDATE()
returns the current date and time,DATEDIFF()
calculates the difference between two dates, andDATEADD()
adds or subtracts a specific time interval from a date.
- Examples:
- Mathematical Functions:
- Examples:
ABS()
,ROUND()
,CEILING()
,FLOOR()
. - Usage: Mathematical functions perform mathematical operations on numeric data.
ABS()
returns the absolute value,ROUND()
rounds a numeric value to a specified number of decimal places, andCEILING()
andFLOOR()
round a number up or down to the nearest integer.
- Examples:
- Conversion Functions:
- Examples:
CAST()
,CONVERT()
. - Usage: Conversion functions are used to convert data from one type to another. For instance,
CAST()
andCONVERT()
can be used to convert a string to a numeric type or vice versa.
- Examples:
These are just a few examples, and there are many other SQL functions designed to meet various data manipulation and retrieval needs. The usage of a specific function depends on the task at hand and the type of data you are working with in the database.