Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 28/ 160
02. Aggregations, Functions & Data Manipulation

String Functions (CONCAT, SUBSTRING, TRIM, UPPER, LOWER, REPLACE)

Clean and reshape text fields with everyday string functions.

BeginnerCONCAT · SUBSTRING / TRIM3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

String functions tidy up text: cut off extra spaces, make letters the same case, swap bits, or take a piece out.

Think of it like…

Tidying a pile of handwritten name cards before filing them: trim the edges, write every name the same way, fix common misspellings, and only then sort them.

Where you’ve seen it

Cleaning city names before grouping: SELECT INITCAP(LOWER(TRIM(city))) AS city, COUNT(*) FROM customers GROUP BY 1; turns 'pune ', 'PUNE' and 'Pune' into one 'Pune' group.

Words you’ll hear

TRIM / LTRIM / RTRIM
Remove spaces (or given characters) from both ends, the left or the right.
SUBSTRING(s FROM start FOR len)
Part of a string; positions start at 1.
CONCAT vs ||
Both join strings; they differ in how they handle NULL.
LENGTH vs CHAR_LENGTH
In MySQL, LENGTH counts bytes and CHAR_LENGTH counts characters.

Visual diagram

Loading interactive diagram

Theory & example queries

The everyday functions

TRIM(s) removes leading and trailing spaces; TRIM(BOTH 'x' FROM s) removes a specific character. UPPER, LOWER and (in PostgreSQL and Oracle) INITCAP normalise case. REPLACE(s, 'from', 'to') swaps every occurrence. SUBSTRING(s FROM 1 FOR 3), LEFT(s, 3) and RIGHT(s, 4) take pieces, such as the last four digits of a phone number.

POSITION('@' IN email) (or STRPOS in PostgreSQL) finds where a substring starts, which combines with SUBSTRING to split values: the domain of an email is SUBSTRING(email FROM POSITION('@' IN email) + 1). LPAD and RPAD pad to a fixed width, such as zero-padding invoice numbers.

Email domainsQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  LOWER(3    SUBSTRING(4      email5      FROM6        POSITION('@' IN email) + 17    )8  ) AS domain,9  COUNT(*)10FROM11  users12GROUP BY13  114ORDER BY15  2 DESC;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Users grouped by email domain3 sample rows
Users grouped by email domain
domaincount
example.com24
gmail.com17
company.test6

Note: Counts and domains are illustrative; only the domain portion after the last @ is grouped after lowercasing.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: TRIM + LOWER first, then SUBSTRING / REPLACE for structure.

NULLs, bytes and case-insensitive matching

NULL handling differs. In PostgreSQL, first_name || ' ' || last_name is NULL if either part is NULL, while CONCAT() treats NULL as empty. In MySQL, CONCAT() returns NULL if any argument is NULL; CONCAT_WS(' ', first, last) skips NULLs. In MySQL, LENGTH counts bytes, so 'ñ' has length 2, while CHAR_LENGTH counts characters.

Case-insensitive comparison depends on collation: MySQL's default collations ignore case, PostgreSQL's don't. In PostgreSQL, compare LOWER(email) = LOWER($1) with an expression index on LOWER(email), or use the citext type. For data quality, clean values when they're written (and enforce it with a CHECK or a generated column) rather than in every query.

A NULL-safe full name

PostgreSQL: CONCAT_WS(' ', first_name, middle_name, last_name) skips NULL parts, so a missing middle name doesn't produce NULL or a double space.

Key takeaway: Know your dialect's NULL behaviour, and normalise data on write.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Profiling

Inspect the mess

Look at distinct values and their lengths to spot spaces, case variations and stray characters.

SQL at this step
1SELECT2  city,3  LENGTH(city),4  COUNT(*)5FROM6  customers7GROUP BY8  1,9  2
What to watch at this step
Find
near-duplicates
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

String functions clean and reshape text. TRIM removes surrounding spaces, UPPER/LOWER change case, REPLACE swaps substrings, SUBSTRING (or SUBSTR) takes part of a string (positions start at 1), CONCAT or || joins strings, and LENGTH or CHAR_LENGTH measures them. They're how imported, messy data becomes something you can group, join and compare.

Why it matters: Real data has trailing spaces, inconsistent capitalisation and stray characters, so "Pune", "pune " and "PUNE" become three different cities in a report. Knowing the functions, and their NULL and dialect quirks, is basic for any analyst or backend role.

When to reach for it

  • Cleaning imported CSVs and form data
  • Building display names and labels
  • Extracting parts of identifiers, emails and codes

When to avoid or be careful

  • Grouping or joining on raw, uncleaned text
  • Using || in PostgreSQL when any part can be NULL
  • Applying LOWER() to an indexed column in WHERE without an expression index

Cleaning in queries vs on write vs generated columns

Clean inside each query
Best for: One-off analysis of messy data

Strengths: No schema changes.

Watch out: Repeated everywhere; functions on columns prevent index use.

Clean on write (app or constraint)
Best for: Operational data that must stay consistent

Strengths: Every query sees clean data; indexes work.

Watch out: Needs a one-time cleanup of existing rows.

Generated / expression-indexed columns
Best for: Keeping the original while querying a normalised form

Strengths: Original value preserved; normalised version indexed.

Watch out: Extra storage and slightly more complex schema.

Interview signals & numbers to know

When this topic comes up

  • “The same city appears three times in the report”
  • “Extract the domain from the email”
  • Trailing spaces in data
  • Case-insensitive search
  • Names coming out as NULL

Benchmarks & rules of thumb

1 -
first position in SQL strings (not 0)
NULL -
result of 'a' || NULL in PostgreSQL
2 -
MySQL LENGTH of 'ñ' (bytes)

Common mistakes & follow-ups

Common interview mistakes

  • Concatenating first and last names with || and getting NULL for everyone without a last name.
  • Using 0-based positions with SUBSTRING and cutting off the first character.
  • Comparing emails without LOWER/TRIM and creating duplicate accounts.

Likely interviewer follow-ups

  • How would you find customers whose names differ only by case or spaces?
  • What's the difference between CONCAT and || when a value is NULL?
  • How would you make case-insensitive email lookups fast in PostgreSQL?
Interview tip: Mention data quality, not just syntax: clean on write, and normalise with TRIM and LOWER before grouping. That turns a function list into an engineering answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply String Functions (CONCAT, SUBSTRING, TRIM, UPPER, LOWER, REPLACE) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
NULL Handling Functions (COALESCE, NULLIF, IFNULL)
Next topic
String Splitting & Pattern Extraction (SPLIT_PART, POSITION, LENGTH)