Your First Queries · Lesson 5 of 64

SQL Text Functions

What you will learn

  • How to join text with ||
  • How to change case and measure text with UPPER, LOWER and LENGTH
  • How to cut pieces out with SUBSTR and find a position with INSTR
  • How to clean text with TRIM and REPLACE
  • What happens when a text value is NULL

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. Join text with ||

The || operator glues two pieces of text together. Constants go in single quotes:

SELECT first_name || ' ' || last_name AS full_name, city
FROM customers ORDER BY customer_id LIMIT 5;
full_name    city
-----------  ------------
Vik Ahmed    Leeds
Wanda Ahmed  Leeds
Dana Costa   Cairo
Noah Nair    Porto Alegre
Hugo Rossi   Porto Alegre
(5 rows)
SELECT full_name || ' lives in ' || city AS sentence
FROM customers ORDER BY customer_id LIMIT 5;
sentence
----------------------------
Chen Park lives in Lima
Rafi Uddin lives in Manila
Grace Kamau lives in Toronto
Mei Bianchi lives in Osaka
Farid Lee lives in Austin
(5 rows)
SELECT last_name || ', ' || first_name AS listed_name, enrolled_year
FROM students ORDER BY student_id LIMIT 5;
listed_name    enrolled_year
-------------  -------------
Khan, Vera              2026
Haque, Elena            2024
Garcia, Chloe           2025
Meyer, Quinn            2023
Torres, Dana            2025
(5 rows)

Numbers are turned into text when you join them to text, so 'Year ' || 2026 gives Year 2026.

In other databases. PostgreSQL also uses || for joining text (its documentation shows 'Post' || 'greSQL'). MySQL does not by default: there || means logical OR unless a special mode (PIPES_AS_CONCAT) is switched on, and you join text with the CONCAT() function. This comes from the official documentation and was not run here.

2. Case and length

UPPER and LOWER change the case, and LENGTH counts characters:

SELECT city, UPPER(city) AS shouting, LOWER(email) AS quiet_email, LENGTH(email) AS email_length
FROM customers ORDER BY customer_id LIMIT 5;
city          shouting      quiet_email                email_length
------------  ------------  -------------------------  ------------
Leeds         LEEDS         vik.ahmed37@example.com              23
Leeds         LEEDS         wanda.ahmed70@example.com            25
Cairo         CAIRO         dana.costa5@example.com              23
Porto Alegre  PORTO ALEGRE  noah.nair50@example.com              23
Porto Alegre  PORTO ALEGRE  hugo.rossi88@example.com             24
(5 rows)
SELECT full_name, UPPER(full_name) AS shouting, LENGTH(full_name) AS name_length
FROM customers ORDER BY customer_id LIMIT 5;
full_name    shouting     name_length
-----------  -----------  -----------
Chen Park    CHEN PARK              9
Rafi Uddin   RAFI UDDIN            10
Grace Kamau  GRACE KAMAU           11
Mei Bianchi  MEI BIANCHI           11
Farid Lee    FARID LEE              9
(5 rows)
SELECT last_name, UPPER(last_name) AS shouting, LENGTH(email) AS email_length
FROM students ORDER BY student_id LIMIT 5;
last_name  shouting  email_length
---------  --------  ------------
Khan       KHAN                27
Haque      HAQUE               29
Garcia     GARCIA              30
Meyer      MEYER               29
Torres     TORRES              29
(5 rows)

A common use is to compare text without worrying about case: LOWER(city) = 'leeds' matches Leeds, LEEDS and leeds.

3. Cut text with SUBSTR and INSTR

SUBSTR(text, start, length) returns part of a text. The first character is position 1. INSTR(text, small) returns the position where small first appears in text (0 if it does not):

SELECT SUBSTR('database', 1, 4) AS first_four, SUBSTR('database', 5) AS from_fifth, INSTR('database', 'b') AS position_of_b;
first_four  from_fifth  position_of_b
----------  ----------  -------------
data        base                    5
(1 row)
SELECT SUBSTR('database', 1, 4) AS first_four, SUBSTR('database', 5) AS from_fifth, INSTR('database', 'b') AS position_of_b;
first_four  from_fifth  position_of_b
----------  ----------  -------------
data        base                    5
(1 row)
SELECT SUBSTR('database', 1, 4) AS first_four, SUBSTR('database', 5) AS from_fifth, INSTR('database', 'b') AS position_of_b;
first_four  from_fifth  position_of_b
----------  ----------  -------------
data        base                    5
(1 row)

