← Back to course: SQL and databases from scratch

Text, number and date functions

Video coming soon

Stored data rarely has exactly the format you need in a report. Functions transform values inside the query: they put a text in uppercase, round a price, extract the year from a date. Important: functions do not change the data in the table, only the result you see. You can use them in SELECT, in WHERE and in ORDER BY. Here you will see the most useful ones; the full PostgreSQL catalog is huge, and the habit of looking things up is part of the craft.

Text functions

  • UPPER(x), LOWER(x): uppercase and lowercase.
  • LENGTH(x): number of characters.
  • TRIM(x): removes spaces at the start and end.
  • SUBSTRING(x FROM 1 FOR 3) or SUBSTR(x, 1, 3): extracts a piece.
  • REPLACE(x, 'a', 'b'): replaces text.
  • a || b: concatenates (standard; MySQL uses CONCAT(a, b)).
sql
SELECT UPPER(name) AS name_upper,
       LENGTH(name) AS name_length,
       SUBSTR(name, 1, 3) AS short_code,
       name || ' (' || city || ')' AS label
FROM customers
WHERE city IS NOT NULL;

SELECT REPLACE(name, 'Wireless ', '') AS simple_name FROM products WHERE product_id = 2;

Notice the || operator: if either side is NULL, the whole result is NULL. That is why the first query filters out Hugo, who has no city. PostgreSQL's CONCAT function, on the other hand, ignores NULLs. And remember that a function applied to a column in WHERE (for example WHERE UPPER(name) = 'ANA SILVA') can prevent the use of indexes, something we will see in week 7.

Numeric functions and COALESCE

ROUND(x, n) rounds to n decimals; CEIL and FLOOR round up and down; ABS gives the absolute value; the % operator gives the remainder of an integer division (PostgreSQL also has MOD). A classic detail: dividing two integers drops the decimals (7 / 2 is 3), so to get 3.5 you must convert one of them to decimal with CAST(7 AS NUMERIC) / 2. COALESCE(a, b, ...) returns the first value that is not NULL: it is the standard way to supply a default value.

sql
SELECT name,
       price,
       ROUND(price * 1.21, 1) AS price_vat,
       CEIL(price) AS rounded_up,
       stock % 10 AS remainder
FROM products;

-- Integer division vs decimal division
SELECT 7 / 2 AS int_division, CAST(7 AS NUMERIC) / 2 AS decimal_division;

-- Show 'no email' instead of NULL
SELECT name, COALESCE(email, 'no email') AS contact FROM customers;

Date functions

Dates are a classic source of differences between engines. In PostgreSQL, CURRENT_DATE gives today's date, EXTRACT(YEAR FROM date) pulls out a part (YEAR, MONTH, DAY), DATE_TRUNC('month', date) cuts a date to the start of its month, and adding or subtracting numbers to a date adds or subtracts days. TO_CHAR formats a date as text. MySQL uses YEAR(), MONTH() and DATE_FORMAT(); SQLite uses strftime(). The standard only guarantees EXTRACT and CURRENT_DATE, which is why it pays to prefer them.

sql
-- PostgreSQL date functions
SELECT order_id,
       order_date,
       EXTRACT(MONTH FROM order_date) AS month_number,
       DATE_TRUNC('month', order_date) AS month_start,
       order_date + 7 AS expected_delivery,
       TO_CHAR(order_date, 'DD/MM/YYYY') AS formatted
FROM orders
WHERE EXTRACT(YEAR FROM order_date) = 2024;

-- Days since each customer signed up
SELECT name, CURRENT_DATE - signup_date AS days_as_customer FROM customers;

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →