Anda di halaman 1dari 16

SQL Functions

SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:

AVG() - Returns the average value COUNT() - Returns the number of rows MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

BY Rupal Chavda(Msc.I.T.)

The AVG() Function


The AVG() function returns the average value of a numeric column.

SQL AVG() Syntax SELECT AVG(column_name) FROM table_name

SQL AVG() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the average value of the "OrderPrice" fields. We use the following SQL statement:

SELECT AVG(OrderPrice) AS OrderAverage FROM Orders


The result-set will look like this: OrderAverage 950 Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice value. We use the following SQL statement:

SELECT Customer FROM WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)


The result-set will look like this: Customer Hansen Nilsen Jensen

Orders

BY Rupal Chavda(Msc.I.T.)

SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax


The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:

SELECT COUNT(column_name) FROM table_name

SQL COUNT(*) Syntax


The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name

SQL COUNT(DISTINCT column_name) Syntax


The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:

SELECT COUNT(DISTINCT column_name) FROM table_name


Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.

SQL COUNT(column_name) Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to count the number of orders from "Customer Nilsen". We use the following SQL statement:

BY Rupal Chavda(Msc.I.T.)

SELECT COUNT(Customer) WHERE Customer='Nilsen'

AS

CustomerNilsen

FROM

Orders

The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total: CustomerNilsen 2

SQL COUNT(*) Example


If we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberOfOrders FROM Orders


The result-set will look like this: NumberOfOrders 6 which is the total number of rows in the table.

SQL COUNT(DISTINCT column_name) Example


Now we want to count the number of unique customers in the "Orders" table. We use the following SQL statement:

SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders


The result-set will look like this: NumberOfCustomers 3

BY Rupal Chavda(Msc.I.T.)

SQL MIN() Function


The MIN() Function
The MIN() function returns the smallest value of the selected column.

SQL MIN() Syntax SELECT MIN(column_name) FROM table_name

SQL MIN() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the smallest value of the "OrderPrice" column. We use the following SQL statement:

SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders


The result-set will look like this: SmallestOrderPrice 100

BY Rupal Chavda(Msc.I.T.)

The MAX() Function


The MAX() function returns the largest value of the selected column.

SQL MAX() Syntax SELECT MAX(column_name) FROM table_name

SQL MAX() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the largest value of the "OrderPrice" column. We use the following SQL statement:

SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders


The result-set will look like this: LargestOrderPrice 2000

BY Rupal Chavda(Msc.I.T.)

The SUM() Function


The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax SELECT SUM(column_name) FROM table_name

SQL SUM() Example


We have the following "Orders" table: O_Id 1 2 3 4 5 6 OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04 OrderPrice 1000 1600 700 300 2000 100 Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

Now we want to find the sum of all "OrderPrice" fields". We use the following SQL statement:

SELECT SUM(OrderPrice) AS OrderTotal FROM Orders


The result-set will look like this: OrderTotal 5700

BY Rupal Chavda(Msc.I.T.)

2)Scalar functions:
2.1 Numeric functions Sql abs() function
Description This SQL ABS() returns the absolute value of a number passed as argument. Syntax Select ABS(expression) from <tableName>; Example of Sql abs() function SELECT ABS(-17.36) FROM dual; o/p : 17.36

The ROUND() Function


The ROUND() function is used to round a numeric field to the number of decimals specified. SQL ROUND() Syntax SELECT ROUND(column_name,decimals) FROM table_name Parameter decimals Description Required. Specifies the number of decimals to be returned.

column_name Required. The field to round.

SQL ROUND() Example We have the following "Products" table: Prod_Id ProductName Unit 1 2 3 Jarlsberg Mascarpone Gorgonzola UnitPrice 1000 g 10.45 1000 g 32.56 1000 g 15.67

Now we want to display the product name and the price rounded to the nearest integer. We use the following SELECT statement: SELECT ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products The result-set will look like this: ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10 33 16

Sql sqrt() function


Description

BY Rupal Chavda(Msc.I.T.)

The SQL SQRT() returns the square root of given value in the argument. Syntax Select SQRT( expression ) from <tableName>; Example of Sql sqrt() function SELECT SQRT(36) FROM dual; o/p: 6

Sql sin() function


Description Returns the trigonometric sine of the specified angle, in radians, and in an approximate numeric, float and expression. Syntax SIN ( angle ) Example of Sql sin() function SELECT SIN(45.175643) FROM dual; o/p: 0.929607

Sql cos() function


Description Is a mathematical function that returns the trigonometric cosine of the specified angle, in radians, in the specified expression. Syntax COS ( angle ) Example of Sql cos() function SELECT COS(14.78) FROM dual; o/p: -0.599465

Sql tan() function


Description Returns the tangent of the input expression. Syntax TAN ( angle ) Example of Sql tan() function SELECT TAN(3.141592/2) FROM dual; o/p: 1.633177

Sql log() function BY Rupal Chavda(Msc.I.T.) 9

Description Returns the natural logarithm of the specified float expression. Syntax LOG ( Number ) Example of Sql log() function SELECT LOG(10) FROM dual; o/p: 2.30259

Sql Exp() function


Description Returns the exponential value of the specified float expression. Syntax EXP ( Number) Example of Sql Exp() function SELECT EXP(10) FROM dual; o/p: 22026.5

2.2 String functions


The LCASE() Function
The LCASE() function converts the value of a field to lowercase.

SQL LCASE() Syntax


SELECT LCASE(column_name) FROM table_name;

SQL LCASE() Example


