SQL String Functions: Length, Case, Trim, Substring, Replace and Collations
The everyday SQL string functions and how they differ between databases: length in characters and bytes, UPPER, LOWER and INITCAP, concatenation and NULL, SUBSTRING, LEFT, RIGHT and POSITION, TRIM, REPLACE and TRANSLATE, padding and FORMAT, case-insensitive comparison and collations.
kvi5hnuCode Sprout team member12 min readOn this page
Text is everywhere in a database: names, emails, codes, addresses, descriptions. Much of it arrives messy, with extra spaces, inconsistent capitals and stray punctuation, and much of it needs reshaping for reports, such as a first name, a padded code or a label made from several columns.
SQL has a set of string functions for this. The core ones exist in every database, but their names and details differ more than for any other group of functions, so this article gives the PostgreSQL version first and the main differences after each topic. Article 37 builds on these functions to split, aggregate and extract text, and article 42 covers regular expressions.
Length, case and concatenation
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Length, case and concatenation
SELECT name,
LENGTH(name) AS chars,
UPPER(name) AS upper_name,
LOWER(name) AS lower_name,
INITCAP(LOWER(name)) AS title_case,
name || ' (' || category || ')' AS label
FROM products
WHERE product_id IN (1, 3, 7)
ORDER BY product_id;
-- Characters versus bytes: 'é' and '€' take more than one byte in UTF-8
SELECT word,
CHAR_LENGTH(word) AS characters,
OCTET_LENGTH(word) AS bytes
FROM (VALUES ('cafe'), ('café'), ('€5')) AS t(word);
name | chars | upper_name | lower_name | title_case | label
-----------------+-------+-----------------+-----------------+-----------------+----------------------------
Ridge 2 tent | 12 | RIDGE 2 TENT | ridge 2 tent | Ridge 2 Tent | Ridge 2 tent (tents)
Glow head torch | 15 | GLOW HEAD TORCH | glow head torch | Glow Head Torch | Glow head torch (lighting)
Merino socks | 12 | MERINO SOCKS | merino socks | Merino Socks | Merino socks (clothing)
(3 rows)
word | characters | bytes
------+------------+-------
cafe | 4 | 4
café | 4 | 5
€5 | 2 | 4
(3 rows)
LENGTH(s)or the standardCHAR_LENGTH(s)returns the number of characters.UPPERandLOWERchange case.INITCAPcapitalises the first letter of each word and lowers the rest, so applying it toLOWER(name)gives title case. It's simple-minded, though: it turnsMcDonaldintoMcdonaldandvan der BergintoVan Der Berg, so don't use it to "fix" people's names in stored data.||joins strings, as standard SQL specifies.
The second query shows the difference between characters and bytes. Text is stored as UTF-8, where letters with accents take 2 bytes and symbols like € take 3. CHAR_LENGTH counts characters, and OCTET_LENGTH counts bytes, which matters for storage limits and byte-based protocols.
Watch out in other databases:
- MySQL:
LENGTHreturns bytes, not characters, soLENGTH('café')is 5. UseCHAR_LENGTHfor characters. - SQL Server:
LENcounts characters but ignores trailing spaces.DATALENGTHreturns bytes. - SQLite:
UPPERandLOWERonly change ASCII letters by default, soUPPER('é')staysé.
Concatenation and NULL
What happens when one part of a concatenation is NULL depends on the operator and the database:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- || returns NULL if any part is NULL; CONCAT and CONCAT_WS skip NULLs
SELECT name,
brand,
brand || ' ' || name AS with_pipes,
CONCAT(brand, ' ', name) AS with_concat,
CONCAT_WS(' / ', brand, name, category) AS with_separator,
COALESCE(brand || ' ', '') || name AS with_coalesce
FROM products
WHERE product_id IN (3, 4)
ORDER BY product_id;
name | brand | with_pipes | with_concat | with_separator | with_coalesce
------------------+--------+-----------------------+-----------------------+------------------------------------+-----------------------
Glow head torch | Lumen | Lumen Glow head torch | Lumen Glow head torch | Lumen / Glow head torch / lighting | Lumen Glow head torch
Basecamp lantern | (null) | (null) | Basecamp lantern | Basecamp lantern / lighting | Basecamp lantern
(2 rows)
The lantern has no brand. In PostgreSQL:
brand || ' ' || nameis NULL, because any operation with NULL gives NULL (article 8).CONCAT(a, b, ...)treats NULL arguments as empty strings, so it returns' Basecamp lantern', with a stray leading space.CONCAT_WS(separator, a, b, ...)("with separator") skips NULL arguments and their separators, which makes it ideal for joining optional parts, such as address lines.COALESCE(brand || ' ', '') || nameadds the brand and its space only when the brand exists, so the result is clean.
The rules elsewhere:
| Database | || | CONCAT with a NULL argument |
|---|---|---|
| PostgreSQL | concatenates; NULL if any part is NULL | skips NULLs |
| Oracle | concatenates; treats NULL as empty | takes exactly 2 arguments before 23ai (any number since); treats NULL as empty |
| SQL Server | concatenates in SQL Server 2025 and later; earlier versions use + (NULL if any part is NULL) | skips NULLs |
| MySQL | logical OR (deprecated), unless PIPES_AS_CONCAT is set | returns NULL |
| SQLite | concatenates; NULL if any part is NULL | skips NULLs (3.44+) |
CONCAT_WS exists in PostgreSQL, MySQL, SQL Server 2017+ and SQLite 3.44+, and skips NULLs in all of them. It's the most portable way to join optional parts.
Extracting part of a string
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Pieces of a string: SUBSTRING, LEFT, RIGHT and POSITION
SELECT name,
SUBSTRING(name FROM 1 FOR 4) AS first_four,
SUBSTRING(name, 6) AS from_sixth,
LEFT(name, 3) AS left_3,
RIGHT(name, 4) AS right_4,
POSITION(' ' IN name) AS first_space,
LEFT(name, POSITION(' ' IN name) - 1) AS first_word
FROM products
WHERE product_id IN (1, 5, 7)
ORDER BY product_id;
name | first_four | from_sixth | left_3 | right_4 | first_space | first_word
-------------------+------------+--------------+--------+---------+-------------+------------
Ridge 2 tent | Ridg | 2 tent | Rid | tent | 6 | Ridge
Trail 30 backpack | Trai | 30 backpack | Tra | pack | 6 | Trail
Merino socks | Meri | o socks | Mer | ocks | 7 | Merino
(3 rows)