Together they can pull a piece out of a column. Here the text before the @ of an email address, and the text after it:

SELECT email,
       SUBSTR(email, 1, INSTR(email, '@') - 1) AS username,
       SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM customers ORDER BY customer_id LIMIT 4;
email                      username       domain
-------------------------  -------------  -----------
vik.ahmed37@example.com    vik.ahmed37    example.com
wanda.ahmed70@example.com  wanda.ahmed70  example.com
dana.costa5@example.com    dana.costa5    example.com
noah.nair50@example.com    noah.nair50    example.com
(4 rows)

The first word of a name is the text before the first space:

SELECT full_name,
       SUBSTR(full_name, 1, INSTR(full_name, ' ') - 1) AS first_word,
       SUBSTR(full_name, INSTR(full_name, ' ') + 1) AS rest
FROM customers ORDER BY customer_id LIMIT 4;
full_name    first_word  rest
-----------  ----------  -------
Chen Park    Chen        Park
Rafi Uddin   Rafi        Uddin
Grace Kamau  Grace       Kamau
Mei Bianchi  Mei         Bianchi
(4 rows)
SELECT email,
       SUBSTR(email, 1, INSTR(email, '@') - 1) AS username,
       SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM students ORDER BY student_id LIMIT 4;
email                           username        domain
------------------------------  --------------  ---------------
vera.khan38@student.example     vera.khan38     student.example
elena.haque48@student.example   elena.haque48   student.example
chloe.garcia13@student.example  chloe.garcia13  student.example
quinn.meyer73@student.example   quinn.meyer73   student.example
(4 rows)

Read the first expression slowly: INSTR finds the position of the separator, minus one gives the length of the part before it.

4. Clean text with TRIM and REPLACE

TRIM removes spaces from both ends, and REPLACE(text, old, new) swaps every occurrence of old for new:

SELECT TRIM('   padded   ') AS trimmed, LENGTH(TRIM('   padded   ')) AS trimmed_length,
       REPLACE('2026/03/15', '/', '-') AS replaced;
trimmed  trimmed_length  replaced
-------  --------------  ----------
padded                6  2026-03-15
(1 row)
SELECT TRIM('   padded   ') AS trimmed, LENGTH(TRIM('   padded   ')) AS trimmed_length,
       REPLACE('2026/03/15', '/', '-') AS replaced;
trimmed  trimmed_length  replaced
-------  --------------  ----------
padded                6  2026-03-15
(1 row)
SELECT TRIM('   padded   ') AS trimmed, LENGTH(TRIM('   padded   ')) AS trimmed_length,
       REPLACE('2026/03/15', '/', '-') AS replaced;
trimmed  trimmed_length  replaced
-------  --------------  ----------
padded                6  2026-03-15
(1 row)

Phone numbers in the Shop have a space after the country code. Remove it:

SELECT phone, REPLACE(phone, ' ', '') AS compact_phone
FROM customers WHERE phone IS NOT NULL ORDER BY customer_id LIMIT 4;
phone         compact_phone
------------  -------------
+35 49854883  +3549854883
+58 13864688  +5813864688
+48 26805141  +4826805141
+49 13135594  +4913135594
(4 rows)

Birth dates are written 1956-03-20. Swap the dashes for slashes:

SELECT birth_date, REPLACE(birth_date, '-', '/') AS slashed
FROM customers ORDER BY customer_id LIMIT 4;
birth_date  slashed
----------  ----------
1956-03-20  1956/03/20
1990-10-10  1990/10/10
1961-11-15  1961/11/15
1977-11-18  1977/11/18
(4 rows)

Guardian names are written like Amir Khan. Remove the space to make a code-like text:

