String & Math Functions

Transform, format, and compute in pure SQL

Tutorial 8 of 11


Over 30 built-in scalar functions are available for string manipulation, math, and conditional logic. This tutorial walks through the most useful ones with a product catalog dataset. Every function runs in the block-oriented executor—35% faster than PostgreSQL on the scalar_functions benchmark.

1. Schema and seed data

CREATE TABLE products (
    id       SERIAL PRIMARY KEY,
    name     TEXT NOT NULL,
    sku      TEXT NOT NULL,
    price    FLOAT NOT NULL,
    discount FLOAT,
    category TEXT,
    notes    TEXT
);

INSERT INTO products (name, sku, price, discount, category, notes) VALUES
    ('Wireless Mouse',     'WM-2024-PRO',  49.99,  0.10, 'Electronics', 'Best seller'),
    ('USB-C Hub',          'HUB-7PORT',    34.50,  NULL, 'Electronics', 'New arrival'),
    ('Standing Desk',      'DESK-ADJ-60',  599.00, 0.15, 'Furniture',   NULL),
    ('Ergonomic Chair',    'CHAIR-ERG-V2', 449.99, 0.20, 'Furniture',   'Updated model'),
    ('Mechanical Keyboard','KB-MX-BLUE',    89.95, 0.05, 'Electronics', 'Cherry MX Blue'),
    ('Monitor Arm',        'ARM-DUAL-27',  129.00, NULL, 'Accessories', NULL),
    ('Desk Lamp',          'LAMP-LED-DIM', 45.00,  0.10, 'Accessories', 'Dimmable LED');

2. String case and length

UPPER, LOWER, and LENGTH are the workhorses of string processing. Use them for normalization, display formatting, and validation.

SELECT name,
       UPPER(name) AS upper_name,
       LOWER(sku) AS lower_sku,
       LENGTH(name) AS name_len
FROM products
WHERE LENGTH(name) > 10
ORDER BY name_len DESC;

Result

nameupper_namelower_skuname_len
Mechanical KeyboardMECHANICAL KEYBOARDkb-mx-blue19
Ergonomic ChairERGONOMIC CHAIRchair-erg-v215
Wireless MouseWIRELESS MOUSEwm-2024-pro14
Standing DeskSTANDING DESKdesk-adj-6013
Monitor ArmMONITOR ARMarm-dual-2711

3. SUBSTRING and REPLACE

SUBSTRING(str FROM start FOR length) extracts a portion. REPLACE(str, from, to) swaps substrings.

SELECT sku,
       SUBSTRING(sku FROM 1 FOR 3)
         AS prefix,
       REPLACE(sku, '-', '/')
         AS slash_sku
FROM products
ORDER BY sku;

Result

skuprefixslash_sku
ARM-DUAL-27ARMARM/DUAL/27
CHAIR-ERG-V2CHACHAIR/ERG/V2
DESK-ADJ-60DESDESK/ADJ/60
HUB-7PORTHUBHUB/7PORT
KB-MX-BLUEKB-KB/MX/BLUE
LAMP-LED-DIMLAMLAMP/LED/DIM
WM-2024-PROWM-WM/2024/PRO

4. CONCAT and string concatenation

CONCAT(a, b, ...) joins strings together. Unlike the || operator, CONCAT treats NULL as an empty string.

SELECT name,
       CONCAT(category, ': ', name)
         AS full_label
FROM products
ORDER BY category, name;

Result

namefull_label
Desk LampAccessories: Desk Lamp
Monitor ArmAccessories: Monitor Arm
Mechanical KeyboardElectronics: Mechanical Keyboard
USB-C HubElectronics: USB-C Hub
Wireless MouseElectronics: Wireless Mouse
Ergonomic ChairFurniture: Ergonomic Chair
Standing DeskFurniture: Standing Desk

5. Math functions: ABS, ROUND, POWER, MOD

Compute discounted prices with ROUND, use ABS for absolute values, and MOD for modular arithmetic.

SELECT name, price,
       COALESCE(discount, 0) AS disc,
       ROUND(price * (1 - COALESCE(
         discount, 0))::numeric, 2)
         AS sale_price,
       ABS(price - 100) AS dist_from_100,
       MOD(id, 3) AS group_num
FROM products
ORDER BY sale_price DESC;

Result

namepricediscsale_pricedist_from_100group_num
Standing Desk5990.15509.154990
Ergonomic Chair449.990.2359.99349.991
Monitor Arm1290129290
Mechanical Keyboard89.950.0585.4510.052
Wireless Mouse49.990.144.9950.011
Desk Lamp450.140.5551
USB-C Hub34.5034.565.52

6. COALESCE and NULLIF

COALESCE(a, b, ...) returns the first non-NULL argument. NULLIF(a, b) returns NULL if a = b, otherwise returns a. Together they handle missing data gracefully.

SELECT name,
       COALESCE(notes, 'No notes')
         AS display_notes,
       COALESCE(discount, 0) * 100
         AS disc_pct,
       NULLIF(category, 'Electronics')
         AS non_elec_cat
FROM products
ORDER BY name;

Result

namedisplay_notesdisc_pctnon_elec_cat
Desk LampDimmable LED10Accessories
Ergonomic ChairUpdated model20Furniture
Mechanical KeyboardCherry MX Blue5NULL
Monitor ArmNo notes0Accessories
Standing DeskNo notes15Furniture
USB-C HubNew arrival0NULL
Wireless MouseBest seller10NULL

7. CASE WHEN for conditional logic

CASE WHEN is SQL’s if/else. Use it to categorize, bucket, or transform values conditionally.

SELECT name, price,
       CASE
         WHEN price >= 400 THEN 'premium'
         WHEN price >= 80  THEN 'mid-range'
         ELSE 'budget'
       END AS tier,
       CASE
         WHEN discount IS NULL THEN 'full price'
         WHEN discount >= 0.15 THEN 'big sale'
         ELSE 'small discount'
       END AS pricing
FROM products
ORDER BY price DESC;

Result

namepricetierpricing
Standing Desk599premiumbig sale
Ergonomic Chair449.99premiumbig sale
Monitor Arm129mid-rangefull price
Mechanical Keyboard89.95mid-rangesmall discount
Wireless Mouse49.99budgetsmall discount
Desk Lamp45budgetsmall discount
USB-C Hub34.5budgetfull price

What you learned

In this tutorial you transformed a 7-product catalog using 12 scalar functions and conditional expressions: