SQL Basics

Chapter 8 - Functions

  • Functions are predefined routines that transform values through conversion or calculation
  • These functions operate on the values displayed in the result, rather than changing the stored data
  • There are hundreds of functions; you will typically use a few dozen
  • Functions depend heavily on the DBMS. Only a few work identically across all systems

SELECT	FUNCTIENAAM(column1)
FROM	<table>;
  • Parameters appear in parentheses after the function name and specify the values on which it operates
  • A function returns a value of a particular data type
  • Some functions take no parameters, for example when simply retrieving a system value
  • Parentheses normally follow the function name. Oracle system expressions such as CURRENT_DATE are an exception
  • Functions fall into several groups. Most DBMSs support the following groups:

Function Type Description
Text functions Operate on strings, for example by removing spaces or converting characters to uppercase
Numeric functions Operate on numbers, for example by rounding to a whole number or calculating a square root
Date and time functions Operate on dates and times, for example by calculating the difference between two times or adding seven days to today's date
Other functions Provide various operations, such as converting a value to another data type or retrieving the current date from the DBMS
Aggregate functions Operate across multiple rows, for example to calculate a column's average or sum (see Chapter 9)

  • Some commonly used text functions

Function Description
LEN(field) or LENGTH(field) Returns the length of a field
LOWER(field) or LCASE(field) Converts the string to lowercase
UPPER(field) or UCASE(field) Converts the string to uppercase
TRIM(field) Removes spaces around a value in a field
SUBSTR(field, 3, 5) or SUBSTRING(field, 3, 5) Extracts part of a string, using a starting position and length
SOUNDEX(field)
W3Schools explanation
Uses a phonetic algorithm to convert text into an alphanumeric code representing how a word sounds. Not supported by PostgreSQL

Select the customer name and contact name from Customers for contacts whose names sound like "Michael Green."

-- Oracle / MySQL / SQL Server
SELECT cust_name,
       cust_contact
FROM   Customers
WHERE  SOUNDEX(cust_contact) = SOUNDEX('Michael Green');
cust_namecust_contact
Kids PlaceMichelle Green

Select the vendor names from Vendors and display them in uppercase.

-- Oracle / MySQL / SQL Server
SELECT   UPPER(vend_name) AS Leveranciers
FROM     Vendors
ORDER BY vend_name;
Leveranciers
BEAR EMPORIUM
BEARS R US
DOLL HOUSE INC.
FUN AND GAMES
FURBALL INC.
JOUETS ET OURS
  • Some commonly used numeric functions

Function Description
ROUND(field, 2) Rounds a number to two decimal places
CEILING(field) Rounds a number up
FLOOR(field) Rounds a number down
MOD(field, 3) Returns the remainder after division by 3

Select item_price multiplied by quantity from OrderItems. Name the column 'Totaalprijs', round it down and sort by it in descending order.

-- Oracle / MySQL / SQL Server
SELECT   FLOOR(item_price * quantity) AS Totaalprijs
FROM     OrderItems
ORDER BY Totaalprijs DESC;
Totaalprijs
1099
622
622
622
574
549
299
299
299
224
119
119
89
59
34
34
34
24
  • Dates and times are stored in database-specific formats
  • Functions are often needed when working with dates
  • Date and time functions are among the most important SQL functions

Function Oracle MYSQL SQL Server PostgreSQL SQLite
Returns the current date CURRENT_DATE CURRENT_DATE( ) GETDATE( ) CURRENT_DATE( ) DATE( )
Add days to a date DATEADD( ) ADDDATE( ) DATEADD( ) Operators rather than a function DATE( )
Extract part of a date EXTRACT( ) EXTRACT( ) DATEPART( ) EXTRACT( ) STRFTIME( ) / SUBSTR( )
Number of days between two dates DATEDIFF( ) DATEDIFF( ) DATEDIFF( ) Operators rather than a function JULIANDAY( )

Select all orders placed in May

-- Oracle / MySQL / PostgreSQL
SELECT *
FROM   Orders
WHERE  EXTRACT(month FROM order_date) = 5;
-- MySQL / SQL Server
SELECT *
FROM   Orders
WHERE  MONTH(order_date) = 5;	
-- SQL Server
SELECT *
FROM   Orders
WHERE  DATEPART(mm, order_date) = 5;	
-- SQLite
SELECT * 
FROM   Orders
WHERE  SUBSTR(order_date, 6,2) = '05';	
order_numorder_datecust_id
200052012-05-01 00:00:001000000001
  • Other functions can be divided into several categories.
  • Examples include conversion functions, NULL-handling functions and system functions

Function Description
CAST(field AS datatype) Converts a value to another data type
IFNULL(field) Replaces a NULL value in the result with another value
VERSION( ) Returns the DBMS server version

Select the product name and price including 21% VAT, rounded to two decimal places

-- Oracle / SQL Server	
SELECT   prod_name,
         CAST(prod_price * 1.21 AS DECIMAL(8,2)) AS PrijsIncl
FROM     Products
ORDER BY PrijsIncl;
-- MySQL / Oracle / Azure SQL Server / PostgreSQL
SELECT   prod_name,
         ROUND(prod_price * 1.21,2) AS PrijsIncl
FROM     Products
ORDER BY PrijsIncl;	
prod_namePrijsIncl
Fish bean bag toy4.22
Bird bean bag toy4.22
Rabbit bean bag toy4.22
Raggedy Ann6.04
8 inch teddy bear7.25
12 inch teddy bear10.88
King doll11.48
Queen doll11.48
18 inch teddy bear14.51



Select all customer email addresses and replace NULL values with 'Onbekend'

-- Oracle 
SELECT	 NVL(cust_email,'Onbekend') EmailAdressen
FROM     Customers;
-- MySQL 
SELECT	 IFNULL(cust_email,'Onbekend') AS EmailAdressen
FROM     Customers;
-- SQL Server 
SELECT	 ISNULL(cust_email,'Onbekend') AS EmailAdressen
FROM     Customers;
-- Oracle / MySQL / SQL Server / PostgreSQL 
SELECT	 COALESCE(cust_email,'Onbekend') AS EmailAdressen 
FROM     Customers;
EmailAdressen
sales@villagetoys.com
Onbekend
jjones@fun4all.com
dstephens@fun4all.com
Onbekend



Select the current date

-- Oracle
SELECT   SYSDATE HuidigeDatum
FROM     dual;	
-- MySQL
SELECT   CURDATE() AS HuidigeDatum;
-- SQL Server
SELECT   CAST(GETDATE() AS Date) AS HuidigeDatum;	
-- PostgreSQL
SELECT   CURRENT_DATE AS HuidigeDatum;	
HuidigeDatum
2022-08-26
  1. Select the customer name and add a column containing the length of the name (5)


  1. Select all orders placed in January 2012 (2)


  1. Select the product name and price from Products. Round the price down (9)


  1. Select prod_id, prod_name and prod_price from Products. Add columns for VAT and the price including VAT. Format the last two columns to two decimal places (9)


  1. Select the name of the current database (1)