0% found this document useful (0 votes)
2 views

Built in Functions

The document provides an overview of SQL built-in functions, explaining their purpose and categorizing them into numeric, string, date, aggregate, and REGEX functions. It highlights the vendor-specific nature of these functions across different database management systems (DBMS) and includes examples of various functions and their implementations. Additionally, it discusses the nesting of functions and the use of the CASE expression for conditional processing in SQL statements.

Uploaded by

jmrobison5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Built in Functions

The document provides an overview of SQL built-in functions, explaining their purpose and categorizing them into numeric, string, date, aggregate, and REGEX functions. It highlights the vendor-specific nature of these functions across different database management systems (DBMS) and includes examples of various functions and their implementations. Additionally, it discusses the nesting of functions and the use of the CASE expression for conditional processing in SQL statements.

Uploaded by

jmrobison5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

SQL Built-in Functions

SQL Built-in Functions

What are Functions?

Like most programming languages, SQL supports the use of functions to manipulate data.
Functions are operations that are usually performed on data to facilitate conversion and other
manipulation.

Think of SQL functions as tools designed to accomplish well defined tasks. For example, calculating
square root, or converting lowercase characters to uppercase. You invoke a function within SQL
query by name. Some functions take parameters, (also known as arguments) and some do not.
If a function requires parameters, they must be passed by placing them as a comma separated list
within parenthesis. Once the function performs its task, the function returns a value which is the
result of the execution of that function.

Functions are not standard

Unlike the base SQL statements, which for the most part are standard and are supported equally by
most DBMS. Most functions tend to be very DBMS vendor specific. In fact very few functions
are supported identically by all major vendors. Although all vendors provide functions that have
the same functionalities, vendor specific implementations of those functions tend to vary between
one vendor and another. .
Here is an example of some functions and vendor implementations:

Function Vendor Implementation

Extract part of a string SUBSTR( ) MySQL, Oracle, PostgreSQL, SQLite


SUBSTRING( ) SQL Server
MID( ) Microsoft Access

Obtain current date/time NOW( ) MySQL, Microsoft Access


SYSDATE Oracle
GETDATE( ) SQL Server

Type of Functions

Numeric functions – Functions that work on numeric columns or values that are numbers.
String functions – Functions that work on textual/descriptive columns or values that are text.
Date functions – Functions that deal with date and time
Aggregate functions – Functions that allow you to sum, count average, etc.
REGEX functions – Functions that allow you to perform granular text searching/matching

Property of: Sam Sultan © Page 1 of 29


SQL Built-in Functions

I - Numeric Functions

Most DBMS provide functions to enable you to perform mathematical operations on numerical
data. These functions usually take one or more numeric parameters, and return a single numeric
value.

Note: To read the function list below, read the line that represents the DBMS you are interested in.
If there is no corresponding function on the same line, then the function is the same as the
line above..

Some of these functions are:

DBMS Function Description

MySQL: ABS(number) Returns the absolute value of the


Oracle: given. That is the value without the
SQL Server: sign.
PostgreSQL:
MySQL: SIGN(number) Returns –1 if the number is negative,
Oracle: 0 if the number is zero,
SQL Server: 1 if the number is positive
PostgreSQL:
MySQL: CEIL(number) Round the number up to the next
Oracle: CEIL(number) whole number.
SQL Server: CEILING(number)
PostgreSQL: CEIL(number)
MySQL: FLOOR(number) Round the number down to the
Oracle: previous whole number.
SQL Server:
PostgreSQL:
MySQL: ROUND(number, dec_places) Round the number to the specified
Oracle: number of decimal places.
SQL Server: If decimal places is not specified,
PostgreSQL: round to the nearest whole number.
SQLite
MySQL: TRUNCATE(number, dec_places) Truncate the number to the specified
Oracle: TRUNC(number, dec_places) number of decimal places.
SQL Server: n/a
PostgreSQL: TRUNC(number, dec_places)
MySQL: POWER(number, exp) Raise the number to the power of the
Oracle: exponent.
SQL Server
PostgreSQL:
MySQL: SQRT(number) Return the square root of the number.
Oracle:
SQL Server:
PostgreSQL:

Property of: Sam Sultan © Page 2 of 29


SQL Built-in Functions

DBMS Function Description


MySQL: MOD(num1, num2) Return the modulus (the remainder of)
Oracle: an integer division of num1 by num2
SQL Server: (In MySql and SQL Server you can
PostgreSQL: also use % operator)
MySQL: RAND(seed) Returns a random decimal number
Oracle: --- between 0 and .99999999
SQL Server: RAND( ) If the seed is specified, the sequence
PostgreSQL: RANDOM( ) of random numbers generated will be
SQLite RANDOM( ) repeatable.
For Oracle, must use PL/SQL
MySQL: FORMAT(number, dec_ place) Returns the value rounded and
(only) formatted with commas as: 9,999.99
Oracle: TO_CHAR(number, ‘format’) Returns the value rounded and
(only) formatted as per the given format
you can use the characters $ 9 0 , .
(see example below)

Examples:
SELECT course_id, price, CEIL(price * 1.05)
FROM course

SELECT course_id, price, FLOOR(price * 1.05), description


FROM course

SELECT course_id, price, ROUND(price * 1.05, 2)


FROM course

SELECT course_id, price, TRUNCATE(price * 1.05, 2) /* for Oracle use */


FROM course /* TRUNC(..) */

SELECT student_id, POWER(student_id, 2), POWER(2, 8)


FROM student

SELECT student_id, SQRT(student_id)


FROM student

SELECT student_id, MOD(student_id, 2) AS "odd or even" /*MySql only */


FROM student /*the remainder of 2 */

SELECT RAND( ) /*MySql generate */


FROM student /*a random number */

SELECT FORMAT(amount*1.05, 2) /* MySql 1,356.24 */


FROM payment

SELECT TO_CHAR(amount*1.05, '9,999,999.99') /* Oracle 1,356.24 */


FROM payment

Property of: Sam Sultan © Page 3 of 29


SQL Built-in Functions

II - String Functions

