Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

Whether you are a beginner stepping into the world of SQL or a seasoned

professional looking to brush up on your skills, our Standard SQL Functions Cheat
Sheet is designed to be your go-to guide for SQL functions. This comprehensive cheat
sheet is packed with syntax for different text and numeric functions, CASE
WHEN statements, handling NULL, date and time types, INTERVALs, and aggregate
functions. It also features a troubleshooting section to help you navigate through
common issues seamlessly.
https://learnsql.com/

Text functions
Concatenation
Use the || operator to concatenate two strings:

SELECT 'Hi ' || 'there!';


-- result: Hi there!

Remember that you can concatenate only character strings using ||. Use this trick for
numbers:

SELECT '' || 4 || 2;
-- result: 42

Some databases implement non-standard solutions for concatenating strings


like CONCAT() or CONCAT_WS(). Check the documentation for your specific database.

LIKE operator – pattern matching


Use the _ character to replace any single character. Use the % character to replace any
number of characters (including 0 characters).

Fetch all names that start with any letter followed by 'atherine':

SELECT name
FROM names
WHERE name LIKE '_atherine';
Fetch all names that end with 'a':

SELECT name
FROM names
WHERE name LIKE '%a';

Useful functions
Get the count of characters in a string:

SELECT LENGTH('LearnSQL.com');
-- result: 12

Convert all letters to lowercase:

SELECT LOWER('LEARNSQL.COM');
-- result: learnsql.com

Convert all letters to uppercase:

SELECT UPPER('LearnSQL.com');
-- result: LEARNSQL.COM

Convert all letters to lowercase and all first letters to uppercase (not implemented in
MySQL and SQL Server):

SELECT INITCAP('edgar frank ted cODD');


-- result: Edgar Frank Ted Codd

Get just a part of a string:

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


-- result: .com
SELECT SUBSTRING('LearnSQL.com', 0, 6);
-- result: Learn

Replace part of a string:

SELECT REPLACE('LearnSQL.com', 'SQL', 'Python');


-- result: LearnPython.com
Numeric functions
Basic operations
Use +, -, *, / to do some basic math. To get the number of seconds in a week:

SELECT 60 * 60 * 24 * 7; -- result: 604800

Casting
From time to time, you need to change the type of a number. The CAST() function is
there to help you out. It lets you change the type of value to almost anything
(integer, numeric, double precision, varchar, and many more).

Get the number as an integer (without rounding):

SELECT CAST(1234.567 AS integer);


-- result: 1234

Change a column type to double precision

SELECT CAST(column AS double precision);

Useful functions
Get the remainder of a division:

SELECT MOD(13, 2);


-- result: 1

Round a number to its nearest integer:


SELECT ROUND(1234.56789);
-- result: 1235

Round a number to three decimal places:

SELECT ROUND(1234.56789, 3);


-- result: 1234.568

PostgreSQL requires the first argument to be of the type numeric – cast the number
when needed.

To round the number up:

SELECT CEIL(13.1); -- result: 14


SELECT CEIL(-13.9); -- result: -13

The CEIL(x) function returns the smallest integer not less than x. In SQL Server, the
function is called CEILING().

To round the number down:

SELECT FLOOR(13.8); -- result: 13


SELECT FLOOR(-13.2); -- result: -14

The FLOOR(x) function returns the greatest integer not greater than x.

To round towards 0 irrespective of the sign of a number:

SELECT TRUNC(13.5); -- result: 13


SELECT TRUNC(-13.5); -- result: -13

TRUNC(x) works the same way as CAST(x AS integer). In MySQL, the function is
called TRUNCATE().

To get the absolute value of a number:

SELECT ABS(-12); -- result: 12

To get the square root of a number:

SELECT SQRT(9); -- result: 3


NULLs
To retrieve all rows with a missing value in the price column:

WHERE price IS NULL

To retrieve all rows with the weight column populated:

WHERE weight IS NOT NULL

Why shouldn't you use price = NULL or weight != NULL? Because databases don't
know if those expressions are true or false – they are evaluated as NULLs.

Moreover, if you use a function or concatenation on a column that is NULL in some


rows, then it will get propagated. Take a look:

Useful functions
COALESCE

To replace NULL in a query with something meaningful:

