1) This document provides a cheat sheet on standard SQL functions for text, numeric, and logical operations.
2) It explains functions for concatenating strings, performing calculations, casting data types, rounding numbers, and working with null values.
3) The CASE WHEN statement is demonstrated for conditional logic based on column values, returning different results based on conditions.
1) This document provides a cheat sheet on standard SQL functions for text, numeric, and logical operations.
2) It explains functions for concatenating strings, performing calculations, casting data types, rounding numbers, and working with null values.
3) The CASE WHEN statement is demonstrated for conditional logic based on column values, returning different results based on conditions.
CONCATENATION BASIC OPERATIONS To retrieve all rows with a missing value in the price column: The basic version of CASE WHEN checks if the values are equal WHERE price IS NULL (e.g., if fee is equal to 50, then 'normal' is returned). If there Use the || operator to concatenate two strings: Use +, -, *, / to do some basic math. To get the number of isn't a matching value in the CASE WHEN, then the ELSE value SELECT 'Hi ' || 'there!'; seconds in a week: To retrieve all rows with the weight column populated: will be returned (e.g., if fee is equal to 49, then 'not -- result: Hi there! SELECT 60 * 60 * 24 * 7; -- result: 604800 WHERE weight IS NOT NULL available' will show up. Remember that you can concatenate only character strings using SELECT CASTING ||. Use this trick for numbers: Why shouldn't you use price = NULL or weight != NULL? CASE fee From time to time, you need to change the type of a number. The SELECT '' || 4 || 2; Because databases don't know if those expressions are true or WHEN 50 THEN 'normal' CAST() function is there to help you out. It lets you change the -- result: 42 false – they are evaluated as NULLs. WHEN 10 THEN 'reduced' type of value to almost anything (integer, numeric, double Some databases implement non-standard solutions for Moreover, if you use a function or concatenation on a column that WHEN 0 THEN 'free' precision, varchar, and many more). concatenating strings like CONCAT() or CONCAT_WS(). Check is NULL in some rows, then it will get propagated. Take a look: ELSE 'not available' Get the number as an integer (without rounding): the documentation for your specific database. END AS tariff SELECT CAST(1234.567 AS integer); domain LENGTH(domain) FROM ticket_types; LIKE OPERATOR – PATTERN MATCHING -- result: 1234 Change a column type to double precision LearnSQL.com 12 The most popular type is the searched CASE WHEN – it lets you Use the _ character to replace any single character. Use the % SELECT CAST(column AS double precision); LearnPython.com 15 pass conditions (as you'd write them in the WHERE clause), character to replace any number of characters (including 0 characters). evaluates them in order, then returns the value for the first USEFUL FUNCTIONS NULL NULL condition met. Fetch all names that start with any letter followed by Get the remainder of a division: vertabelo.com 13 SELECT 'atherine': SELECT MOD(13, 2); CASE SELECT name -- result: 1 WHEN score >= 90 THEN 'A' FROM names USEFUL FUNCTIONS WHEN score > 60 THEN 'B' WHERE name LIKE '_atherine'; Round a number to its nearest integer: COALESCE(x, y, ...) ELSE 'F' Fetch all names that end with 'a': SELECT ROUND(1234.56789); To replace NULL in a query with something meaningful: END AS grade SELECT name -- result: 1235 SELECT FROM test_results; FROM names Round a number to three decimal places: domain, Here, all students who scored at least 90 will get an A, those with WHERE name LIKE '%a'; SELECT ROUND(1234.56789, 3); COALESCE(domain, 'domain missing') the score above 60 (and below 90) will get a B, and the rest will -- result: 1234.568 FROM contacts; receive an F. USEFUL FUNCTIONS PostgreSQL requires the first argument to be of the type domain coalesce Get the count of characters in a string: SELECT LENGTH('LearnSQL.com'); numeric – cast the number when needed. LearnSQL.com LearnSQL.com TROUBLESHOOTING -- result: 12 To round the number up: Integer division NULL domain missing When you don't see the decimal places you expect, it means that Convert all letters to lowercase: SELECT CEIL(13.1); -- result: 14 SELECT CEIL(-13.9); -- result: -13 The COALESCE() function takes any number of arguments and you are dividing between two integers. Cast one to decimal: SELECT LOWER('LEARNSQL.COM'); The CEIL(x) function returns the smallest integer not less than returns the value of the first argument that isn't NULL. CAST(123 AS decimal) / 2 -- result: learnsql.com x. In SQL Server, the function is called CEILING(). Division by 0 Convert all letters to uppercase: SELECT UPPER('LearnSQL.com'); To round the number down: NULLIF(x, y) To avoid this error, make sure that the denominator is not equal -- result: LEARNSQL.COM SELECT FLOOR(13.8); -- result: 13 To save yourself from division by 0 errors: to 0. You can use the NULLIF() function to replace 0 with a SELECT FLOOR(-13.2); -- result: -14 SELECT NULL, which will result in a NULL for the whole expression: Convert all letters to lowercase and all first letters to uppercase The FLOOR(x) function returns the greatest integer not greater last_month, count / NULLIF(count_all, 0) (not implemented in MySQL and SQL Server): than x. this_month, SELECT INITCAP('edgar frank ted cODD'); Inexact calculations this_month * 100.0 -- result: Edgar Frank Ted Codd If you do calculations using real (floating point) numbers, you'll To round towards 0 irrespective of the sign of a number: / NULLIF(last_month, 0) Get just a part of a string: end up with some inaccuracies. This is because this type is meant SELECT TRUNC(13.5); -- result: 13 AS better_by_percent SELECT SUBSTRING('LearnSQL.com', 9); for scientific calculations such as calculating the velocity. SELECT TRUNC(-13.5); -- result: -13 FROM video_views; -- result: .com Whenever you need accuracy (such as dealing with monetary TRUNC(x) works the same way as CAST(x AS integer). In SELECT SUBSTRING('LearnSQL.com', 0, 6); last_month this_month better_by_percent values), use the decimal / numeric type (or money if MySQL, the function is called TRUNCATE(). -- result: Learn available). 723786 1085679 150.0 To get the absolute value of a number: Replace part of a string: 0 178123 NULL Errors when rounding with a specified precision SELECT ABS(-12); -- result: 12 SELECT REPLACE('LearnSQL.com', 'SQL', Most databases won't complain, but do check the documentation 'Python'); To get the square root of a number: The NULLIF(x, y) function will return NULL if x is the same as if they do. For example, if you want to specify the rounding -- result: LearnPython.com SELECT SQRT(9); -- result: 3 y, else it will return the x value. precision in PostgreSQL, the value must be of 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 the 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 time group timestamp. Time is expressed using a 24-hour clock, and it can DATEADD() and DATEDIFF() functions. zone, but the time and timestamp types can. In the real world, SUM(expr) − the sum of values within the group be as vague as just hour and minutes (e.g., 15:30 – 3:30 p.m.) or time zones have little meaning without the date, as the offset can AVG(expr) − the average value for the rows within the group as precise as microseconds and time zone (as shown below): To get the simplest interval, subtract one time value from vary through the year because of daylight saving time. So, it's MIN(expr) − the minimum value within the group another: best to work with the timestamp 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 zone To get the number of rows in the table: timestamp) - CAST('2021-06-01 12:00:00' AS (abbr. timestamptz), you can type in the value in your local timestamp SELECT COUNT(*) timestamp); time zone, and it'll get converted to the UTC time zone as it is FROM city; YYYY-mm-dd HH:MM:SS.ssssss±TZ -- result: 213 days 11:59:59 inserted into the table. Later when you select from the table it 14:39:53.662522-05 is almost 2:40 p.m. CDT (e.g., in gets converted back to your local time zone. This is immune to To get the number of non-NULL values in a column: time zone changes. SELECT COUNT(rating) Chicago; in UTC it'd be 7:40 p.m.). The letters in the above To define an interval: INTERVAL '1' DAY FROM city; example represent: This syntax consists of three elements: the INTERVAL keyword, a In the date part: In the time part: quoted value, and a time part keyword (in singular form.) You can AT TIME ZONE To get the count of unique values in a column: use the following time parts: YEAR, MONTH, WEEK, DAY, HOUR, To operate between different time zones, use the AT TIME YYYY – the 4-digit HH – the zero-padded hour in a 24- SELECT COUNT(DISTINCT country_id) MINUTE, and SECOND. In MySQL, omit the quotes. You can join ZONE keyword. year. hour clock. FROM city; many different INTERVALs using the + or - operator: mm – the zero-padded MM – the minutes. If you use this format: {timestamp without time zone} month (01—January SS – the seconds. Omissible. INTERVAL '1' YEAR + INTERVAL '3' MONTH GROUP BY AT TIME ZONE {time zone}, then the database will read through 12— ssssss – the smaller parts of a the time stamp in the specified time zone and convert it to the CITY December). second – they can be expressed In some databases, there's an easier way to get the above value. time zone local to the display. It returns the time in the format name country_id dd – the zero-padded using 1 to 6 digits. Omissible. And it accepts plural forms! INTERVAL '1 year 3 timestamp with time zone. day. ±TZ – the timezone. It must start months' Paris 1 If you use this format: {timestamp with time zone} AT CITY with either + or -, and use two There are two more syntaxes in the Standard SQL: Marseille 1 TIME ZONE {time zone}, then the database will convert the country_id count digits relative to UTC. Omissible. Syntax What it does time in one time zone to the target time zone specified by AT Lyon 1 1 3 TIME ZONE. It returns the time in the format timestamp What time is it? INTERVAL 'x-y' YEAR TO INTERVAL 'x year y Berlin 2 without time zone, in the target time zone. 2 3 To answer that question in SQL, you can use: 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 TO INTERVAL 'x day y Munich 2 SECOND second' MST, or GMT, or by continent/city such as: CURRENT_DATE – to get today's date. (GETDATE() in SQL America/New_York, Europe/London, and Asia/Tokyo. Warsaw 4 Server.) In MySQL, write year_month instead of YEAR TO MONTH and Cracow 4 CURRENT_TIMESTAMP – to get the timestamp with the two day_to_second instead of DAY TO SECOND. above. Examples The example above – the count of cities in each country: 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 one FROM city Creating values SELECT TIMESTAMP '2021-07-16 21:00:00' AT day: GROUP BY name; To create a date, time, or timestamp, simply write the value TIME ZONE 'America/Los_Angeles'; SELECT CAST('2021-02-01' AS date) as a string and cast it to the proper type. -- result: 2021-07-17 00:00:00-04 The average rating for the city: + INTERVAL '1' MONTH SELECT CAST('2021-12-31' AS date); SELECT city_id, AVG(rating) - INTERVAL '1' DAY; Here, the database takes a timestamp without a time zone and it's SELECT CAST('15:31' AS time); FROM ratings told it's in Los Angeles time, which is then converted to the local SELECT CAST('2021-12-31 23:59:29+02' AS GROUP BY city_id; time – New York for displaying. This answers the question "At timestamp); To get all events for next three months from today: what time should I turn on the TV if the show starts at 9 PM in Common mistake: COUNT(*) and LEFT JOIN SELECT CAST('15:31.124769' AS time); SELECT event_date, event_name Los Angeles?" When you join the tables like this: client LEFT JOIN Be careful with the last example – it will be interpreted as 15 FROM calendar project, and you want to get the number of projects for every minutes 31 seconds and 124769 microseconds! It is always a good WHERE event_date BETWEEN CURRENT_DATE AND idea to write 00 explicitly for hours: '00:15:31.124769'. CURRENT_DATE + INTERVAL '3' MONTH; SELECT TIMESTAMP WITH TIME ZONE '2021-06-20 client you know, COUNT(*) will return 1 for each client even if 19:30:00' AT TIME ZONE 'Australia/Sydney'; you've never worked for them. This is because, they're still -- result: 2021-06-21 09:30:00 present in the list but with the NULL in the fields related to the You might skip casting in simple conditions – the database will To get part of the date: project after the JOIN. To get the correct count (0 for the clients know what you mean. SELECT EXTRACT(YEAR FROM birthday) Here, the database gets a timestamp specified in the local time you've never worked for), count the values in a column of the SELECT airline, flight_number, departure_time FROM artists; zone and converts it to the time in Sydney (note that it didn't other table, e.g., COUNT(project_name). Check out this FROM airport_schedule One of possible returned values: 1946. In SQL Server, use the return a time zone.) This answers the question "What time is it in exercise to see an example. WHERE departure_time < '12:00'; DATEPART(part, date) function. 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