Most DBMS provide many functions to enable you to work with, manipulate, and convert
character text strings. These functions are very flexible and powerful, and allow you to mold your
data to the specific look that you require. Some of these are…

DBMS Function Description


MySQL: CONCAT(string1, string2,…) Concatenate multiple strings together,
Oracle: CONCAT(string1, string2) or || and return a single string containing all
SQL Server: CONCAT(string1, string2,…) or + the concatenated strings.
PostgreSQL: CONCAT(string1, string2,…) or ||
SQLite: use || In MySQL, you might also use ||
depending on configuration
MySQL: LOWER(string), UPPER(string) Converts the string to lower case or
Oracle: upper case and returns that value.
SQL Server: (in MySQL you can also use
PostgreSQL: LCASE(string) UCASE(string)
SQLite:
MySQL: LENGTH(string) Returns the number of characters within
Oracle: LENGTH (string) the string.
SQL Server: LEN(string) For fixed length CHAR columns:
PostgreSQL LENGTH (string) MySql does not count trailing spaces.
SQLite: LENGTH (string) Oracle counts trailing spaces.
MySQL: LTRIM(string), RTRIM(string) Eliminate all leading (left) spaces or
Oracle: ….or TRIM(string) trailing (right) spaces, or both.
SQL Server:
PostgreSQL:
SQLite:
MySQL: LPAD(string, n, string2) , RPAD Pad the given string starting from the
Oracle: LPAD(string, n, string2) , RPAD leftmost position with string2, and repeat
SQL Server: REPEAT(char, string, n) until entire string is n char long.
PostgreSQL LPAD(string, n, string2) , RPAD Used to right justify numbers.
MySQL: SUBSTR(string, start, length) Extract a substring from the string,
Oracle: SUBSTR(string, start, length) starting from position “start”, and going
SQL Server: SUBSTRING(string, start, length) for the specified “length”.
PostgreSQL SUBSTRING (string, start, length) If length is not specified, then extract to
SQLite: SUBSTR (string, start, length) the end of sting. Counting starts at 1.
MySQL: COALESCE(field1,field2,field3, Return the first field that is not null.
Oracle: …)
SQL Server: (Great tool for selecting the first of many
PostgreSQL optional columns)
SQLite:
MySQL: IFNULL(field1, field2) If field1 is null then return field2
Oracle: NVL(field1, field2) otherwise return field1
SQL Server: ISNULL(field1, field2)
SQLite: IFNULL(field1, field2) (basically a subset of COALESCE)

Property of: Sam Sultan © Page 4 of 29


SQL Built-in Functions

DBMS Function Description


MySQL: GREATEST(col1, col2, col3,…) Return the largest or smallest of the set
Oracle: LEAST(col1, col2, col3,…) of columns or fields.
SQL Server: GREATER(…), LESSER(…) Columns can be numeric or strings
PostgreSQL GREATEST(…), LEAST(…)
Do not confuse with MIN( ) or MAX( ),
(see aggregate functions)
MySQL: LOCATE(value, string, start) Return the position of the first
Oracle: INSTR(string, value, start, n) occurrence (or Oracle nth occurrence) of
SQL Server: PATINDEX(value, string) the value within the given string. The
PostgreSQL POSITION(value IN string) search begins starting at position “start”.
SQLite: INSTR(string, value) If start is not specified, the search begins
at the first character.
(in MySQL you can also use If the value is not found, return 0
INSTR(string, value)
MySQL: REPLACE(string, old, new) Within the string, replace all occurrences
Oracle: of the “old” value with the “new” value.
SQL Server: This replacement is in the output only.
PostgreSQL The table value is not changed.
SQLite:
MySQL: IF(expression, field1, field2) If the expression is true,
then return field1, else return field2
Oracle: DECODE(string, val1, field1, if string = val1 display field1,
(only) val2, field2, … if string = val2 display field2
otherwise_field3) Optionally if given, when no match,
return the otherwise_field
Oracle: TRANSLATE(string, ‘from’, ‘to’) Converts the string one char at a time
(only) using the ‘from’ string, to the ‘to’ string.
This is a good function to scramble data

Examples:
SELECT CONCAT(fname, ' ', lname) AS fullname /* MySql only */
FROM student
/* Oracle only */
SELECT fname || ' ' || lname AS fullname /* Oracle CONCAT( ) */
FROM student /* allows 2 fields only */
SELECT fname, lname, sex FROM instructor /* test the value */
WHERE LOWER(lname) = 'sultan' /* case insensitive */
SELECT description, LENGTH(description), course_id
FROM course
SELECT RTRIM(description), LPAD(price*1.03,10,'$') /* $$$1127.85 */
FROM course
SELECT course_id, SUBSTR(description, 1, 15)
FROM course

Property of: Sam Sultan © Page 5 of 29


SQL Built-in Functions

SELECT description, INSTR(description, 'Dev') # the position where found


FROM course # or if not found, show 0
SELECT vendor, description, IFNULL(amount, 0) FROM payment /* MySql only */
SELECT vendor, description, NVL(amount, 0) FROM payment /* Oracle only */
SELECT course_id, description, REPLACE(description, 'XML', 'SQL')
FROM course
SELECT sex, IF(sex='M', 'male', 'female'), fname /* MySql only */
FROM student
SELECT sex, DECODE(sex, 'M', 'male', 'F', 'female'), fname /* Oracle only */
FROM student

Nesting Functions

You can always nest one function within another. This allows you to build very sophisticated
capabilities to achieve the desired results. When nesting functions, the entire inner function
including all of its parameters will typically replace a single parameter of the outer function.

When nesting functions, you will use multiple sets of parenthesis.


Examples:
SELECT student_id, SUBSTR( CONCAT(lname, fname), 1, 20)
FROM student
In the above example, we are first concatenating last name, and first name together.
Subsequently, we are taking a substring of the resulting string starting at position 1 for the
length of 20 characters.

SELECT course_id, SUBSTR( description, LENGTH(description) -5)


FROM course
In the above example, we first obtain the length of the course description. Subsequently,
we take the substring of the course description starting at position length - 5, going to the
end of the description (Notice there was. no 3rd argument for substring function).
SELECT CONCAT( '$', FORMAT(price,2) ) FROM course --MySql only
SELECT REPLACE( REPLACE(sex,'M','male'), 'F','female') FROM student
SELECT lname, IF(sex='M', IF(lname LIKE 'R%', 'male with R last name', 'male'), 'female')
AS gender
FROM student --MySql only

Property of: Sam Sultan © Page 6 of 29


SQL Built-in Functions

As you can see, you can develop very sophisticated capabilities by nesting one SQL function within
another function. There is no limit to the number of nested functions you can have. When nesting
functions, be careful to use the correct punctuation (parenthesis, commas, etc.) for each function.
The CASE Expression

CASE expression is often over-looked but can be extremely useful to change very complex query
requirements into simpler, and sometimes more efficient SQL statements.

The CASE expression enables many forms of conditional processing to be placed into a SQL
statement. By using CASE, more logic can be placed into SQL statements instead of being
expressed in a host language such as Java, Python, PHP, etc.

The CASE expression can be syntactically written in one of two styles:

STYLE 1: Simple Case - CASE <column or expression> WHEN … … END

SELECT fname, lname,


CASE sex
WHEN 'M' THEN 'Male'
WHEN 'F' THEN 'Female'
ELSE 'Unknown' --optional ELSE
END as gender
FROM student

fname lname gender


Barbara Burns Female
Vincent Cambria Male
Duncan Davidson Male
… … …

STYLE 2: Searched Case - CASE WHEN <column or expression> … … END

SELECT fname, lname, description,


CASE
WHEN sex='M' and description like '%SQL%' THEN 'SQL/Male'
WHEN sex='F' and description like '%SQL%' THEN 'SQL/Female'
ELSE '--'
END as "skills/gender"
FROM student s, class c, course co
WHERE ssn=stu_ssn
AND c.course_id= co.course_id

fname lname description skills/gender


Vincent Cambria Web Page Development with HTML --
Vincent Cambria SQL Programming Language SQL/Male

Property of: Sam Sultan © Page 7 of 29


SQL Built-in Functions

Cynthia Owens JavaScript --


Cynthia Owens SQL Programming Language SQL/Female
Rick Myers PL/SQL SQL/Male
Another CASE Example

SELECT c.course_id ,
CASE s.sex
WHEN 'M' THEN concat(s.fname, s.lname)
ELSE null -- ELSE null is not needed
END as "Male" , -- but trying to make a point
CASE s.sex
WHEN 'F' THEN concat(s.fname, s.lname)
END as "Female" ,
sex
FROM class c, student s
WHERE c.stu_ssn = s.ssn

Course_id Male Female Sex


X52-9759 BarbaraBurns F
X52-9740 BarbaraBurns F
X52-9272 VincentCambria M
X52-9759 EugeneThomas M
X52-9272 CynthiaOwens F

Maybe separate the debits from the credits in a financial report.

Nested CASE Example

SELECT course_id, description, price,


CASE
WHEN price < 1000 THEN
case
when description like '%Dev%' then 'cheap development course'
when description like '%Java%' then 'cheap Java course'
else 'cheap course'
end
WHEN price < 2000 THEN
case
when description like '%Dev%' then 'moderately priced development course'
when description like '%Java%' then 'moderately priced Java course'
else 'moderately priced course'
end

Property of: Sam Sultan © Page 8 of 29


SQL Built-in Functions

ELSE 'expensive'
END as "case results"
FROM course

Can I use a column alias on the SELECT or WHERE clause? (Self Reading)

You are always free to assign an alias to a column. This is often useful when the column is a
derived column which is a result of a function or case expression. The column alias will be used
as the column header for the resulting output.

In most databases, including Oracle and MySQL, you cannot reuse the alias on the SELECT or
in the WHERE clause. The aliased name is not known yet. As such, if you want to filter your
rows by the resulting value of the function or case expression, you must repeat the code of that
function or case expression in the SELECT or WHERE clause.

Examples:
SELECT description, price, price*1.05 AS new_price, ROUND(new_price, 2)
FROM course

SELECT course_id, description, price, FLOOR( price * 1.05) AS new_price


FROM course
WHERE new_price > 1000

Mysql ERROR 1054: Unknown column 'new_price' in 'where clause'

Oracle: ORA-00904: "NEW_PRICE": invalid identifier

Change the above to:


SELECT description, price, price*1.05 AS new_price, ROUND(price*1.05, 2)
FROM course

SELECT course_id, description, price, FLOOR( price * 1.05) AS new_price


FROM course
WHERE FLOOR( price * 1.05) > 1000 #must repeat the function

Another Example (using CASE):


SELECT fname, lname, ssn,
CASE sex WHEN 'M' THEN 'male' WHEN 'F' THEN 'female' END as gender
FROM student
WHERE (CASE sex WHEN 'M' THEN 'Male' WHEN 'F' THEN 'Female' END) = 'male'

FNAME LNAME SSN GENDER


Vincent Cambria 000-01-0002 Male
Duncan Davidson 000-01-0003 Male

Property of: Sam Sultan © Page 9 of 29


SQL Built-in Functions

David Smith 000-01-0004 Male


… … … …

I optionally placed the above CASE expression is parenthesis to help readability and code isolation.

Property of: Sam Sultan © Page 10 of 29


SQL Built-in Functions

III - Date Functions

Most DBMS provide functions to allow you to obtain the current date and time from the DBMS,
and to enable you to work with and perform various manipulations for date and time.

Most Databases use a different format for date & time, and also use different functions to
manipulate such dates and times. However, although most DBMS provide different date/time
functions, they all provide common functionalities for the manipulation of dates and times.

Date and time are stored using date datatypes, and each DBMS uses its own special format.
Date and time values are stored in special formats so that they can be sorted, filtered and
computed quickly and efficiently, and to save space internally.

The format used to store dates and times are usually of no consequence to you, and so date and time
functions are almost always used to read, extract, expand, and manipulate these dates and times.
These functions are crucial to your application if you need to deal with dates as most applications do.
Unfortunately, these functions tend to be least consistent between one DBMS and another.

Dates in MySQL:

 To get the current date and time use: NOW( )

 The default date display is: YYYY-MM-DD HH:MM:SS


To display the date in any other format, you can use the DATE_FORMAT( ) function.

 To enter a date, use the same format: YYYY-MM-DD HH:MM:SS


You can enter the year as YYYY or YY. You can enter the date with or without the time.
If you want to enter a date in any other format, you use the STR_TO_DATE( ) function.

Some of the date functions in MySQL are:

Function Description

NOW( ) Returns the current date and time as


SYSDATE( ) YYYY-MM-DD HH:MM:SS.
LOCALTIME( )
LOCALTIMESTAMP( )
CURRENT_TIMESTAMP( )
CURDATE( ) Return the current date in
CURRENT_DATE( ) YYYY-MM-DD format.
CURTIME( ) Return the current time in
CURRENT_TIME( ) HH:MM:SS format.
UTC_TIMESTAMP( ) Returns the GMT date and time
YEAR(date) Returns the year of a given date.
Property of: Sam Sultan © Page 11 of 29
SQL Built-in Functions

MONTH(date) Returns the month number for a given date.

MONTHNAME(date) Returns the month name for a given date.

DAY(date) Returns the day number of a given date.


DAYOFMONTH(date)
DAYNAME(date) Returns the day name for a given date.

DAYOFWEEK(date) Returns the day number within the week


as: 1-Sunday, 2-Monday, … 7-Saturday
DAYOFYEAR(date) Returns the Julian day for a given date.

HOUR(date) Returns the hours, minutes, or seconds for


MINUTE(date) the given date
SECOND(date)
DATE(date) Returns the date portion of a date
YYYY-MM-DD
TIME(date) Returns the time portion of a date
HH-MI-SS
LAST_DAY(date) Returns the last day of the month for a
given date. Example January  31
TIMESTAMPADD(unit, n, date) Add / subtract n units of hours, days,
months, years, etc. to the given date

Similarly: n  positive or negative integer only


DATE_ADD(date, INTERVAL n unit)
DATE_SUB(date, INTERVAL n unit) Units are:
YEAR, QUARTER, MONTH, WEEK,
DAY, HOUR, MINUTE, SECOND
(upper or lower case)
TIMESTAMPDIFF(unit, date1,date2) Subtract date2 – date1 and return the
number of hours, days, months, etc. units.
Similarly:
DATEDIFF(date2, date1) Units are:
YEAR, QUARTER, MONTH, WEEK,
PS. DATEDIFF returns DAY unit only DAY, HOUR, MINUTE, SECOND
(upper or lower case. No quotes)
UNIX_TIMESTAMP(date) Returns the number of seconds since
'1970-01-01 00:00:00'
and the reverse
FROM_UNIXTIME(string) This allows you to add and subtract the
date using normal mathematical operations.

Property of: Sam Sultan © Page 12 of 29


SQL Built-in Functions

DATE_FORMAT(date, 'format') Format a date using the given format.

%d – numeric day of month (01-31)


%e – numeric day of month (1-31)
%m – numeric month (01-12)
%c – numeric month (1-12)
%Y – year in 4 digit format
%y – year in 2 digit format
%H – hour in 24 hour clock (00-23)
%h – hour in 12 hour clock (01-12)
%i – minutes (00-59)
%s – seconds (00-59)
%p – AM or PM
%D – day of the month as 1st, 2nd, 3rd,..
%j – Julian day of the year (001-366)
%a – abbreviated day name (Sun, Mon…)
%W – full day name (Sunday, …)
%w – day of the week (0-6) 0=Sunday
%b – abbreviated month name (Jan, …)
%M – full month name (January, …)
%f – microseconds (000000-999999)
%r – time in 12 hour clock with AM/PM
%T – time in 24 hour clock
etc.

Any other character in the format string


including spaces will be displayed as is.
STR_TO_DATE(string, 'format') Convert a string to a date using the
specified format

(see the list above for possible formats)

What about Time Zone?

To obtain the time zone offset between the local time and the GMT time, simply subtract NOW( )
from UTC_TIMESTAMP( )

SELECT TIMESTAMPDIFF(hour, UTC_TIMESTAMP( ), NOW( ) )

Result: -5 //we are 5 hours behind


//GMT time zone

Property of: Sam Sultan © Page 13 of 29


SQL Built-in Functions

Examples:

SELECT NOW( ), CURRENT_DATE, CURRENT_TIME

Result: 2024-06-23 13:47:17 2024-06-23 13:47:17

SELECT YEAR(pay_date), MONTH(pay_date), DAY(pay_date)


FROM payment

SELECT MONTHNAME(NOW( )), DAYNAME('1776-07-04')

Result: June Thursday

SELECT DAYOFYEAR(NOW( )), DAYOFMONTH(NOW( )), DAYOFWEEK(NOW( ))

Result: 176 24 2 # 176 is Julian day


# 1-Sun, 2-Mon, 3-Tue, … 7-Sat

SELECT HOUR(NOW( )), MINUTE(NOW( )), SECOND(NOW( ))

Result: 13 47 17

SELECT LAST_DAY('2024-02-01'), LAST_DAY('2025-02-19')

Result: 2024-02-29 2025-02-28

SELECT TIMESTAMPADD( DAY, 20, NOW( ) ) # today + 20 days

SELECT TIMESTAMPADD( HOUR, -24, NOW( ) ) # today -24 hours


# notice minus

SELECT TIMESTAMPDIFF( hour, NOW( ) , '2024-01-01 00:00:00')

Result: -4210 # hours between

SELECT DATE_FORMAT( NOW( ), '%W, %M %e %Y')

Result: Sunday, June 23 2024 # notice the spacing


# and punctuation

SELECT STR_TO_DATE('May 12, 2024 5:30:15', '%M %e, %Y %h:%i:%s')

Result: 2024-05-12 05:30:15

Please note: If a function takes a date or time argument, a datetime type can also be given.

Property of: Sam Sultan © Page 14 of 29


SQL Built-in Functions

Dates in Oracle:

 To get the current date and time use: SYSDATE

 The default date display is: DD-MON-YY (example: 11-JUN-24 )


However, your installation may vary depending on installation configuration
To display the date in any other format, including the time portion, use the TO_CHAR( ) function

 To enter a date, use: DD-MON-YY (or YYYY) (example '12-apr-24' )


If you want to enter a date in any other format, including the ability to enter a time component,
you must use the TO_DATE( ) function.

Some of the date functions in Oracle are:

Function Description

SYSDATE Returns the current date and time in format:


DD-MON-YY
or other format depending on DB configuration.
The format may be missing the time component.
LAST_DAY(date) Returns the last day of the month for a given date.

e.g. LAST_DAY('01-feb-24')  29-FEB-24


MONTHS_BETWEEN(date1, date2) Return the number of months (or partial months)
between the given 2 dates
As per: date1 – date2
ADD_MONTHS(date, number) Add a specified number of months to the given
date
e.g. ADD_MONTHS(sysdate, 4)
NEXT_DAY(date, ‘day_name’) Returns the next day requested starting from the
given date
Example: NEXT_DAY(sysdate, 'monday')
Returns the next Monday from today
TRUNC(date) Without a unit, the time portion is truncated
TRUNC(date, unit)
With a unit, all lesser units are truncated
Units are: Example: TRUNC(sysdate, 'MM')
YY, MM, DD, HH, MI Returns the first day of the month for that date
ROUND(date) Without a unit, the time portion is rounded.
ROUND(date, unit) If the time is in the PM then you get next day.
With a unit, all lesser units are rounded
Units are: Example: ROUND(sysdate, 'MM')
YY, MM, DD, HH, MI Returns the first day of current or next month
depending on the day being 01-15 vs. 16-31.

Property of: Sam Sultan © Page 15 of 29


SQL Built-in Functions

+ and - You can use the plus and minus operators to add
and subtract dates.
(add and subtract) Values are always in full and fraction of days
TO_CHAR(date, 'format') Convert a date to a string using the any of
the following formats:

formats are case sensitive, DD - 2 digit day (01-31))


DY - 3 char abbrv. day name (Sun, …)
Example: DAY - full day name (Sunday, …)
MONTH  JANUARY D - number of day within the week (1-7)
Month  January DDD - . Julian day of the year (001-366)
month  january WW - the week of the year (01-52)
MM - 2 digit month (01-12)
MON - 3 char abbrv. month name (JAN,…)
MONTH - full month name (JANUARY,…)
YY - 2 digit year
YYYY - 4 digit year
YEAR - the year in words
HH - the hour portion of time (01-12)
HH24 - hour portion of time (00-23)
MI - the minutes portion of time (00-59)
SS - the seconds portion of time (00-59)
AM - display AM/PM
CC - the century
Q - the quarter
Any other punctuation in the format string
including spaces will be displayed as is.
TO_DATE(string, 'format') Convert a string to a date using the specified
format
(see the list above for possible formats)
SESSIONTIMEZONE Get the time zone GMT offset for the current
database session.

Example:
SELECT SYSDATE, TO_CHAR(sysdate, 'mm/dd/yy hh :mi:ss am') -- Display date.
FROM dual -- to display the time
-- you must use to_char( )
Result: 12-JUN-24 06/12/24 01:07:14 pm

From dual ?
Oracle has a dummy table called DUAL. This table is used whenever you need to a retrieve system
information. The table has a single column called “DUMMY” with a single row containing “X”.
The purpose of this table is to allow you to retrieve a single row, and to complete the SELECT
statement with the required FROM clause. Other databases may not require a FROM clause.

Property of: Sam Sultan © Page 16 of 29


SQL Built-in Functions

Examples:
SELECT SYSDATE, SESSIONTIMEZONE FROM dual
Result: 12-JUN-24 -04:00 -- today and time zone

SELECT MONTHS_BETWEEN(sysdate, '01-Jan-2024') -- date format standard


FROM dual

SELECT MONTHS_BETWEEN(sysdate, TO_DATE('07/04/1776', 'mm/dd/yyyy') )


FROM dual
Result: 2975.3926

SELECT ADD_MONTHS('31-MAR-2023', -1) FROM dual -- subtract 1 month


Result: 28-FEB-23 -- notice 28 not 31

SELECT LAST_DAY('01-FEB-2024'), LAST_DAY('15-FEB-2025')


FROM dual
Result: 29-FEB-24 28-FEB-25

SELECT TO_CHAR(sysdate, 'Day, mm/dd/yy hh:mi:ss') -- Convert a date to string.


FROM dual -- punctuation, spaces & case
-- are preserved as entered
Result: Sunday, 06/13/24 08:38:32

SELECT TO_DATE('2024/10/4 11:21 ', 'yyyy/mm/dd hh:mi') -- Convert a string to date


FROM dual
Result: 04-OCT-24 -- where is the time component?
-- you must use TO_CHAR(…)

SELECT sysdate + 20, sysdate - 6.5/24 -- Add 20 days, Subtract 6.5 hours
From dual

SELECT sysdate - TO_DATE('04-JUL-1776') -- must use TO_DATE( )


FROM dual -- between now and end-of-year
Result: 90570.544 -- notice fraction of days

SELECT sysdate - 6.5/24, TO_CHAR(sysdate - 6.5/24, 'dd-Mon-yy hh:mi:ss')


FROM dual
-- Subtract 6.5 hours
Result: 12-JUN-24 12-Jun-24 01:29:13 -- to display time, use to_char( )

SELECT to_char( to_date('11/09/24 05:30', 'mm/dd/yy hh:mi') + 5/24, 'yyyy/mm/dd hh:mi:ss')


FROM dual
-- add 5 hours to a given date
Result: 2024/11/09 10:30:00 -- nested functions
Property of: Sam Sultan © Page 17 of 29
SQL Built-in Functions

Dates in Other Databases:

See appendix (page 23) for date functions using…

 PostgreSQL
 SQLite
 MS SQL Server

Property of: Sam Sultan © Page 18 of 29


SQL Built-in Functions

IV - Aggregate Functions
We will discuss aggregate functions including the list below in a future session.

For the most part, most aggregate functions tend to be standard between implementations of
various DBMS.

Aggregate functions are often used in conjunction with the GROUP BY clause.

Function Description
SUM(column) Total the values for all (or some) of the instances for the
specified numeric column.
COUNT(column) Count the number of occurrences for all (or some) of the
COUNT(*) instances for the specified column.
COUNT(*) – count entire row
AVG(column) Compute the average of all (or some) the instances of the
specified numeric column.
MIN(column) Return the minimum value of the specified column.
Can also be used for text columns
MAX(column) Return the maximum value of the specified column.
Can also be used for text columns
MEDIAN(column) Return the median (mid-point value) of a numeric column.
- If number of rows is odd, you get the value for the row.
(Oracle only) - If number of rows is even, you get the average of the 2 rows.
GROUP_CONCAT(…) Concatenate all the values of a single (or multiple) columns.
Values are separated with a comma by default
(MySql and SQLite)
LISTAGG(…) Concatenate all the values of a single or multiple columns.
Values are not separated by default
(Oracle only)

Important:

Unlike all functions described previously, where the functions work horizontally within a single
individual row, all of the above aggregate functions work vertically across multiple rows.

We will discuss these aggregate functions next session.

Property of: Sam Sultan © Page 19 of 29


SQL Built-in Functions

V - REGEX Functions (Advanced Class Only)

Most new releases of database engines including both MySql and Oracle support the concept of
Regular Expression (also known as REGEX).

You can use a special regular expression language to construct a pattern which the column value
must match in order to be selected. The regex language is based on the Perl regular expression
language. It is a very sophisticated mechanism that allows you to create detail patterns that text
content or column values must match in order to be accepted.

As you recall, you can use the LIKE command to test whether a column value matches (or does not
match) a given pattern. The pattern is typically made up of any character, as well as 2 special
wildcard characters % and _

Using REGEX is similar to using the LIKE command, except that regex offers us a much wider and
broader set of wildcard and meta-characters, and allows us to define more complex patterns.

Using MySQL:
MySql implemented regex by providing a comparison operator called RLIKE, also called REGEXP.
You can use the operator exactly as you would use the LIKE operator.
Examples:
select * from course --or you can use REGEXP
where description RLIKE '^java' --starts with java

select description, description REGEXP 'java$' --ends with java


from course --returns 0 or 1 for each row
--0 means no match, 1 match

Using ORACLE:
Oracle implemented regex functionality by providing a few new regex functions, mainly:

REGEXP_LIKE(string, regex, mode) Allows you to find a regex pattern in a string value
Mode is 'i' for case insensitive. Default 'c' case sensitive.
REGEXP_REPLACE(string, regex, replacement, position, occurrence, mode)
Find a pattern, and replace what is found with the replacement string value
Position allows you to specify a starting position. Default is position 1.
Occurrence allows you to specify which occurrence to replace. Default is 0 (all).
Examples:
select * from course
where REGEXP_LIKE(description, '^java', 'i' ) --starts with java

select description, REGEXP_REPLACE(description, 'java$', 'Coffee',1, 0, 'i' )


from course
Property of: Sam Sultan © Page 20 of 29
SQL Built-in Functions

The REGEX Meta Characters

Meta Character Description


Any character Matches itself
. (a dot) A wildcard that matches any single character
\d Matches any digit 0-9
\D Matches any character that excluding 0-9
\w Matches any character in the range a-z, A-Z, 0-9, and underscore
\W Matches any character excluding a-z, A-Z, 0-9, and underscore
\s Matches any white space including space, tab, newline, form feed, etc.
\S Matches any character excluding white space
\b Matches at a word boundary
Example: \bscore\b matches score but not scores or underscore
\B Matches content but not a word boundary
Example: \Bscore matches underscore but not score or scores
? The previous character must exist 0 or 1 time
Example: a? matches 'a' or nothing at all
* The previous character must exist 0 or more times
Example: a* matches a, aa, aaa, etc. as well as nothing at all.
+ The previous character must exist 1 or more times
Example: a+ matches a, aa, aaa, etc..
*? +? Perform the matching in a non greedy fashion
\char Any meta character can be escaped by using a slash
Example: \. matches a dot. It is no longer used as a wildcard character..
{n} The previous character must exist n times
Example: a{3} matches aaa only
{n.m} The previous character must exist at least n times, but no more than m times
Example: a{3,5} matches aaa, aaaa, aaaaa only
{n.} The previous character must exist at least n times, no upper limit
{,m} The previous character must exist no more than m times, no lower limit
[aeiou] Matches any 1 character from the list of characters enclosed
Example: [abc] matches either a, b or c
[a-z] or Matches any 1 character from the range of characters enclosed
[a-zA-Z0-9] Example: [a-zA-Z0-9] matches any lower/uppercase letter or a number
[^a-z] Matches any 1 character that is not in the range of characters enclosed
Example: [^a-z] matches any non-lowercase letter
^ Matches the next character at beginning of the string
Example: ^[a-z][0-9] matches any string, must start with alpha, then number
$ Matches the previous character at the end of the string
Example: [a-z][0-9]$ matches any string, must end with alpha, then number
( ) Used for grouping
(A|B) Used for alternatives
Example: gr(a|e)y matches gray or grey

Property of: Sam Sultan © Page 21 of 29


SQL Built-in Functions

REGEX in MySQL

MySql does not support the classes such as \s for any space, \d for digit, \w, \b, etc. Instead,
MySql offers the following meta-character classes as substitute:

Meta Classes Description


[[:digit:]] Numeric digit (Similar to \d)
[[:alnum:]] Alphanumeric character (Similar to \w)
[[:alpha:]] Alphabetic character only
[[:space:]] A space, carriage return, newline, tab, form feed (Similar to \s)
[[:blank:]] A blank space character only
[[:<:]] [[:>:]] Must be on a word boundary (Similar to \b)
[[:print:]] Any printable character
[[:cntrl:]] Control character – non-printable
[[:punct:]] A punctuation character
[[:lower:]] Any lower case alphabetic character
[[:upper:]] Any upper case alphabetic character
[[:xdigit:]] A hexadecimal digit
[[:graph:]] Combination of [[:lower:]], [[:upper:]], [[:digit:]], and [[:punct:]]

 By default, MySql performs regex comparison as case insensitive.


 If you want to perform your REGEX comparison case sensitive, add the keyword BINARY

Regex Pattern Examples:


hello Will match any text that contains ‘hello’
^hello Will match any text that starts with ‘hello’
^hello$ Will match any text that only contains ‘hello’

Regex Examples using MySql:


select * from course
where description RLIKE 'java(script)?' --java or javascript case insensitive

select * from course


where BINARY description RLIKE 'Java(script)?' --Java or Javascript case sensitive

select s.*, case


when email RLIKE '^[[:alnum:]]+(\.[[:alnum:]]+)*@[0-9A-z]+\.[A-z]{2,4}$'
then 'valid'
else 'invalid'
end as "regex test" --see output on next page
from student_email s

Practice with REGEX… (is it a valid SSN?)


select case when '999-99-9999' RLIKE('^[[:digit:]]{3}-[[:digit:]]{2}-[[:digit:]]{4}$')
then 'Valid' else 'Invalid' end as "regex test"

Property of: Sam Sultan © Page 22 of 29


SQL Built-in Functions

REGEX in Oracle

 By default, Oracle performs regex comparison as case sensitive.


 If you want to perform your REGEX comparison using case insensitive compares, add the
mode parameter ‘i’ as part of the regex functions.

Regex Examples using Oracle:

select * from course


where regexp_like(description, 'Java(script)?' ) --Java or Javascript case sensitive

select * from course


where regexp_like(description, 'java(script)?', 'i' ) --java or javascript case insensitive

select * from student


where regexp_like(ssn, '^\d\d\d-\d1-\d{3}5$' ) --an SSN in format: xxx-x1-xxx5

select s.*, case


when regexp_like(email, '^\w+(\.\w+)*@[0-9A-z]+\.[A-z]{2,4}$', 'i' )
then 'valid'
else 'invalid'
end as "regex test"
from student_email s

EMAIL_ID STUDENT_ID EMAIL Regex test


1 1 [email protected] valid
2 2 [email protected] valid
3 3 [email protected] valid
4 3 [email protected] valid
5 5 [email protected] valid
6 8 [email protected] valid
7 8 [email protected] valid
8 8 [email protected] valid
9 12 none invalid
10 15 [email protected] valid

Practice with REGEX… (is it a valid SSN?)

select case
when REGEXP_LIKE('999-99-9999', '^\d\d\d-\d\d-\d{4}$')
then 'Valid' else 'Invalid' end as "regex test"
from dual

Property of: Sam Sultan © Page 23 of 29


SQL Built-in Functions

Appendix (Date Functions in Other DBs)

Dates in PostgreSQL: (Optional Reading)

 To get the current date and time use: NOW( )

 The default date display is: YYYY-MM-DD HH:MM:SS.mil-TZ


To display the date in any other format, you can use the TO_CHAR( ) function.

 To enter a date, use the same format: YYYY-MM-DD HH:MM:SS::timestamp


You can enter the year as YYYY or YY. You can enter the date with or without the time.
If you want to enter a date in any other format, you use the TO_DATE( ) function.

Some of the date functions in PostgreSQL are:

Function Description

NOW( ) Returns the current date and time as


YYYY-MM-DD HH:MM:SS.mil-TZ
CURRENT_DATE Return the current date in
YYYY-MM-DD format.
CURRENT_TIME Return the current time in
HH:MM:SS.mil-TZ.
::DATE Cast a string to a date
select '2025-3-15'::DATE
::TIMESTAMP Cast a string to a timestamp
select '2025-3-15 6:30:10 '::TIMESTAMP
INTERVAL Add or subtract an interval to a date
Intervals are:
year, month, week, day, hour, minute, second
select now( ) + INTERVAL '1 day'
EXTRACT(‘format’ FROM date) Extract part of a date
select EXTRACT ( 'year' FROM now( ))
DATE_PART (date, ‘format’) or
select DATE_PART(now( ), 'month')
AGE Compute the difference between 2 dates
select AGE(current_date, '2024-12-31')
+/- Allows you to perform date calculation
Add/subtract dates:
select now( ) + interval '1 year'
Interval between dates:
select current_date - '2025-01-01'::date

Property of: Sam Sultan © Page 24 of 29


SQL Built-in Functions

TO_CHAR(date, 'format') Format a date using the given format.

yyyy – year 4 digit


yy – year 2 digit
mm – numeric month (01-12)
dd – numeric day (01-31)
ddd – Julian day
d – day of the week (1-7) 1=Sun
hh – hour of the day
hh24 – hour using 24hour clock
mi – minutes
ss – seconds
ms – milliseconds
AM – AM or PM
TZ – timezone
Month – month name – case sensitive
Mon – month name (abbrev 3 char only)
Day – day name – case sensitive
Dy – day name (abbrev 3 char only)
etc.
Any other character in the format string
including spaces will be displayed as is.
TO_DATE(string, 'format') Convert a string to a date using the
specified format
(see the list above for possible formats)

Examples:

SELECT NOW( ), CURRENT_DATE, CURRENT_TIME


Result: 2025-02-27 14:47:17.6357-05 2025-02-27 14:47:17.6357-05

SELECT TO_CHAR(now( ), 'Month, Dy. mm/dd/yyyy @ hh:mi:ss AM')


Result: February, Thu. 02/27/2025 @ 02:46:41 PM

SELECT TO_DATE( '02/27/2025', 'mm/dd/yyyy');


Result: 2025-02-27 //proper postgresql date

SELECT '2025-01-01'::DATE - '2024-01-01'::DATE


Result: 366

SELECT '2025-01-01 01:01:01'::TIMESTAMP + INTERVAL '+100 minute'


Result: '2025-01-01 02:41:01'

Property of: Sam Sultan © Page 25 of 29


SQL Built-in Functions

Dates in SQLite: (Optional Reading)

 To get the current GMT date and time use: DATETIME( )


 To get the current Local date and time use: DATETIME( 'now', 'localtime' )

 The default date display is: YYYY-MM-DD HH:MM:SS


To display the date in any other format, you can use the STRFTIME( ) function

 To enter a date, use the same format: YYYY-MM-DD HH:MM:SS


You can enter the date with or without the time component.

Some of the date functions in SQLite are:

Function Description

DATETIME(date, ‘modifiers’) Returns the date and time as


YYYY-MM-DD HH:MM:SS.
Without the date, you get GMT date/time.
To get local date/time, use:
DATETIME(‘now’, ‘localtime’)
You can supply any date/time in format:
YYYY-MM-DD HH:MM:SS
You can supply one or multiple modifiers:
‘now’ - current date/time in
GMT
‘utc’ - use GMT
‘localtime’ - use localtime
‘start of day’ - 00:00:00 hour of day
‘start of month’ - first day of the
month
‘start of year’ - first day of the year
‘n day’ - add/sub n number of
days
‘n hour’ - add/sub n hours
‘n minute’ - add/sub n minutes
‘n month’ - add/sub n months
‘n year’ - add/sub n years

DATE(date, ‘modifiers’) Returns the date or the time as


YYYY-MM-DD or HH:MM:SS.
TIME(date, ‘modifiers’)
Parameters, same as above

Property of: Sam Sultan © Page 26 of 29


SQL Built-in Functions

JULIANDAY(date, ‘modifiers’) Returns the number of days since


Nov 24, 4714 BC
Function can be used to subtract dates
STRFTIME('format', date) Format a date using the given format.
%d – numeric day of month (01-31)
%m – numeric month (01-12)
%Y – year in 4 digit format
%H – hour in 24 hour clock (00-23)
%M – minutes (00-59)
%S – seconds (00-59)
%f – seconds & fraction of sec (00-999)
%j – Julian day of the year (001-366)
%s – number of seconds since EPOCH
%w – day of the week (0-6) 0=Sunday
%W – week of the year
Any other character in the format string
including spaces will be displayed as is.

To get day name:


SELECT CASE strftime( '%w', 'now', 'localtime')
WHEN '0' then 'Sunday'
WHEN '1' then 'Monday'
WHEN '2' then 'Tuesday'
WHEN '3' then 'Wednesday'
WHEN '4' then 'Thursday'
WHEN '5' then 'Friday'
WHEN '6' then 'Saturday'
END as day_of_week

To get the month name:


SELECT CASE strftime( '%m', '2024-02-14' )
WHEN '01' then 'January'
WHEN '02' then 'February'
etc.
WHEN '12' then 'December'
END as day_of_week

To get AM/PM:
SELECT CASE WHEN strftime( '%H', 'now', 'localtime') < '12' THEN 'AM'
ELSE 'PM'
END as "AM/PM"

Property of: Sam Sultan © Page 27 of 29


SQL Built-in Functions

Examples:

SELECT DATETIME( ), DATE( ), TIME( )

Result: 2024-06-12 13:47:17 2024-06-12 13:47:17 //current GMT time

SELECT DATETIME('now', 'localtime')

Result: 2024-06-12 11:47:17 //current localtime

SELECT DATETIME('2024-06-12 14:02:03')

Result: 2024-06-12 14:02:03 //any given date/time

SELECT STRFTIME( '%m/%d/%Y @ %H:%M:%S', 'now')

Result: 06/12/2024 @ 14:02:03 //format m/d/y @ h:m:s

SELECT DATETIME( 'now', 'localtime', '+20 day')

Result: 2024-07-03 16:52:47 //add today + 20 days

SELECT DATETIME( 'now', 'localtime', '-1 year')

Result: 2023-06-12 16:52:47 //sub today -1 year

SELECT JULIANDAY(DATETIME('now')) - JULIANDAY('1776-07-04')

Result: 90570.713958333 //interval of 2 dates

SELECT ( JULIANDAY(DATETIME('now')) - JULIANDAY('1960-03-15') ) *24

Result: 4662.805528333 //how old am I in hours

SELECT CASE strftime('%w', 'now', 'localtime')


WHEN '0' then 'Sunday'
WHEN '1' then 'Monday'
WHEN '2' then 'Tuesday'
WHEN '3' then 'Wednesday'
WHEN '4' then 'Thursday'
WHEN '5' then 'Friday'
WHEN '6' then 'Saturday'
END
|| ', ' || strftime('%m/%d/%Y @ %H:%M:%S','now','localtime') AS date_format

Result: Monday, 06/17/2024 @ 20:45:49 //including day name

Property of: Sam Sultan © Page 28 of 29


SQL Built-in Functions

Dates in SQL-Server: (Optional Reading)

 To get the current date and time use: GETDATE( )

 The default date display is: YYYY-MM-DD HH:MI:SS.mil


To display the date in any other format, you can use the CONVERT( ) function

 To enter a date, use the same format: YYYY-MM-DD HH:MI:SS.mil


You can enter the year as YYYY or YY. You can enter the date with or without the time.
If you want to enter a date in any other format, you use the CONVERT( ) function.

CONVERT(to, from, style) Convert any value from one datatype to another.
Can be used with dates using the following styles:

For YYYY add 100, 0, 100 - Mon dd yyyy hh:miAM/PM (default)


1, 101 - mm/dd/yyyy
Example: 2, 102 - yyyy.mm.dd
style 1  mm/dd/yy 3, 103 - dd/mm/yyyy
style 101  mm/dd/yyyy 4, 104 - dd.mm.yyyy
5, 105 - dd-mm-yyyy
6, 106 - dd Mon yyyy
7, 107 - Mon dd yyyy
8 - hh:mi:ss
9 - Mon dd yyyy hh:mi:ss:milAM/PM
10,110 - mm-dd-yyyy
20 - yyyy-mm-dd hh:mi:ss
21 - yyyy-mm-dd hh:mi:ss.mil
etc.

Examples:

SELECT GETDATE( ), GETUTCDATE( )


Result: 2024-03-09 13:12:43.110 2024-03-09 17:12:43.110

SELECT CONVERT( varchar, GETDATE( ), 9)


Result: Mar 9 2024 4:50:28:353PM //format date to string

SELECT CONVERT(datetime, '03/09/2020 13:30:15', 20)


Result: 2024-03-09 13:30:15.000 //convert string to datetime

Property of: Sam Sultan © Page 29 of 29

You might also like