SUBSTRING(s FROM start FOR length)is the standard form.SUBSTRING(s, start, length)andSUBSTR(s, start, length)are the common function forms. Leaving out the length takes everything to the end.- Positions start at 1, not 0, in every SQL database.
LEFT(s, n)andRIGHT(s, n)take the first or lastncharacters.POSITION(substring IN s)returns the position of the first occurrence, or 0 if it isn't found.
Combining them extracts variable-length pieces: LEFT(name, POSITION(' ' IN name) - 1) takes everything before the first space, the first word. If a name had no space, POSITION would return 0, and LEFT(name, -1) would return everything but the last character in PostgreSQL. Guard such expressions with CASE, or use SPLIT_PART (article 37), which handles the missing case cleanly.
Names in other databases:
| Task | PostgreSQL | MySQL | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
| find a substring | POSITION, STRPOS | LOCATE, INSTR, POSITION | CHARINDEX | INSTR | INSTR |
| substring | SUBSTRING, SUBSTR | SUBSTRING, SUBSTR | SUBSTRING (length required before SQL Server 2025) | SUBSTR | SUBSTR, SUBSTRING |
| left / right part | LEFT, RIGHT | LEFT, RIGHT | LEFT, RIGHT | SUBSTR(s, 1, n), SUBSTR(s, -n) | SUBSTR(s, 1, n), SUBSTR(s, -n) |
INSTR in Oracle takes a start position and an occurrence number, and CHARINDEX in SQL Server a start position, which helps when parsing.
Cleaning text: TRIM, REPLACE and TRANSLATE
Real data needs cleaning before it can be compared or deduplicated. The next table holds contact details typed in by hand:
-- Contact details typed in by hand
CREATE TABLE contacts (
contact_id INTEGER PRIMARY KEY,
full_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
phone VARCHAR(20)
);
INSERT INTO contacts VALUES
(1, ' asha rao ', 'Asha.Rao@Example.com', '+44 (0)20 7946 0018'),
(2, 'BEN OKAFOR', 'ben@example.com ', '020-7946-0019'),
(3, 'Chen Wei', ' chen.wei@example.COM', '(020) 7946 0020');
-- Cleaning text: TRIM, REPLACE, TRANSLATE, case
SELECT contact_id,
'[' || TRIM(full_name) || ']' AS trimmed,
INITCAP(TRIM(full_name)) AS tidy_name,
REPLACE(TRIM(full_name), ' ', ' ') AS single_spaces,
LOWER(TRIM(email)) AS clean_email,
TRANSLATE(phone, '+()- ', '') AS digits_only
FROM contacts
ORDER BY contact_id;
-- TRIM can remove other characters, from one or both ends
SELECT TRIM(BOTH '-' FROM '--ref-42--') AS both_ends,
TRIM(LEADING '0' FROM '000123') AS leading_zeros,
RTRIM('total....', '.') AS trailing_dots;
contact_id | trimmed | tidy_name | single_spaces | clean_email | digits_only
------------+--------------+------------+---------------+----------------------+---------------
1 | [asha rao] | Asha Rao | asha rao | asha.rao@example.com | 4402079460018
2 | [BEN OKAFOR] | Ben Okafor | BEN OKAFOR | ben@example.com | 02079460019
3 | [Chen Wei] | Chen Wei | Chen Wei | chen.wei@example.com | 02079460020
(3 rows)
both_ends | leading_zeros | trailing_dots
-----------+---------------+---------------
ref-42 | 123 | total
(1 row)
TRIM(s)removes spaces from both ends.LTRIMandRTRIMremove them from one end. The brackets in thetrimmedcolumn show that the leading and trailing spaces are gone.REPLACE(s, from, to)replaces every occurrence of a substring. Replacing a double space with a single one fixes'Chen Wei', but a run of three spaces would still leave two. For "any run of spaces", use a regular expression:REGEXP_REPLACE(s, '\s+', ' ', 'g')(article 42).TRANSLATE(s, from_chars, to_chars)replaces characters one for one: each character infrom_charsbecomes the character at the same position into_chars, and characters with no counterpart are deleted. With an emptyto_chars, it deletes every listed character, which strips phone punctuation in one call. (In Oracle, an empty string is NULL, so useTRANSLATE(s, 'x+()- ', 'x'). SQL Server'sTRANSLATErequires both lists to be the same length, so it can't delete characters: use nestedREPLACEthere.)LOWER(TRIM(email))normalises email addresses for comparison and storage.
The second query shows the full standard form, TRIM([LEADING | TRAILING | BOTH] chars FROM s), which removes characters other than spaces: dashes, leading zeros, trailing dots.
Clean text when it's stored, not in every query. A CHECK (email = LOWER(TRIM(email))) constraint, or a trigger or application code that normalises values on the way in, keeps the data consistent.
Padding, repeating and formatting
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Padding, repeating, reversing and formatting
SELECT LPAD(CAST(product_id AS text), 5, '0') AS padded_id,
RPAD(name, 18, '.') || price AS dotted,
REPEAT('*', stock / 10) AS stock_bar,
REVERSE(name) AS reversed
FROM products
WHERE product_id IN (1, 3, 7)
ORDER BY product_id;
SELECT FORMAT('%s costs %s (%s in stock)', name, price, stock) AS sentence
FROM products
WHERE product_id = 3;
padded_id | dotted | stock_bar | reversed
-----------+--------------------------+-----------+-----------------
00001 | Ridge 2 tent......249.99 | * | tnet 2 egdiR
00003 | Glow head torch...34.50 | **** | hcrot daeh wolG
00007 | Merino socks......16.00 | ******* | skcos onireM
(3 rows)
sentence
-------------------------------------------
Glow head torch costs 34.50 (40 in stock)
(1 row)
LPAD(s, length, fill)pads on the left to the given length, which turns1into00001for fixed-width codes.RPADpads on the right, here with dots to line up a price list. Both cut strings that are already longer than the length.REPEAT(s, n)repeats a string, which makes simple text bar charts: one star per 10 units of stock.REVERSEreverses a string. It's occasionally useful for "the last part after a separator" problems.FORMAT(template, values...)(PostgreSQL) fills%splaceholders, likeprintf. SQL Server'sFORMATis different: it formats a single number or date with a .NET format string. MySQL'sFORMAT(n, d)formats a number with thousands separators.
SQL Server has REPLICATE instead of REPEAT, and no LPAD: use RIGHT(REPLICATE('0', 5) + CAST(id AS varchar), 5). SQLite has no LPAD, RPAD or REPEAT built in.
Formatting for display usually belongs in the application or reporting tool, which knows the user's language and locale. Use SQL formatting for exports, fixed-width files and quick reports.
Case-insensitive comparison and collations
Whether 'Asha' = 'ASHA' is true depends on the collation: the rules a database uses to compare and sort text. It decides whether case and accents matter, and the order of characters.
-- Contact details typed in by hand
CREATE TABLE contacts (
contact_id INTEGER PRIMARY KEY,
full_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
phone VARCHAR(20)
);
INSERT INTO contacts VALUES
(1, ' asha rao ', 'Asha.Rao@Example.com', '+44 (0)20 7946 0018'),
(2, 'BEN OKAFOR', 'ben@example.com ', '020-7946-0019'),
(3, 'Chen Wei', ' chen.wei@example.COM', '(020) 7946 0020');
-- Case-sensitive by default: = and LIKE compare exact characters
SELECT COUNT(*) FILTER (WHERE email = 'asha.rao@example.com') AS exact_match,
COUNT(*) FILTER (WHERE LOWER(email) = 'asha.rao@example.com') AS lower_match,
COUNT(*) FILTER (WHERE email ILIKE 'asha.rao@%') AS ilike_match
FROM contacts;
-- A case-insensitive collation (ICU) makes = ignore case
CREATE COLLATION case_insensitive (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
SELECT 'Asha.Rao@Example.com' = 'asha.rao@example.com' COLLATE case_insensitive AS ci_equal;
-- Sort order depends on the collation too
SELECT word
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('Apple')) AS t(word)
ORDER BY word COLLATE "C";
SELECT word
FROM (VALUES ('apple'), ('Banana'), ('cherry'), ('Apple')) AS t(word)
ORDER BY word COLLATE "und-x-icu";
exact_match | lower_match | ilike_match
-------------+-------------+-------------
0 | 1 | 1
(1 row)
ci_equal
----------
t
(1 row)
word
--------
Apple
Banana
apple
cherry
(4 rows)
word
--------
apple
Apple
Banana
cherry
(4 rows)
- PostgreSQL's default collations are case-sensitive, so the exact comparison finds nothing: the stored email has capitals.
LOWER(email) = 'asha.rao@example.com'compares lowercase versions. To make it fast on a large table, create an index onLOWER(email)(article 55).ILIKEis PostgreSQL's case-insensitiveLIKE.- A nondeterministic ICU collation with
ks-level2("ignore case, respect accents") makes=itself case-insensitive. PostgreSQL 12 added nondeterministic collations, and PostgreSQL 18 made them work withLIKE.
The last two queries sort the same words with different collations. The "C" collation sorts by byte value, so all capital letters come before all lower-case letters: Apple, Banana, apple, cherry. A linguistic collation such as ICU's sorts as a dictionary would: apple, Apple, Banana, cherry. The "C" collation is faster and stable across operating system upgrades, while linguistic collations give the order users expect.
Defaults differ widely between databases:
| Database | Default comparison |
|---|---|
| PostgreSQL | case-sensitive (depends on the database's collation, set at creation) |
| MySQL 8 | case-insensitive and accent-insensitive (utf8mb4_0900_ai_ci) |
| SQL Server | usually case-insensitive (SQL_Latin1_General_CP1_CI_AS; CI = case-insensitive, AS = accent-sensitive) |
| Oracle | case-sensitive (NLS_COMP and NLS_SORT can change it) |
| SQLite | case-sensitive =, but LIKE is case-insensitive for ASCII letters |
So a query that finds 'asha@example.com' in MySQL may find nothing in PostgreSQL, and a unique constraint that allows both 'Asha' and 'asha' in PostgreSQL rejects the second in MySQL. When moving between databases, check the collations.
To compare without accents in PostgreSQL, the unaccent extension removes them: unaccent('café') = 'cafe'.
Character codes: ASCII and CHR
Every character has a numeric code point. ASCII(s) returns the code of the first character, and CHR(n) the character for a code. They're useful for writing characters that are hard to type, such as tabs (CHR(9)) and line breaks (CHR(10)), and for finding and cleaning control characters in imported data:
-- Characters and their code points
SELECT ASCII('A') AS code_a, CHR(65) AS char_65, ASCII('é') AS code_e_acute, CHR(8364) AS euro;
-- Finding and removing control characters, such as tabs and line breaks
SELECT REPLACE(REPLACE(note, CHR(9), '<TAB>'), CHR(10), '<LF>') AS visible,
POSITION(CHR(9) IN note) > 0 AS has_tab,
REGEXP_REPLACE(note, '[[:cntrl:]]+', ' ', 'g') AS cleaned
FROM (VALUES ('Ridge 2' || CHR(9) || 'tent'), ('two' || CHR(10) || 'lines'), ('plain')) AS v (note);
code_a | char_65 | code_e_acute | euro
--------+---------+--------------+------
65 | A | 233 | €
(1 row)
visible | has_tab | cleaned
------------------+---------+--------------
Ridge 2<TAB>tent | t | Ridge 2 tent
two<LF>lines | f | two lines
plain | f | plain
(3 rows)
In PostgreSQL with UTF-8, ASCII and CHR work with Unicode code points, not just ASCII: é is 233 and CHR(8364) is the euro sign. Oracle and MySQL have ASCII and CHR/CHAR, and SQL Server has ASCII, CHAR and UNICODE/NCHAR for Unicode.
Comparing strings by sound or similarity
Exact comparison fails for typing mistakes and spelling variants, such as Smith and Smyth. Several functions compare strings approximately:
SOUNDEX(s)encodes how an English word sounds, such asS530for bothSmithandSmyth, soWHERE SOUNDEX(name) = SOUNDEX('Smyth')finds both. It's built into Oracle, MySQL and SQL Server, whereDIFFERENCE(a, b)scores the match from 0 to 4. PostgreSQL has it in thefuzzystrmatchextension, withmetaphoneanddmetaphoneas better-sounding alternatives.- Edit distance, the number of single-character changes from one string to another, catches typos in any language:
levenshtein('tent', 'tnet')is 2 in PostgreSQL'sfuzzystrmatch, and SQL Server 2025 addedEDIT_DISTANCEandJARO_WINKLER_SIMILARITY. - Trigram similarity, with the
pg_trgmextension, scores how many three-letter sequences two strings share, and can use an index (article 55).
Sound-based codes are crude and English-centric. For searching names or products, trigram similarity or full-text search usually works better.
What's current
- PostgreSQL 18 added
casefold()for correct case-insensitive comparison in all languages (for example, Germanßmatchesss), thePG_UNICODE_FASTcollation with full Unicode case mapping, andLIKEsupport for nondeterministic collations. - PostgreSQL 17 added a built-in collation provider with a fast, stable
C.UTF-8collation that doesn't depend on the operating system. - SQLite 3.44 added
CONCATandCONCAT_WS. - MySQL 8.0's
utf8mb4_0900collations follow the Unicode Collation Algorithm and treat trailing spaces as significant (NO PAD), unlike older collations.
Common questions
Why does LENGTH return a larger number than the visible characters in MySQL?
MySQL's LENGTH counts bytes. Accented letters and symbols take more than one byte in UTF-8. Use CHAR_LENGTH.
Why is my concatenated column NULL?
One of the parts is NULL, and || (or + in SQL Server) returns NULL. Use CONCAT, CONCAT_WS or COALESCE on the nullable parts.
Do string positions start at 0 or 1? At 1, in every SQL database.
How do I compare strings ignoring case?
LOWER(a) = LOWER(b), ILIKE in PostgreSQL, or a case-insensitive collation. MySQL and SQL Server are usually case-insensitive by default.
How do I remove all non-digit characters?
TRANSLATE with a list of the characters to remove, or a regular expression: REGEXP_REPLACE(s, '[^0-9]', '', 'g') in PostgreSQL (article 42).
Why does ORDER BY name put Zebra before apple?
The collation sorts by byte value, as "C" does, so capitals come first. Use a linguistic collation, or sort by LOWER(name).
Summary
CHAR_LENGTHcounts characters andOCTET_LENGTHbytes. MySQL'sLENGTHcounts bytes, and SQL Server'sLENignores trailing spaces.UPPER,LOWERandINITCAPchange case.INITCAPis too simple for real names.||returns NULL if any part is NULL, except in Oracle.CONCAT_WSskips NULLs everywhere it exists.SUBSTRING,LEFT,RIGHTandPOSITIONextract text. Positions start at 1, andPOSITIONreturns 0 when nothing is found.TRIM,REPLACEandTRANSLATEclean text. Normalise data when it's stored.LPAD,RPAD,REPEATandFORMATbuild fixed-width and formatted output.- The collation decides case and accent sensitivity and sort order. PostgreSQL and Oracle are case-sensitive by default, and MySQL and SQL Server usually aren't.
Practice questions
Write a query that returns each customer's name and their initials, such as AR for Asha Rao, assuming every name has exactly one space.
Answer
SELECT name,
LEFT(name, 1) || SUBSTRING(name FROM POSITION(' ' IN name) + 1 FOR 1) AS initials
FROM customers
ORDER BY customer_id;
POSITION(' ' IN name) + 1 is the first letter of the surname. It gives AR, BO, CW, DC, EN and FH.
What do CONCAT('a', NULL, 'b') and 'a' || NULL || 'b' return in PostgreSQL, MySQL and Oracle?
Answer
PostgreSQL: 'ab' and NULL. MySQL: NULL for CONCAT, and || is a logical OR by default, returning 0 or NULL rather than a string. Oracle: before 23ai CONCAT takes only two arguments, so the first is an error (from 23ai it returns 'ab'), and || treats NULL as empty, returning 'ab'.
Write an expression that turns phone numbers like '(020) 7946-0020' into digits only, in PostgreSQL, without regular expressions.
Answer
TRANSLATE(phone, '()- ', '')
Each listed character has no counterpart in the empty replacement string, so it's deleted.
A unique constraint on users.email exists, but the table contains both Ben@example.com and ben@example.com. How is that possible in PostgreSQL, and how would you prevent it?
Answer
PostgreSQL's default collations are case-sensitive, so the two values are different. Create a unique index on the lowercase value, CREATE UNIQUE INDEX ON users (LOWER(email)), store emails in lower case, or use a case-insensitive collation for the column.
What does LPAD('12345678', 5, '0') return?
Answer
'12345'. When the string is longer than the target length, LPAD cuts it to that length rather than returning it unchanged, which can silently corrupt codes. Check lengths before padding.
Previous: SQL Data Types: Numbers, Text, Dates, Booleans and CAST
Next: String Techniques in SQL: Splitting, Aggregating and Extracting Text

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.