We have the following "Persons" table: P_Id LastName FirstName Address 1 2 3 Hansen Svendson Pettersen Ola Tove Kari Borgvn 23 Storgt 20 City Sandnes Stavanger Timoteivn 10 Sandnes

Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the "LastName" column to lowercase. We use the following SELECT statement: SELECT LCASE(LastName) as LastName,FirstName FROM Persons;

BY Rupal Chavda(Msc.I.T.)

10

The result-set will look like this: LastName hansen svendson pettersen FirstName Ola Tove Kari

The UCASE() Function


The UCASE() function converts the value of a field to uppercase. SQL UCASE() Syntax SELECT UCASE(column_name) FROM table_name SQL UCASE() Example We have the following "Persons" table: P_Id LastName FirstName Address 1 2 3 Hansen Svendson Pettersen Ola Tove Kari Borgvn 23 Storgt 20 City Sandnes Stavanger Timoteivn 10 Sandnes

Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the "LastName" column to uppercase. We use the following SELECT statement: SELECT UCASE(LastName) as LastName,FirstName FROM Persons The result-set will look like this: LastName HANSEN SVENDSON PETTERSEN FirstName Ola Tove Kari

The LEFT() Function


Returns the left part of a character string with the specified number of characters. SQL LEFT() Syntax LEFT ( character_expression , integer_expression ) SQL LEFT() Example SELECT LEFT('abcdefg',2)

Output
ab

The RIGHT() Function


Returns the right part of a character string with the specified number of characters.

BY Rupal Chavda(Msc.I.T.)

11

SQL RIGHT() Syntax RIGHT ( character_expression , integer_expression ); SQL RIGHT() Example SELECT RIGHT('abcdefg',2);

Output
fg

The MID() Function


The MID() function is used to extract characters from a text field. SQL MID() Syntax SELECT MID(column_name,start[,length]) FROM table_name; Parameter column_name start length Description Required. The field to extract characters from Required. Specifies the starting position (starts at 1) Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text

SQL MID() Example We have the following "Persons" table: P_Id LastName FirstName Address 1 2 3 Hansen Svendson Pettersen Ola Tove Kari Borgvn 23 Storgt 20 City Sandnes Stavanger Timoteivn 10 Sandnes

Now we want to extract the first four characters of the "City" column above. We use the following SELECT statement: SELECT MID(City,1,4) as SmallCity FROM Persons The result-set will look like this: SmallCity Sand Sand Stav

The LEN() Function


The LEN() function returns the length of the value in a text field. SQL LEN() Syntax SELECT LEN(column_name) FROM table_name SQL LEN() Example We have the following "Persons" table: P_Id LastName FirstName Address 1 Hansen Ola City Timoteivn 10 Sandnes

BY Rupal Chavda(Msc.I.T.)

12

2 3

Svendson Pettersen

Tove Kari

Borgvn 23 Storgt 20

Sandnes Stavanger

Now we want to select the length of the values in the "Address" column above. We use the following SELECT statement: SELECT LEN(Address) as LengthOfAddress FROM Persons The result-set will look like this: LengthOfAddress 12 9 9

The strReverse() function


Returns the reverse of a string value. SQL strReverse() Syntax strReverse ( string_expression ) SQL strReverse() Example strReverse(Pooja); Output ajooP

The Space() function


Returns a string of repeated spaces. SQL Space() Syntax SPACE ( integer_expression ) SQL Space() Example SELECT fname + SPACE(2) + lname as FullName FROM student;

Output
FullName Rupal Chavda Dhruti Mehta Sejal Chavda

2.3 Date/time functions


DateAdd() function
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date. Syntax DATEADD (datepart , number , date )

BY Rupal Chavda(Msc.I.T.)

13

=>datepart Is the part of date to which an integer number is added. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid. datepart Abbreviations year yy , yyyy quarter qq , q month mm , m dayofyear dy , y day dd , d week wk , ww weekday dw , w hour hh minute mi , n second ss , s millisecond ms microsecond mcs nanosecond ns =>number Is an expression that can be resolved to an int that is added to a datepart of date. User-defined variables are valid. If you specify a value with a decimal fraction, the fraction is truncated and not rounded. =>date Is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value. date can be an expression, column expression, user-defined variable, or string literal. If the expression is a string literal, it must resolve to a datetime. To avoid ambiguity, use fourdigit years. Example SELECT DateAdd("m",1,"01-28-2012"); Output 2/28/2012

BY Rupal Chavda(Msc.I.T.)

14

DateDiff() function
Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate. Syntax DATEDIFF ( datepart , startdate , enddate ) =>datepart Is the part of startdate and enddate that specifies the type of boundary crossed. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid. datepart Abbreviations year yy, yyyy quarter qq, q month mm, m dayofyear dy, y day dd, d week wk, ww hour hh minute mi, n second ss, s millisecond ms microsecond mcs nanosecond ns =>startdate Is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value. date can be an expression, column expression, user-defined variable or string literal. startdate is subtracted from enddate. To avoid ambiguity, use four-digit years =>enddate Same as startdate. Example SELECT DateDiff("m","01-28-2012","02-28-2012"); Output 1

BY Rupal Chavda(Msc.I.T.)

15

Day() function
Returns an integer representing the day (day of the month) of the specified date. Syntax DAY ( date ) Example SELECT Day("01-18-2012"); Output 18

Month() function
Returns an integer that represents the month of the specified date. Syntax Month( date ) Example SELECT Month("01-18-2012"); Output 1

Year() function
Returns an integer that represents the year of the specified date. Syntax Year( date ) Example SELECT Year("01-18-2012"); Output 2012

MonthName() function
Returns Name of the specified month Syntax MonthName( Month number ) Example SELECT MonthName(7); Output July

BY Rupal Chavda(Msc.I.T.)

16

Anda mungkin juga menyukai