SQL string functions

Text data is messy, so string functions are everyday tools: building full names, cleaning emails, extracting parts of codes.

In PostgreSQL, || joins text together. UPPER and LOWER change case, LENGTH counts characters, and SUBSTRING and REPLACE extract and edit text.

Syntax

first || ' ' || last
UPPER(text), LOWER(text), LENGTH(text)
SUBSTRING(text FROM 1 FOR 3), REPLACE(text, 'a', 'b')

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

string-functions.sql · PostgreSQL
Loading editor…

Examples

1. Concatenate

SELECT first_name || ' ' || last_name AS full_name FROM employees;

One column with the full name.

2. Change case and measure

SELECT UPPER(name), LENGTH(name) FROM products;

Uppercase names and their length.

3. Extract a part

SELECT email, SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain FROM customers WHERE email IS NOT NULL;

The domain of each email.

Common mistakes

  • Concatenating with NULL: 'a' || NULL is NULL. Use CONCAT() or COALESCE when values can be missing.

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 10 pts

Return each employee's full name as one column, in the form first_name last_name (with a space).

challenge.sql · PostgreSQL
Loading editor…

FAQ

CONCAT() or ||?

Both work in PostgreSQL. CONCAT() treats NULL as an empty string; || returns NULL.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →