Standard SQL Functions Cheat Sheet Ledger
Standard SQL Functions Cheat Sheet Ledger
using ||. Use this trick for numbers: From time to time, you need to change the type of a number. WHEN 50 THEN 'normal'
SELECT '' || 4 || 2;
The CAST() function is there to help you out. It lets you WHEN 10 THEN 'reduced'
-- result: 42 change the type of value to almost anything (integer, WHEN 0 THEN 'free'
numeric, double precision, varchar, and many Why shouldn't you use price = NULL or weight != ELSE 'not available'
Some databases implement non-standard solutions for more). NULL? Because databases don't know if those expressions END AS tariff
concatenating strings like CONCAT() or CONCAT_WS(). Get the number as an integer (without rounding): are true or false – they are evaluated as NULLs. FROM ticket_types;
Check the documentation for your specific database. SELECT CAST(1234.567 AS integer);
Moreover, if you use a function or concatenation on a column
-- result: 1234 that is NULL in some rows, then it will get propagated. Take a
The most popular type is the searched CASE WHEN – it lets
LIKE OPERATOR – PATTERN MATCHING Change a column type to double precision look:
you pass conditions (as you'd write them in the WHERE
Use the _ character to replace any single character. Use the % SELECT CAST(column AS double precision); clause), evaluates them in order, then returns the value for
domain LENGTH(domain)
character to replace any number of characters (including 0 the first condition met.
characters). LearnSQL.com 12
USEFUL FUNCTIONS SELECT
LearnPython.com 15 CASE
Fetch all names that start with any letter followed by Get the remainder of a division:
NULL NULL WHEN score >= 90 THEN 'A'
SELECT name
-- result: 1 vertabelo.com 13
ELSE 'F'
FROM names
END AS grade
WHERE name LIKE '_atherine'; Round a number to its nearest integer: FROM test_results;
SELECT ROUND(1234.56789);
Here, all students who scored at least 90 will get an A, those
Fetch all names that end with 'a': -- result: 1235 USEFUL FUNCTIONS with the score above 60 (and below 90) will get a B, and the
SELECT name
COALESCE(x, y, ...) rest will receive an F.
FROM names
Round a number to three decimal places: To replace NULL in a query with something meaningful:
WHERE name LIKE '%a'; SELECT ROUND(1234.56789, 3);
SELECT
Integer division
Get the count of characters in a string: numeric – cast the number when needed. FROM contacts;
When you don't see the decimal places you expect, it means
SELECT LENGTH('LearnSQL.com');
that you are dividing between two integers. Cast one to
domain coalesce
-- result: 12 To round the number up: decimal:
LearnSQL.com LearnSQL.com
SELECT CEIL(13.1); -- result: 14
CAST(123 AS decimal) / 2
Convert all letters to lowercase: NULL domain missing
SELECT CEIL(-13.9); -- result: -13
SELECT LOWER('LEARNSQL.COM');
The CEIL(x) function returns the smallest integer not less Division by 0
-- result: learnsql.com The COALESCE() function takes any number of arguments
than x. In SQL Server, the function is called CEILING(). To avoid this error, make sure that the denominator is not
and returns the value of the first argument that isn't NULL.
Convert all letters to uppercase: equal to 0. You can use the NULLIF() function to replace 0
SELECT UPPER('LearnSQL.com');
To round the number down: with a NULL, which will result in a NULL for the whole
-- result: LEARNSQL.COM SELECT FLOOR(13.8); -- result: 13
expression:
SELECT FLOOR(-13.2); -- result: -14 NULLIF(x, y) count / NULLIF(count_all, 0)
Convert all letters to lowercase and all first letters to The FLOOR(x) function returns the greatest integer not To save yourself from division by 0 errors:
uppercase (not implemented in MySQL and SQL Server): greater than x. SELECT
last_month,
Inexact calculations
SELECT INITCAP('edgar frank ted cODD');
this_month,
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:
this_month * 100.0
you'll end up with some inaccuracies. This is because this
SELECT TRUNC(13.5); -- result: 13
type is meant for scientific calculations such as calculating
Get just a part of a string: / NULLIF(last_month, 0)
SELECT TRUNC(-13.5); -- result: -13 the velocity. Whenever you need accuracy (such as dealing
SELECT SUBSTRING('LearnSQL.com', 9);
AS better_by_percent
TRUNC(x) works the same way as CAST(x AS with monetary values), use the decimal / numeric type (or
-- result: .com
FROM video_views;
integer). In MySQL, the function is called TRUNCATE(). money if available).
SELECT SUBSTRING('LearnSQL.com', 0, 6);
To get the number of rows in the table: your local time zone, and it'll get converted to the UTC time
SELECT COUNT(*)
YYYY-mm-dd HH:MM:SS.ssssss±TZ -- result: 213 days 11:59:59 zone as it is inserted into the table. Later when you select
FROM city; 14:39:53.662522-05 is almost 2:40 p.m. CDT (e.g., in from the table it gets converted back to your local time zone.
Chicago; in UTC it'd be 7:40 p.m.). The letters in the above This is immune to time zone changes.
To get the number of non-NULL values in a column: example represent: To define an interval: INTERVAL '1' DAY
SELECT COUNT(rating)
This syntax consists of three elements: the INTERVAL
In the date part: In the time part:
FROM city; keyword, a quoted value, and a time part keyword (in AT TIME ZONE
YYYY – the 4-digit HH – the zero-padded hour in a
singular form.) You can use the following time parts: YEAR, To operate between different time zones, use the AT TIME
year. 24-hour clock.
MONTH, WEEK, DAY, HOUR, MINUTE, and SECOND. In MySQL, ZONE keyword.
To get the count of unique values in a column: mm – the zero- MM – the minutes.
omit the quotes. You can join many different INTERVALs
SELECT COUNT(DISTINCT country_id)
padded month (01 SS – the seconds. Omissible. If you use this format: {timestamp without time
using the + or - operator:
FROM city; —January through ssssss – the smaller parts of a zone} AT TIME ZONE {time zone}, then the
INTERVAL '1' YEAR + INTERVAL '3' MONTH
12—December). second – they can be expressed database will read the time stamp in the specified time zone
dd – the zero- using 1 to 6 digits. Omissible. and convert it to the time zone local to the display. It returns
GROUP BY padded day. ±TZ – the timezone. It must the time in the format timestamp with time zone.
start with either + or -, and use In some databases, there's an easier way to get the above
CITY value. And it accepts plural forms! INTERVAL '1 year 3 If you use this format: {timestamp with time zone}
two digits relative to UTC. AT TIME ZONE {time zone}, then the database will
name country_id Omissible. months'
There are two more syntaxes in the Standard SQL: convert the time in one time zone to the target time zone
Paris 1 specified by AT TIME ZONE. It returns the time in the
CITY
Marseille 1 Syntax What it does format timestamp without time zone, in the target
country_id count What time is it? time zone.
Lyon 1 INTERVAL 'x-y' YEAR INTERVAL 'x year y
1 3 To answer that question in SQL, you can use:
Berlin 2 TO MONTH month' You can define the time zone with popular shortcuts like UTC,
CURRENT_TIME – to find what time it is.
2 3 INTERVAL 'x-y' DAY INTERVAL 'x day y MST, or GMT, or by continent/city such as:
Hamburg 2 CURRENT_DATE – to get today's date. (GETDATE() in
4 2 TO SECOND second' America/New_York, Europe/London, and
SQL Server.)
Munich 2 Asia/Tokyo.
CURRENT_TIMESTAMP – to get the timestamp with the
In MySQL, write year_month instead of YEAR TO MONTH
Warsaw 4 two above.
and day_second instead of DAY TO SECOND.
Cracow 4
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';
The average rating for the city: - INTERVAL '1' DAY; Here, the database takes a timestamp without a time zone
SELECT CAST('2021-12-31 23:59:29+02' AS
SELECT city_id, AVG(rating) and it's told it's in Los Angeles time, which is then converted
timestamp);
FROM ratings
to the local time – New York for displaying. This answers the
SELECT CAST('15:31.124769' AS time);
GROUP BY city_id; 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 To get all events for next three months from today:
starts at 9 PM in Los Angeles?"
minutes 31 seconds and 124769 microseconds! It is always a SELECT event_date, event_name
Common mistake: COUNT(*) and LEFT JOIN good idea to write 00 explicitly for hours: FROM calendar
When you join the tables like this: client LEFT JOIN '00:15:31.124769'. WHERE event_date BETWEEN CURRENT_DATE AND
project, and you want to get the number of projects for CURRENT_DATE + INTERVAL '3' MONTH; SELECT TIMESTAMP WITH TIME ZONE '2021-06-
every client you know, COUNT(*) will return 1 for each client 20 19:30:00' AT TIME ZONE
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?"
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