SELECT
domain,
COALESCE(domain, 'domain missing')
FROM contacts;
The COALESCE() function takes any number of arguments and returns the value of the
first argument that isn't NULL.

NULLIF

To save yourself from division by 0 errors:

SELECT
last_month,
this_month,
this_month * 100.0
/ NULLIF(last_month, 0)
AS better_by_percent
FROM video_views;

The NULLIF(x, y) function will return NULL if x is the same as y, else it will return
the x value.

CASE WHEN
The basic version of CASE WHEN checks if the values are equal (e.g., if fee is equal to
50, then 'normal' is returned). If there isn't a matching value in the CASE WHEN, then
the ELSE value will be returned (e.g., if fee is equal to 49, then 'not available' will
show up.

SELECT
CASE fee
WHEN 50 THEN 'normal'
WHEN 10 THEN 'reduced'
WHEN 0 THEN 'free'
ELSE 'not available'
END AS tariff
FROM ticket_types;
The most popular type is the searched CASE WHEN – it lets you pass conditions (as
you'd write them in the WHERE clause), evaluates them in order, then returns the value
for the first condition met.

SELECT
CASE
WHEN score >= 90 THEN 'A'
WHEN score > 60 THEN 'B'
ELSE 'F'
END AS grade
FROM test_results;

Here, all students who scored at least 90 will get an A, those with the score above 60
(and below 90) will get a B, and the rest will receive an F.

Troubleshooting
Integer division
When you don't see the decimal places you expect, it means that you are dividing
between two integers. Cast one to decimal:

CAST(123 AS decimal) / 2

Division by 0
To avoid this error, make sure that the denominator is not equal to 0. You can use
the NULLIF() function to replace 0 with a NULL, which will result in a NULL for the whole
expression:

count / NULLIF(count_all, 0)

Inexact calculations
If you do calculations using real (floating point) numbers, you'll end up with some
inaccuracies. This is because this type is meant for scientific calculations such as
calculating the velocity. Whenever you need accuracy (such as dealing with monetary
values), use the decimal / numeric type (or money if available).

Errors when rounding with a specified


precision
Most databases won't complain, but do check the documentation if they do. For
example, if you want to specify the rounding precision in PostgreSQL, the value must
be of the numeric type.

Aggregation and grouping

Aggregate functions
 COUNT(expr) − the count of values for the rows within the group
 SUM(expr) − the sum of values within the group
 AVG(expr) − the average value for the rows within the group
 MIN(expr) − the minimum value within the group
 MAX(expr) − the maximum value within the group

To get the number of rows in the table:

SELECT COUNT(*)
FROM city;

To get the number of non-NULL values in a column:

SELECT COUNT(rating)
FROM city;

To get the count of unique values in a column:


SELECT COUNT(DISTINCT country_id)
FROM city;

GROUP BY

The example above – the count of cities in each country:

SELECT name, COUNT(country_id)


FROM city
GROUP BY name;

The average rating for the city:

SELECT city_id, AVG(rating)


FROM ratings
GROUP BY city_id;

Common mistake: COUNT(*) and LEFT JOIN

When you join the tables like this: client LEFT JOIN project, and you want to get the
number of projects for every client you know, COUNT(*) will return 1 for each client even
if you've never worked for them. This is because, they're still present in the list but with
the NULL in the fields related to the project after the JOIN. To get the correct count (0 for
the clients you've never worked for), count the values in a column of the other table,
e.g., COUNT(project_name).

Date and time


There are 3 main time-related types: date, time, and timestamp. Time is expressed
using a 24-hour clock, and it can be as vague as just hour and minutes (e.g., 15:30 –
3:30 p.m.) or as precise as microseconds and time zone (as shown below):

14:39:53.662522-05 is almost 2:40 p.m. CDT (e.g., in Chicago; in UTC it'd be 7:40
p.m.). The letters in the above example represent:

In the date part: YYYY – the 4-digit year. mm – the zero-padded month (01—January
through 12—December). dd – the zero-padded day.
In the time part: HH – the zero-padded hour in a 24-hour clock. MM – the minutes. SS –
the seconds. Omissible. ssssss – the smaller parts of a second – they can be
expressed using 1 to 6 digits. Omissible. ±TZ – the timezone. It must start with
either + or -, and use two digits relative to UTC. Omissible.

What time is it?


To answer that question in SQL, you can use:

CURRENT_TIME– to find what time it is. CURRENT_DATE – to get today's date. (GETDATE() in
SQL Server.) CURRENT_TIMESTAMP – to get the timestamp with the two above.

Creating values
To create a date, time, or timestamp, simply write the value as a string and cast it to the
proper type.

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


SELECT CAST('15:31' AS time);
SELECT CAST('2021-12-31 23:59:29+02' AS timestamp);
SELECT CAST('15:31.124769' AS time);

Be careful with the last example – it will be interpreted as 15 minutes 31 seconds and
124769 microseconds! It is always a good idea to write 00 explicitly for
hours: '00:15:31.124769'.

You might skip casting in simple conditions – the database will know what you mean.

SELECT airline, flight_number, departure_time


FROM airport_schedule
WHERE departure_time < '12:00';

Intervals
Note: In SQL Server, intervals aren't implemented – use
the DATEADD() and DATEDIFF() functions.

To get the simplest interval, subtract one time value from another:

SELECT CAST('2021-12-31 23:59:59' AS timestamp) - CAST('2021-06-01 12:00:00' AS


timestamp);
-- result: 213 days 11:59:59

To define an interval: INTERVAL '1' DAY

This syntax consists of three elements: the INTERVAL keyword, a quoted value, and a
time part keyword (in singular form.) You can use the following time
parts: YEAR, MONTH, WEEK, DAY, HOUR, MINUTE, and SECOND. In MySQL, omit the quotes. You
can join many different INTERVALs using the + or - operator:

INTERVAL '1' YEAR + INTERVAL '3' MONTH

In some databases, there's an easier way to get the above value. And it accepts plural
forms! INTERVAL '1 year 3 months'
There are two more syntaxes in the Standard SQL:

In MySQL, write year_month instead of YEAR TO MONTH and day_second instead of DAY TO
SECOND.

To get the last day of a month, add one month and subtract one day:

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


+ INTERVAL '1' MONTH
- INTERVAL '1' DAY;

To get all events for next three months from today:

SELECT event_date, event_name


FROM calendar
WHERE event_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '3' MONTH;

To get part of the date:

SELECT EXTRACT(YEAR FROM birthday)


FROM artists;

One of possible returned values: 1946. In SQL Server, use the DATEPART(part,
date) function.

Time zones
In the SQL Standard, the date type can't have an associated time zone, but
the time and timestamp types can. In the real world, time zones have little meaning
without the date, as the offset can vary through the year because of daylight saving
time. So, it's best to work with the timestamp values.
When working with the type timestamp with time zone (abbr. timestamptz), you can
type in the value in your local time zone, and it'll get converted to the UTC time zone
as it is inserted into the table. Later when you select from the table it gets converted
back to your local time zone. This is immune to time zone changes.

AT TIME ZONE

To operate between different time zones, use the AT TIME ZONE keyword.

If you use this format: {timestamp without time zone} AT TIME ZONE {time zone}, then
the database will read the time stamp in the specified time zone and convert it to the
time zone local to the display. It returns the time in the format timestamp with time
zone.

If you use this format: {timestamp with time zone} AT TIME ZONE {time zone}, then the
database will convert the time in one time zone to the target time zone specified by AT
TIME ZONE. It returns the time in the format timestamp without time zone, in the target
time zone.

You can define the time zone with popular shortcuts like UTC, MST, or GMT, or
by continent/city such as: America/New_York, Europe/London, and Asia/Tokyo.

Examples

We set the local time zone to 'America/New_York'.

SELECT TIMESTAMP '2021-07-16 21:00:00' AT TIME ZONE 'America/Los_Angeles';


-- result: 2021-07-17 00:00:00-04

Here, the database takes a timestamp without a time zone and it's told it's in Los
Angeles time, which is then converted to the local time – New York for displaying. This
answers the question "At what time should I turn on the TV if the show starts at 9
PM in Los Angeles?"

SELECT TIMESTAMP WITH TIME ZONE '2021-06-20 19:30:00' AT TIME ZONE 'Australia/Sydney';
-- result: 2021-06-21 09:30:00

Here, the database gets a timestamp specified in the local time zone and converts it to
the time in Sydney (note that it didn't return a time zone.) This answers the
question "What time is it in Sydney if it's 7:30 PM here?"
7 SQL JOIN Examples With
Detailed Explanations

Introduction to JOIN
With relational databases, the information you want is often stored in several tables. In
such scenarios, you’ll need to join these tables. This is where the SQL JOIN comes
into play.

The JOIN clause in SQL is used to combine rows from several tables based on a
related column between these tables. You can get an overview of the SQL JOIN
tool in this introductory article.

In this guide, I want to cover the basic types of SQL JOINs by going through several
examples. I will discuss in detail the syntax of each query, how it works, how to build a
condition, and how to interpret the results.

Practice SQL JOINs with our interactive SQL JOINs course.

For the examples, we will use information about a publishing house that publishes
original and translated books. Our database contains four
tables: books, authors, editors, and translators.

books

aut edit trans


i typ
title hor or_ lator
d e
_id id _id

Ti
me
to orig
1 11 21
Gr inal
ow
Up!
books

Yo
tran
ur
2 slat 15 22 32
Tri
ed
p

Lov
ely orig
3 14 24
Lov inal
e

Dre
am
orig
4 Yo 11 24
inal
ur
Life

Or tran
5 an slat 12 25 31
ges ed

Yo
ur tran
6 Ha slat 15 22 33
ppy ed
Life

Ap
tran
plie
7 slat 13 23 34
d
ed
AI

8 My orig 11 28
Las inal
t
Bo
books

ok

authors

id first_name last_name

11 Ellen Writer

12 Olga Savelieva

13 Jack Smart

14 Donald Brain

15 Yao Dou

editors

id first_name last_name

21 Daniel Brown

22 Mark Johnson

23 Maria Evans
editors

24 Cathrine Roberts

25 Sebastian Wright

26 Barbara Jones

27 Matthew Smith

translators

id first_name last_name

31 Ira Davies

32 Ling Weng

33 Kristian Green

34 Roman Edwards

If you want to practice joining tables in SQL with many examples, I recommend taking
the SQL JOINs course. It includes 93 coding challenges!

INNER JOIN
We’ll start with a basic INNER JOIN, or simply, JOIN. This join type is used when we want
to display matching records from two tables.
Example #1: Showing books and their
authors
Let’s say we want to show book titles along with their authors (i.e., the author’s first
name and last name). The book titles are stored in the books table, and the author
names are stored in the authors table.

In our SQL query, we’ll join these two tables by matching the author_id column from
the books table and the id column from the authors table:

SELECT b.id, b.title, a.first_name, a.last_name

FROM books b

INNER JOIN authors a

ON b.author_id = a.id

ORDER BY b.id;

In the SELECT statement, we list the columns to be displayed: book id, book title,
author’s first name, and author’s last name. In the FROM clause, we specify the first
table to join (also referred to as the left table). In the INNER JOIN clause, we specify the
second table to join (also referred to as the right table).

Then, we use the ON keyword to tell the database which columns should be used for
matching the records (i.e., the author_id column from the books table and
the id column from the authors table).

Note also that we are using aliases for table names (i.e., b for books and a for authors).
We assign the aliases in the FROM and INNER JOIN clauses and use them throughout the
query. The table aliases reduce typing and make the query more readable.

Here’s the resulting set:

id title first_name last_name

1 Time to Grow Up! Ellen Writer


2 Your Trip Yao Dou

3 Lovely Love Donald Brain

4 Dream Your Life Ellen Writer

5 Oranges Olga Savelieva

6 Your Happy Life Yao Dou

7 Applied AI Jack Smart

8 My Last Book Ellen Writer

For each record in the left table (i.e., books), the query checks the author_id, then
looks for the same id in the first column of the authors table. It then pulls the
corresponding first name and last name.

Note that the order of the tables doesn’t matter with INNER JOIN, or simple JOIN.
The result set would be exactly the same if we put the authors table in the FROM clause
and the books table in the INNER JOIN clause.

INNER JOIN only displays records that are available in both tables. In our example, all
books have a corresponding author and all authors have at least one corresponding
book. So, let’s see what happens if some of the records are not matched.

Example #2: Showing books and their


translators
In our second example, we’ll be displaying books along with their translators (i.e., the
translator’s last name). Only half of our books have been translated and thus have a
corresponding translator. So, what would be the result of joining
the books and translators tables using INNER JOIN?

SELECT b.id, b.title, b.type, t.last_name AS translator

FROM books b

JOIN translators t

ON b.translator_id = t.id

ORDER BY b.id;

id title type translator

2 Your Trip translated Weng

5 Oranges translated Davies

6 Your Happy Life translated Green

7 Applied AI translated Edwards

The query outputs only those books that have been translated. I’ve added the type
column to make it clear. The rest of the books couldn’t be matched with
the translators table and thus are not displayed. That’s how INNER JOIN works.

Also, note that in the second example, we were using JOIN rather than the INNER
JOIN keyword. It has no impact on the result because INNER JOIN is the default join type
in SQL. You can learn about other SQL JOIN types in this detailed guide.

Okay. Now we know how to join tables when we need only the matched records to be
displayed. But, what if we want to keep all of the books in the resulting set without
cutting the table to the translated books only? It’s time to learn about outer joins!

LEFT JOIN
We’ll start our overview of OUTER joins with the LEFT JOIN. You should apply this SQL
JOIN type when you want to keep all records from the left table and only the
matched records from the right table.

Example #3: Showing all books


alongside their authors and translators,
if they exist
For instance, let’s say that we want to display information about each book’s author
and translator (i.e., their last names). We also want to keep the basic information
about each book (i.e., id, title, and type).

To get all of this data, we’ll need to join three tables: books for basic info on the
books, authors for the authors’ last names, and translators for the translators’ last
names.

As we have seen in the previous example, using the INNER JOIN (or simple JOIN) to join
the translators table results in losing all of the records for original (not translated)
books. That’s not what we want now. So, to keep all of the books in the result set, we’ll
join the books, authors, and translators tables using the LEFT JOIN.

SELECT b.id, b.title, b.type, a.last_name AS author,

t.last_name AS translator

FROM books b

LEFT JOIN authors a

ON b.author_id = a.id

LEFT JOIN translators t

ON b.translator_id = t.id

ORDER BY b.id;
See that we start with the books table in the FROM clause, making it the left table.
That’s because we want to keep all of the records from this table. The order of the
other tables doesn’t matter.

In our query, we first LEFT JOIN the authors table based on the author_id column from
the books table and the id column from the authors table. Then, we join
the translators table based on the translator_id column from the books table and
the id column from the translators table.

Here’s the resulting table:

i translat
title type author
d or

Time to
1 Grow original Writer NULL
Up!

Your translate
2 Dou Weng
Trip d

Lovely
3 original Brain NULL
Love

Dream
4 Your original Writer NULL
Life

Orange translate Saveliev


5 Davies
s d a

Your
translate
6 Happy Dou Green
d
Life

7 Applied translate Smart Edward


AI d s

My
8 Last original Writer NULL
Book

Great! We kept all of the books!

Note the NULL values in the translator column. These NULL values correspond to the
records that were not matched in the translators table. These records are for original
books without any translators involved.

Hopefully, you have grasped the intuition behind LEFT JOINs. You can learn more
about this type of SQL JOIN in this introductory guide.

Okay, let’s go through another LEFT JOIN example to consolidate knowledge on the
topic.

Example #4: Showing all books with


their editors, if any
This time, we want to show the basic book information (i.e., ID and title) along with the
last names of the corresponding editors. Again, we want to keep all of the books in the
result set. So, what would be the query?

SELECT b.id, b.title, e.last_name AS editor

FROM books b

LEFT JOIN editors e

ON b.editor_id = e.id

ORDER BY b.id;

id title editor
1 Time to Grow Up! Brown

2 Your Trip Johnson

3 Lovely Love Roberts

4 Dream Your Life Roberts

5 Oranges Wright

6 Your Happy Life Johnson

7 Applied AI Evans

8 My Last Book NULL

Pretty simple, right? We again kept all of the books in the result set, including the last
one, which doesn’t have a corresponding editor in our database (note the NULL value in
the last row).

We can imagine that the editor is not present in the table of our current editors simply
because they left the publishing house after editing the book.

Wait! What if we have some editors on the team who haven’t yet published any
books? Let’s check with the next outer join type.

RIGHT JOIN
RIGHT JOIN is very similar to LEFT JOIN. I bet you guessed that the only difference is
that RIGHT JOIN keeps all of the records from the right table, even if they cannot
be matched to the left table. If you did, you’re correct!
Example #5: Books and editors with
RIGHT JOIN
Let’s repeat our previous example, but this time, our task will be to keep all of the
records from the editors table. Thus, we will have the same query as in example
#4 except that we replace LEFT JOIN with RIGHT JOIN:

SELECT b.id, b.title, e.last_name AS editor

FROM books b

RIGHT JOIN editors e

ON b.editor_id = e.id

ORDER BY b.id;

id title editor

1 Time to Grow Up! Brown

2 Your Trip Johnson

3 Lovely Love Roberts

4 Dream Your Life Roberts

5 Oranges Wright

6 Your Happy Life Johnson

7 Applied AI Evans

NULL NULL Jones


NULL NULL Smith

With only one word changed in the query, the result is very different. We can see that
indeed we have two editors (Jones and Smith) that don’t have corresponding books in
our database. Looks like new hires!

And that’s not the only change. We also don’t have My Last Book in the result set.
This record of the left table (i.e., books) was not matched in the right table
(i.e., editors) and didn’t make it to the final result.

RIGHT JOINs are rarely used in practice because they usually can be replaced with
LEFT JOINs that are much more common.

For example, in our case, we could take our query from example #4 and just
swap books and editors by putting editors in the FROM clause, making it the left table,
and putting books in the LEFT JOIN clause, making it the right table. The result would
have been the same as the above table.

FULL JOIN
Here we arrived at the last outer join type, which is FULL JOIN. We use FULL JOIN when
we want to keep all records from all tables, even unmatched ones. So, it’s like LEFT
JOIN and RIGHT JOIN combined. Let’s go straight to the examples to see how this works
in practice.

Example #6: Showing all books and all


editors
To start with, let’s again join the books and editors tables, but this time, we’ll be
keeping all records from both tables. We simply use FULL JOIN as the join keyword,
leaving the rest of the query without any changes:

SELECT b.id, b.title, e.last_name AS editor


FROM books b

FULL JOIN editors e

ON b.editor_id = e.id

ORDER BY b.id;

id title editor

1 Time to Grow Up! Brown

2 Your Trip Johnson

3 Lovely Love Roberts

4 Dream Your Life Roberts

5 Oranges Wright

6 Your Happy Life Johnson

7 Applied AI Evans

8 My Last Book NULL

NULL NULL Jones

NULL NULL Smith


Looks great! As expected, we kept all of the books, even the one without a matching
editor. Also, we kept all of the editors, even the ones that don’t have any
corresponding books yet.

Note that the order of the tables doesn’t matter with FULL JOIN. The result would be
the same if we swapped the tables by putting the editors table in the FROM clause and
the books table in the FULL JOIN clause.

Example #7: Showing all books, authors,


editors, and translators
In our final example, we want to join all four tables to get information about all of the
books, authors, editors, and translators in one table. So, we’ll be using FULL
JOIN throughout our SQL query:

SELECT b.id, b.title, a.last_name AS author, e.last_name AS editor,

t.last_name AS translator

FROM books b

FULL JOIN authors a

ON b.author_id = a.id

FULL JOIN editors e

ON b.editor_id = e.id

FULL JOIN translators t

ON b.translator_id = t.id

ORDER BY b.id;

autho
id title editor translator
r

1 Time Writer Brown NULL


to
Grow
Up!

Your Johns
2 Dou Weng
Trip on

Lovel
Robert
3 y Brain NULL
s
Love

Drea
m Robert
4 Writer NULL
Your s
Life

Oran Saveli
5 Wright Davies
ges eva

Your
Johns
6 Happ Dou Green
on
y Life

Appli
7 Smart Evans Edwards
ed AI

My
8 Last Writer NULL NULL
Book

N
U NULL NULL Jones NULL
LL

N NULL NULL Smith NULL


U
LL

As requested, the table displays all of the books, authors, editors, and translators. The
records that were not matched have NULL values. That’s a great overview of the data
stored in our database.

You might also like