SELECT guardian_name, REPLACE(guardian_name, ' ', '_') AS joined_by_underscore
FROM students WHERE guardian_name IS NOT NULL ORDER BY student_id LIMIT 4;
guardian_name  joined_by_underscore
-------------  --------------------
Amir Khan      Amir_Khan
Nadia Haque    Nadia_Haque
Mina Garcia    Mina_Garcia
Femi Meyer     Femi_Meyer
(4 rows)

(WHERE ... IS NOT NULL keeps only rows that have a value; chapter 2 explains it.)

5. Text and NULL

If any part of a joined text is NULL, the whole result is NULL, just as with arithmetic (lesson 1.3):

SELECT 'Hello, ' || NULL AS joined, LENGTH(NULL) AS length_of_null;
joined  length_of_null
------  --------------
NULL    NULL
(1 row)
SELECT 'Hello, ' || NULL AS joined, LENGTH(NULL) AS length_of_null;
joined  length_of_null
------  --------------
NULL    NULL
(1 row)
SELECT 'Hello, ' || NULL AS joined, LENGTH(NULL) AS length_of_null;
joined  length_of_null
------  --------------
NULL    NULL
(1 row)

The Shop has customers without a phone number, so joining a name to a phone gives NULL for them:

SELECT first_name || ': ' || phone AS name_and_phone
FROM customers ORDER BY customer_id LIMIT 4;
name_and_phone
------------------
Vik: +35 49854883
NULL
Dana: +58 13864688
Noah: +48 26805141
(4 rows)

Every bank customer has a name, so the joins above never gave NULL. Missing values are easy to meet in other tables, and chapter 2 shows how to replace them with a default.

Some students have no guardian recorded, so joining a name to a guardian can give NULL:

SELECT first_name || ' (guardian: ' || guardian_name || ')' AS student_and_guardian
FROM students ORDER BY student_id LIMIT 12;
student_and_guardian
-----------------------------
Vera (guardian: Amir Khan)
Elena (guardian: Nadia Haque)
Chloe (guardian: Mina Garcia)
Quinn (guardian: Femi Meyer)
Dana (guardian: Ana Torres)
Nadia (guardian: Sam Patel)
NULL
Hugo (guardian: Gita Abdi)
NULL
Hugo (guardian: Gita Torres)
Olga (guardian: Priya Rahman)
Xavi (guardian: Sam Sato)
(12 rows)

Chapter 2 shows how to test for NULL and how to replace it with a default (COALESCE).

Worked example: a short code from a name

A report wants a short code made of the first three letters of a name in capitals, then the length of the name.

Step Expression For Mei Bianchi
First three letters SUBSTR(name, 1, 3) Mei
In capitals UPPER(SUBSTR(name, 1, 3)) MEI
Length LENGTH(name) 11
Join them UPPER(SUBSTR(name, 1, 3)) \|\| '-' \|\| LENGTH(name) MEI-11

Each step is a small function; the full expression is just the steps put inside one another. The name is made up.

Common mistakes

  • Counting positions from 0. In SQL the first character is position 1.
  • Forgetting the - 1 or + 1 when cutting around a separator found with INSTR.
  • Expecting a number back from ||. The result is text.
  • Forgetting NULL. One missing piece makes the whole joined text NULL.
  • Using || in MySQL without checking: there it means OR by default.

Key takeaways

  • || joins text; numbers become text when joined.
  • UPPER, LOWER and LENGTH change case and measure text.
  • SUBSTR(text, start, length) cuts a piece (positions start at 1); INSTR finds where something is.
  • TRIM and REPLACE clean text.
  • Any text expression with NULL becomes NULL.

Practice

1. What does SELECT 'SQL' || ' ' || 'Basics'; return?

Show answer

SQL Basics.

2. What does SUBSTR('database', 2, 3) return?

Show answer

ata: three characters starting at position 2.

3. What does INSTR('a-b-c', '-') return?

Show answer

2, the position of the first dash.

4. How do you remove the spaces at both ends of a text?

Show answer

With TRIM(text).

5. What does 'Total: ' || NULL return?

Show answer

NULL. A missing value makes the whole joined text missing.

6. Write an expression that returns the part of an email address after the @.

Show answer

SUBSTR(email, INSTR(email, '@') + 1)