Tier 3 · Intermediate

String Functions (LENGTH, UPPER, LOWER, TRIM, SUBSTRING) in SQL

By Owen Middleton · Updated September 2026 · Examples run on PostgreSQL 17

What are String Functions in SQL?

LENGTH, UPPER, LOWER, TRIM, and SUBSTRING are the core tools for measuring, normalizing, and extracting pieces of string values.

String data in analytical work is rarely clean. Customer names arrive with inconsistent casing. Product codes have leading zeros or trailing spaces. Dates are embedded inside longer strings and need to be sliced out. These five functions handle the most common cleaning and extraction tasks, one row at a time — each operates on one value and returns one result. Nothing is grouped or aggregated.

What do LENGTH, UPPER, LOWER, TRIM and SUBSTRING do?

LENGTH counts characters. UPPER and LOWER convert case. TRIM removes characters from the edges. SUBSTRING extracts a slice starting at a given position. Here's what they look like on real data:

SELECT
  name,
  LENGTH(name) AS name_length,
  UPPER(name) AS name_upper,
  LOWER(name) AS name_lower,
  TRIM(name) AS name_trimmed
FROM customers
LIMIT 5

How do you strip specific characters with TRIM?

TRIM deserves a closer look. By default it removes spaces from both ends. You can also specify which characters to strip and which side to trim from:

TRIM('   hello   ')             -- 'hello'
TRIM(LEADING '0' FROM '007')    -- '7'
LTRIM('###note', '#')           -- 'note'

The characters argument specifies a set of characters to remove, not a prefix or substring. TRIM('xy' FROM 'xyhelloyx') strips any leading or trailing x or y characters — one by one, until it hits a character not in the set.

How do you extract part of a string in PostgreSQL?

SUBSTRING extracts a slice by position. Positions are 1-indexed: the first character is position 1.

SUBSTRING('order-2024-03-15', 7, 10)   -- '2024-03-15'
SUBSTRING('SKU-4821-B', 5, 4)          -- '4821'

The first argument is the string, the second is the start position, the third is the number of characters to return. Omit the length and SUBSTRING returns everything from the start position to the end of the string.

A few edge cases worth knowing: requesting a SUBSTRING start position beyond the end of the string returns an empty string, not an error or NULL. LENGTH('') returns 0. UPPER('') returns ''. The functions handle empty strings gracefully without any special handling needed.

What does LENGTH(NULL) return in SQL?

The one thing that trips people up: all five functions return NULL when the input is NULL.

LENGTH(NULL) is NULL, not 0. TRIM(NULL) is NULL, not an empty string. If a column can contain NULLs and you need a non-NULL result, wrap with COALESCE: LENGTH(COALESCE(name, '')) returns 0 for NULL names instead of NULL. This pattern applies to all five functions — always consider whether a NULL input would produce a NULL output that would silently flow through the rest of your query.

Check your understanding

You run TRIM('ab' FROM 'ababHELLOabab'). What does PostgreSQL return?

Practice String Functions in SQL

Practice · easy ecommerce · Brightlane

Brightlane's customer data normalization pipeline standardizes product names to uppercase for case-insensitive matching.

Write a query to return the uppercase version of the string 'Wireless Keyboard'.

Output:

  • A single row with one column, normalized_name, containing the uppercased string.
Schema · ecommerce5 tables? = nullable
categories
idinteger
nametext
parent_id?integer
products
idinteger
nametext
category_id?integer
pricenumeric
stock_qtyinteger
attributes?jsonb
order_items
idinteger
order_id?integer
product_id?integer
quantityinteger
unit_pricenumeric
customers
idinteger
nametext
emailtext
city?text
countrytext
created_attimestamptz
is_activeboolean
orders
idinteger
customer_id?integer
ordered_attimestamptz
statustext
total_amountnumeric

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution

The full breakdown walks through the shape, each clause, why this approach beats the alternatives, and the trap to avoid.

See the full worked solution

9 String Functions practice problems

Start learning to practice all 9 String Functions problems, with instant grading and mastery tracking.

Common questions about String Functions

Does LENGTH count characters or bytes?

Characters. A four-letter word with an accent returns four, even though it occupies five bytes of storage. Reach for OCTET_LENGTH when the byte count is what you actually need, which is usually a storage question rather than an analysis one.

How do you trim only the leading spaces?

Say which end you mean with LEADING or TRAILING. Plain TRIM removes from both, so it is the wrong tool when the padding on one side is meaningful, as it is in fixed-width data pulled out of an export.

What does SUBSTRING return if it starts past the end of the string?

An empty string, not NULL and not an error. That matters when the result feeds a comparison, because an empty string is a value that compares normally while a NULL would quietly drop the row.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.