You are on page 1of 2

Standard SQL Functions Cheat Sheet

TEXT FUNCTIONS NUMERIC FUNCTIONS NULLs CASE WHEN


CONCATENATION BASIC OPERATIONS To retrieve all rows with a missing value in the price The basic version of CASE WHEN checks if the values are
column: equal (e.g., if fee is equal to 50, then 'normal' is
Use the || operator to concatenate two strings: Use +, -, *, / to do some basic math. To get the number of
WHERE price IS NULL returned). If there isn't a matching value in the CASE WHEN,
SELECT 'Hi ' || 'there!';
seconds in a week:
then the ELSE value will be returned (e.g., if fee is equal to
-- result: Hi there! SELECT 60 * 60 * 24 * 7; -- result: 604800
To retrieve all rows with the weight column populated: 49, then 'not available' will show up.
Remember that you can concatenate only character strings CASTING WHERE weight IS NOT NULL SELECT

using ||. Use this trick for numbers: CASE fee

From time to time, you need to change the type of a number.


SELECT '' || 4 || 2;
Why shouldn't you use price = NULL or weight != WHEN 50 THEN 'normal'

The CAST() function is there to help you out. It lets you


-- result: 42 NULL? Because databases don't know if those expressions WHEN 10 THEN 'reduced'

change the type of value to almost anything (integer,


are true or false – they are evaluated as NULLs. WHEN 0 THEN 'free'

Some databases implement non-standard solutions for numeric, double precision, varchar, and many
Moreover, if you use a function or concatenation on a column ELSE 'not available'

concatenating strings like CONCAT() or CONCAT_WS(). more).


that is NULL in some rows, then it will get propagated. Take a END AS tariff

Check the documentation for your specific database. Get the number as an integer (without rounding):
look: FROM ticket_types;
SELECT CAST(1234.567 AS integer);

LIKE OPERATOR – PATTERN MATCHING -- result: 1234


domain LENGTH(domain)
The most popular type is the searched CASE WHEN – it lets
Use the _ character to replace any single character. Use the % Change a column type to double precision you pass conditions (as you'd write them in the WHERE
character to replace any number of characters (including 0 SELECT CAST(column AS double precision); LearnSQL.com 12 clause), evaluates them in order, then returns the value for
characters). LearnPython.com 15 the first condition met.

Fetch all names that start with any letter followed by USEFUL FUNCTIONS NULL NULL
SELECT

Get the remainder of a division: CASE

'atherine':
SELECT MOD(13, 2);
vertabelo.com 13 WHEN score >= 90 THEN 'A'

SELECT name

-- result: 1 WHEN score > 60 THEN 'B'

FROM names

ELSE 'F'

WHERE name LIKE '_atherine';


Round a number to its nearest integer: USEFUL FUNCTIONS END AS grade

Fetch all names that end with 'a': SELECT ROUND(1234.56789);


COALESCE(x, y, ...) FROM test_results;
SELECT name
-- result: 1235 To replace NULL in a query with something meaningful: Here, all students who scored at least 90 will get an A, those
FROM names
SELECT
with the score above 60 (and below 90) will get a B, and the
Round a number to three decimal places: domain,

WHERE name LIKE '%a'; rest will receive an F.


SELECT ROUND(1234.56789, 3);
COALESCE(domain, 'domain missing')

USEFUL FUNCTIONS -- result: 1234.568


PostgreSQL requires the first argument to be of the type
FROM contacts; TROUBLESHOOTING
Get the count of characters in a string: Integer division
numeric – cast the number when needed. domain coalesce
SELECT LENGTH('LearnSQL.com');
When you don't see the decimal places you expect, it means
-- result: 12 LearnSQL.com LearnSQL.com that you are dividing between two integers. Cast one to
To round the number up:
Convert all letters to lowercase: SELECT CEIL(13.1); -- result: 14
NULL domain missing decimal:
SELECT LOWER('LEARNSQL.COM');
SELECT CEIL(-13.9); -- result: -13 CAST(123 AS decimal) / 2
The COALESCE() function takes any number of arguments
-- result: learnsql.com The CEIL(x) function returns the smallest integer not less Division by 0
and returns the value of the first argument that isn't NULL.
Convert all letters to uppercase: than x. In SQL Server, the function is called CEILING(). To avoid this error, make sure that the denominator is not
SELECT UPPER('LearnSQL.com');
equal to 0. You can use the NULLIF() function to replace 0
To round the number down: NULLIF(x, y)
-- result: LEARNSQL.COM with a NULL, which will result in a NULL for the whole
SELECT FLOOR(13.8); -- result: 13
To save yourself from division by 0 errors:
expression:
Convert all letters to lowercase and all first letters to SELECT FLOOR(-13.2); -- result: -14 SELECT

count / NULLIF(count_all, 0)
uppercase (not implemented in MySQL and SQL Server): The FLOOR(x) function returns the greatest integer not last_month,

greater than x. this_month,


Inexact calculations
SELECT INITCAP('edgar frank ted cODD');

this_month * 100.0
If you do calculations using real (floating point) numbers,
-- result: Edgar Frank Ted Codd
To round towards 0 irrespective of the sign of a number: / NULLIF(last_month, 0)
you'll end up with some inaccuracies. This is because this
Get just a part of a string: SELECT TRUNC(13.5); -- result: 13
type is meant for scientific calculations such as calculating
AS better_by_percent

SELECT SUBSTRING('LearnSQL.com', 9);


SELECT TRUNC(-13.5); -- result: -13 the velocity. Whenever you need accuracy (such as dealing
FROM video_views;
-- result: .com
TRUNC(x) works the same way as CAST(x AS with monetary values), use the decimal / numeric type (or
SELECT SUBSTRING('LearnSQL.com', 0, 6);
integer). In MySQL, the function is called TRUNCATE(). last_month this_month better_by_percent money if available).
-- result: Learn Errors when rounding with a specified precision
To get the absolute value of a number: 723786 1085679 150.0
Replace part of a string: Most databases won't complain, but do check the
SELECT ABS(-12); -- result: 12 0 178123 NULL
SELECT REPLACE('LearnSQL.com', 'SQL', documentation if they do. For example, if you want to specify
'Python');
To get the square root of a number: The NULLIF(x, y) function will return NULL if x is the the rounding precision in PostgreSQL, the value must be of
-- result: LearnPython.com SELECT SQRT(9); -- result: 3 same as y, else it will return the x value. the numeric type.

LearnSQL.com is owned by Vertabelo SA

Try out the interactive Standard SQL Functions course at LearnSQL.com, and check out our other SQL courses. vertabelo.com | CC BY-NC-ND Vertabelo SA
Standard SQL Functions Cheat Sheet
AGGREGATION AND GROUPING DATE AND TIME INTERVALs TIME ZONES
COUNT(expr) − the count of values for the rows within There are 3 main time-related types: date, time, and Note: In SQL Server, intervals aren't implemented – use the In the SQL Standard, the date type can't have an associated
the group timestamp. Time is expressed using a 24-hour clock, and it DATEADD() and DATEDIFF() functions. time zone, but the time and timestamp types can. In the
SUM(expr) − the sum of values within the group can be as vague as just hour and minutes (e.g., 15:30 – 3:30 real world, time zones have little meaning without the date,
AVG(expr) − the average value for the rows within the p.m.) or as precise as microseconds and time zone (as shown as the offset can vary through the year because of daylight
To get the simplest interval, subtract one time value from
group below): saving time. So, it's best to work with the timestamp
another:
MIN(expr) − the minimum value within the group values.
2021-12-31 14:39:53.662522-05 SELECT CAST('2021-12-31 23:59:59' AS
MAX(expr) − the maximum value within the group When working with the type timestamp with time
date time timestamp) - CAST('2021-06-01 12:00:00' AS
To get the number of rows in the table: timestamp);
zone (abbr. timestamptz), you can type in the value in
timestamp
SELECT COUNT(*)
-- result: 213 days 11:59:59 your local time zone, and it'll get converted to the UTC time
YYYY-mm-dd HH:MM:SS.ssssss±TZ zone as it is inserted into the table. Later when you select
FROM city;
from the table it gets converted back to your local time zone.
14:39:53.662522-05 is almost 2:40 p.m. CDT (e.g., in To define an interval: INTERVAL '1' DAY
To get the number of non-NULL values in a column: This is immune to time zone changes.
Chicago; in UTC it'd be 7:40 p.m.). The letters in the above This syntax consists of three elements: the INTERVAL
SELECT COUNT(rating)

example represent: keyword, a quoted value, and a time part keyword (in AT TIME ZONE
FROM city;
In the date part: In the time part: singular form.) You can use the following time parts: YEAR, To operate between different time zones, use the AT TIME
To get the count of unique values in a column: YYYY – the 4-digit HH – the zero-padded hour in a MONTH, WEEK, DAY, HOUR, MINUTE, and SECOND. In MySQL, ZONE keyword.
SELECT COUNT(DISTINCT country_id)
year. 24-hour clock. omit the quotes. You can join many different INTERVALs
If you use this format: {timestamp without time
FROM city; mm – the zero- MM – the minutes. using the + or - operator:
zone} AT TIME ZONE {time zone}, then the
padded month (01 SS – the seconds. Omissible. INTERVAL '1' YEAR + INTERVAL '3' MONTH
database will read the time stamp in the specified time zone
GROUP BY —January through ssssss – the smaller parts of a and convert it to the time zone local to the display. It returns
CITY 12—December). second – they can be expressed In some databases, there's an easier way to get the above the time in the format timestamp with time zone.
dd – the zero- using 1 to 6 digits. Omissible. value. And it accepts plural forms! INTERVAL '1 year 3
name country_id If you use this format: {timestamp with time zone}
padded day. ±TZ – the timezone. It must months'
Paris 1 start with either + or -, and use AT TIME ZONE {time zone}, then the database will
CITY There are two more syntaxes in the Standard SQL:
two digits relative to UTC. convert the time in one time zone to the target time zone
Marseille 1
country_id count Omissible. Syntax What it does specified by AT TIME ZONE. It returns the time in the
Lyon 1 format timestamp without time zone, in the target
1 3 INTERVAL 'x-y' YEAR INTERVAL 'x year y
Berlin 2 What time is it? time zone.
2 3 To answer that question in SQL, you can use: TO MONTH month'
Hamburg 2 You can define the time zone with popular shortcuts like UTC,
4 2 CURRENT_TIME – to find what time it is. INTERVAL 'x-y' DAY INTERVAL 'x day y
MST, or GMT, or by continent/city such as:
Munich 2 CURRENT_DATE – to get today's date. (GETDATE() in TO SECOND second'
America/New_York, Europe/London, and
Warsaw 4 SQL Server.)
In MySQL, write year_month instead of YEAR TO MONTH Asia/Tokyo.
CURRENT_TIMESTAMP – to get the timestamp with the
Cracow 4 and day_second instead of DAY TO SECOND.
two above. Examples
The example above – the count of cities in each country:
Creating values We set the local time zone to 'America/New_York'.
SELECT name, COUNT(country_id)
To get the last day of a month, add one month and subtract
FROM city
To create a date, time, or timestamp, simply write the SELECT TIMESTAMP '2021-07-16 21:00:00' AT
one day:
GROUP BY name; value as a string and cast it to the proper type. TIME ZONE 'America/Los_Angeles';

SELECT CAST('2021-02-01' AS date)

SELECT CAST('2021-12-31' AS date);


-- result: 2021-07-17 00:00:00-04
The average rating for the city: + INTERVAL '1' MONTH

SELECT CAST('15:31' AS time);

- INTERVAL '1' DAY; Here, the database takes a timestamp without a time zone
SELECT city_id, AVG(rating) SELECT CAST('2021-12-31 23:59:29+02' AS
and it's told it's in Los Angeles time, which is then converted
FROM ratings
timestamp);

to the local time – New York for displaying. This answers the
GROUP BY city_id; SELECT CAST('15:31.124769' AS time); To get all events for next three months from today:
question "At what time should I turn on the TV if the show
Be careful with the last example – it will be interpreted as 15 SELECT event_date, event_name

Common mistake: COUNT(*) and LEFT JOIN starts at 9 PM in Los Angeles?"


minutes 31 seconds and 124769 microseconds! It is always a FROM calendar

When you join the tables like this: client LEFT JOIN
good idea to write 00 explicitly for hours: WHERE event_date BETWEEN CURRENT_DATE AND SELECT TIMESTAMP WITH TIME ZONE '2021-06-
project, and you want to get the number of projects for
'00:15:31.124769'. CURRENT_DATE + INTERVAL '3' MONTH; 20 19:30:00' AT TIME ZONE
every client you know, COUNT(*) will return 1 for each client
even if you've never worked for them. This is because, they're You might skip casting in simple conditions – the database 'Australia/Sydney';

still present in the list but with the NULL in the fields related will know what you mean. To get part of the date: -- result: 2021-06-21 09:30:00
to the project after the JOIN. To get the correct count (0 for SELECT airline, flight_number, SELECT EXTRACT(YEAR FROM birthday)
Here, the database gets a timestamp specified in the local
the clients you've never worked for), count the values in a departure_time
FROM artists; time zone and converts it to the time in Sydney (note that it
column of the other table, e.g., COUNT(project_name). FROM airport_schedule
One of possible returned values: 1946. In SQL Server, use the didn't return a time zone.) This answers the question "What
Check out this exercise to see an example. WHERE departure_time < '12:00'; DATEPART(part, date) function. time is it in Sydney if it's 7:30 PM here?"

LearnSQL.com is owned by Vertabelo SA

Try out the interactive Standard SQL Functions course at LearnSQL.com, and check out our other SQL courses. vertabelo.com | CC BY-NC-ND Vertabelo SA

You might also like