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

SQL Functions CheatSheet

Uploaded by

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

SQL Functions CheatSheet

Uploaded by

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

Standard SQL Functions Cheat Sheet

Text Functions
Use the || operator to concatenate two Get the count of characters in a string:
strings: SELECT LENGTH(‘CoderSQL.com’);

SELECT ‘Hi’ || ‘there!’;


-- result: 12
-- result: Hi there! Convert all letters to lowercase:
Remember that you can concatenate only SELECT LOWER(‘CODERSQL.com’);

character strings using ||. Use this trick for


-- result: codersql.com
numbers:
Convert all letters to uppercase:
SELECT ‘’ || 4 || 2;

-- result: 42 SELECT UPPER(‘CODERSQL.com’);

-- result: CODERSQL.COM
Some databases implement non-standard
solutions for concatenating strings like Convert all letters to lowercase and all first
CONCAT() or CONCAT_WS(). Check the letters to uppercase (not implemented in
documentation for your specific database. MySQL and SQL Server):
SELECT INITCAP(‘edgar frank ted
cODD’);

Use the_character to replace any single -- result: Edgar Frank Ted Codd
character. Use the % character to replace any Get just a part of a string:
number of characters (including 0
characters). SELECT SUBSTRING(‘CODERSQL.com’,
Fetch all names that start with any letter 9);

followed by ‘atherine’: -- result: .com


SELECT names
Get just a part of a string:
FROM names
SELECT SUBSTRING(‘CODERSQL.com’, 0,
WHERE name LIKE ‘_atherine’; 6);

Fetch all names that end with ‘a’: -- result: Coder


SELECT names
Replace part of string:
FROM names
SELECT REPLACE(‘CODERSQL.com’,
WHERE name LIKE ‘%a’; ‘SQL’, ‘Python’);

-- result: CoderPython.com
Standard SQL Functions Cheat Sheet

Numeric Functions
Round a number to three decimal places:
Use +, -, *, / to do some basic math. To get SELECT ROUND (1234.56789, 3);

the number of seconds in a week: -- result: 1234.568


SELECT 60 * 60 *60 * 7;

PostgreSQL requires the first argument to be


-- result: 604800 of the type numeric - cast the number when
needed.
To round the number up:
From time to time, you need to change the
SELECT CEIL(13.1); -- result: 14

type of a number. The CAST( ) function is


there to help you out. It lets you change the
SELECT CEIL(-13.9); -- result: -13
type of value to almost anything (integer, The CEIL(x) function returns the smallest
numeric, double precision, varchar, and many integer not less than x. In SQL Server, the
more).
function is called CEILING().
Get the number as an integer (without To round the number down:
rounding):
SELECT FLOOR(13.8);-- result: 13

SELECT CAST (1234.567 AS integer);

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


-- result: 1234
The FLOOR(x) function returns the greatest
Change a column type to double precision integer not greater than x.
SELECT CAST (column AS double To round towards 0 irrespective of the sign of
precision); a number:
SELECT TURNC(13.5);-- result: 13

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


Get the remainder of a division:
TRUNC(x) works the same way as CAST (x AS
SELECT MOD (13, 2);
integer). In MySQL, the function is called
-- result: 1 TRUNCATE().
Round a number to its nearest integer: To get the absolute value of a number:
SELECT ROUND (1234.56789);
SELECT ABS(-12);-- result: 12
-- result: 1235 To get the square root of a number:
SELECT SQRT(9);-- result: 3
Standard SQL Functions Cheat Sheet

NULLs
domain coalesce
To retrieve all rows with a missing value in the
price column: CODERSQL.com CODERSQL.com
WHERE price IS NULL NULL domain missing
To retrieve all rows with the weight column The COALESCE() function takes any number
populated: of arguments and returns the value of the first
argument that isn't NULL.
WHERE weight IS NOT NULL
Why shouldn't you use price = NULL or weight NULLIF(x, y)
!= NULL?

Because databases don't know if those To save yourself from division by 0 errors:
expressions are true or false - they are
SELECT

evaluated as NULLs.

Moreover, if you use a function or last_month,

concatenation on a column that is NULL in this_month,

some rows, then it will get propagated. Take a this_month * 100.0

look: / NULLIF (last_month, 0);

AS better_by_percent

domain LENGTH(domain)
FROM video_views;
CODERSQL.com 12
last_month this_month better_by_percent
CoderPython.com 15
723786 1085679 1085679
NULL NULL
0 178123 NULL
vertabelo.com 13
The NULLIF (x, y) function will return NULL if x
is the same as y, else it will return the x value.

COALESCE(x, y, ...)
To replace NULL in a query with something
meaningful:
SELECT

domain,

COALESCE (domain, ‘domain missing’);

SELECT contacts;
Standard SQL Functions Cheat Sheet
Case When Troubleshooting
The basic version of CASE WHEN checks if
the values are equal (e.g., if fee is equal to 50, When you don't see the decimal places you
then ‘normal’ is returned). If there isn't a expect, it means that you are dividing
matching value in the CASE WHEN, then the between two integers. Cast one to decimal:
ELSE value will be returned (e.g., if fee is equal
to 49, then ‘not available’ will show up. CAST(123 AS decimal) / 2
SELECT

CASE fee

WHEN 50 THEN ‘normal’


To avoid this error, make sure that the
WHEN 10 THEN ‘reduced’
denominator is not equal to 0. You can use the
WHEN 0 THEN ‘free’
NULLIF( ) function to replace 0 with a NULL,
ELSE ‘not available’
which will result in a NULL for the whole
END AS tariff
expression:
FROM ticket_types; count / NULLIF(count_all, 0)
The most popular type is the searched CASE
WHEN — it lets you pass conditions (as you'd If you do calculations using real (floating
write them in the WHERE clause), evaluates point) numbers, you'll end up with some
them in order, then returns the value for the inaccuracies. This is because this type is
first condition met. meant for scientific calculations such as
SELECT
calculating the velocity.

CASE
Whenever you need accuracy (such as dealing
WHEN score >= 90 THEN ‘A’
with monetary values), use the decimal /
WHEN score > 60 THEN ‘B’
numeric type (or money if available).
ELSE ‘F’

END AS grade

FROM test_results;
Here, all students who scored at least 90 will M ost databases won't complain, but do check
get an A, those with the score above 60 (and the documentation if they do. For example, if
below 90) will get a B, and the rest will receive you want to specify the rounding precision in
an F. PostgreSQL, the value must be of the numeric
type.

You might also like