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

Standard SQL Functions Cheat Sheet Ledger

The document provides a cheat sheet of standard SQL functions organized into categories including text functions, numeric functions, nulls, case when statements, and troubleshooting. Text functions cover concatenation and the like operator. Numeric functions cover basic math operations, casting, rounding, and modulus. Nulls describe how to retrieve rows with null values. Case when shows basic and searched case statements. Useful functions are listed like length, coalesce, and integer division.

Uploaded by

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

Standard SQL Functions Cheat Sheet Ledger

The document provides a cheat sheet of standard SQL functions organized into categories including text functions, numeric functions, nulls, case when statements, and troubleshooting. Text functions cover concatenation and the like operator. Numeric functions cover basic math operations, casting, rounding, and modulus. Nulls describe how to retrieve rows with null values. Case when shows basic and searched case statements. Useful functions are listed like length, coalesce, and integer division.

Uploaded by

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

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 +, -, *, / to do some basic math. To get the number of
Use the || operator to concatenate two strings: WHERE price IS NULL returned). If there isn't a matching value in the CASE WHEN,
seconds in a week:
SELECT 'Hi ' || 'there!';
then the ELSE value will be returned (e.g., if fee is equal to
SELECT 60 * 60 * 24 * 7; -- result: 604800
-- result: Hi there! 49, then 'not available' will show up.
SELECT

To retrieve all rows with the weight column populated:


Remember that you can concatenate only character strings CASTING WHERE weight IS NOT NULL
CASE fee

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'

'atherine': SELECT MOD(13, 2);

WHEN score > 60 THEN 'B'

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

-- result: 1234.568 domain,


TROUBLESHOOTING
USEFUL FUNCTIONS PostgreSQL requires the first argument to be of the type COALESCE(domain, 'domain missing')

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);

last_month this_month better_by_percent


-- result: Learn
To get the absolute value of a number: 723786 1085679 150.0 Errors when rounding with a specified precision
Replace part of a string: SELECT ABS(-12); -- result: 12 Most databases won't complain, but do check the
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.

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
group below): To get the simplest interval, subtract one time value from saving time. So, it's best to work with the timestamp
MIN(expr) − the minimum value within the group another: values.
2021-12-31 14:39:53.662522-05
MAX(expr) − the maximum value within the group SELECT CAST('2021-12-31 23:59:59' AS
date time When working with the type timestamp with time
timestamp) - CAST('2021-06-01 12:00:00' AS zone (abbr. timestamptz), you can type in the value in
timestamp timestamp);

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';

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

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


-- result: 2021-07-17 00:00:00-04
+ INTERVAL '1' MONTH

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

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?"

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