Professional Documents
Culture Documents
Functions in SQL
Functions in SQL
A function is a special type of command. Infact, functions are one-word command that return a
single value. The value of a function can be determined by input parameters, as with a function
that averages a list of database values. But many functions do not use any type of input
parameter, such as the function that returns the current system time, CURRENT_TIME. There
are normally two types of functions. First is Built in, which are provided by any specific tool or
language. Second is user defined, which are defined by the user. The SQL supports a number of
useful functions.. In addition, each database vendor maintains a long list of their own internal
functions that are outside of the scope of the SQL standard.
Categories of Functions:
These categories of functions are specific to SQL Server. Depending on the arguments and the
return value, functions are categorized as under:
• Mathematical (ABS, ROUND, SIN, SQRT)
• String (LOWER, UPPER, SUBSTRING, LEN)
• Date (DATEDIFF, DATEPART, GETDATE ())
• System (USER, DATALENGTH, HOST_NAME)
• Conversion (CAST, CONVERT)
We will now see an example using above-mentioned functions:
In this example student name will be displayed in upper case whereas father name will be
displayed in lower case. The third function is of getting the length of student address. It has got
nesting of functions, first address is converted into character and then its length will be
displayed.
Aggregate Functions:
These functions operate on a set of rows and return a single value. If used among many other
expressions in the item list of a SELECT statement, the SELECT must have a GROUP BY
clause. No GROUP BY clause is required if the aggregate function is the only value retrieved by
the SELECT statement. Following are some of the aggregate functions:
Function Usage
AVG(expression) Computes average value of a column by the expression
COUNT(expression) Counts the rows defined by the expression
COUNT(*) Counts all rows in the specified table or view
MIN(expression) Finds the minimum value in a column by the expression
MAX(expression) Finds the maximum value in a column by the expression
SUM(expression) Computes the sum of column values by the expression
SELECT avg(cgpa) as 'Average CGPA', max(cgpa) as 'Maximum CGPA' from student
GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple
records and group the results by one or more columns. It is added to SQL because aggregate
functions (like SUM) return the aggregate of all column values every time they are called, and
without the GROUP BY function it is impossible to find the sum for each individual group of
column values.
The syntax for the GROUP BY clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n;
Aggregate function can be a function such as SUM, COUNT, MIN or MAX