SQL · Module 5 · Lesson 11 min read

String Functions

Combining text

  • || – first || ' ' || last (NULL if any part is NULL)
  • concat(a, b, …) – ignores NULLs ✅
  • concat_ws(', ', a, b, c) – "with separator", skips NULLs

Changing case

  • upper(), lower(), initcap() (Title Case Each Word)

Length & trimming

  • length(s) – number of characters
  • trim(s), ltrim(), rtrim() – remove spaces (or other characters: trim('.' FROM s))

Extracting parts

  • left(s, n), right(s, n)
  • substring(s FROM start FOR length) or substr(s, start, length) – positions start at 1
  • split_part(s, delimiter, n) – the nth piece: split_part('a@b.com', '@', 2) → b.com
  • position('@' IN email) / strpos(email, '@') – where a substring is (0 if not found)

Replacing & padding

  • replace(s, 'old', 'new') – replaces all occurrences
  • translate(s, 'abc', 'xyz') – character by character
  • lpad('7', 3, '0') → 007, rpad()
  • repeat('*', 5), reverse(s)

Formatting

  • format('%s spent Rs. %s', name, amount) – like printf
  • to_char(number, '99,99,999.00') – number formatting (Unit 5.2)

Splitting & joining

  • string_to_array('a,b,c', ',') → {a,b,c}
  • string_agg(col, ', ') – join many rows into one string (Unit 6)

Case-insensitive comparison

lower(email) = lower('Asha@Example.com') or use ILIKE, or the citext extension

Example

SQL
SELECT
  name,
  upper(name)                             AS shout,
  length(name)                            AS chars,
  split_part(name, ' ', 1)                AS first_name,
  left(name, 1) || '.'                    AS initial,
  split_part(email, '@', 2)               AS email_domain,
  concat_ws(', ', name, city)             AS label        -- Hari has no city: "Hari Shrestha"
FROM users
ORDER BY id;

-- Cleaning messy input
SELECT trim('   Kathmandu  ')            AS trimmed,       -- 'Kathmandu'
       initcap('ravi THAPA')             AS proper,        -- 'Ravi Thapa'
       replace('98-0123-4567', '-', '')  AS digits,        -- '9801234567'
       lpad('42', 6, '0')                AS invoice_no,    -- '000042'
       reverse('stressed')               AS dessert;       -- 'desserts'

-- Mask an email: a***@example.com
SELECT email,
       left(email, 1) || repeat('*', position('@' IN email) - 2) || substring(email FROM position('@' IN email)) AS masked
FROM users
WHERE id <= 2;
-- asha@example.com | a***@example.com
-- ravi@example.com | r***@example.com

-- format(): readable sentences
SELECT format('%s spent Rs. %s on %s', u.name, e.amount, e.title) AS sentence
FROM expenses e JOIN users u ON u.id = e.user_id
ORDER BY e.amount DESC
LIMIT 2;
-- Ravi Thapa spent Rs. 8500.00 on Paragliding