String Techniques in SQL: Splitting, Aggregating and Extracting Text
Practical techniques for text in SQL: splitting strings with SPLIT_PART and string_to_table, turning rows into lists with STRING_AGG, GROUP_CONCAT and LISTAGG, turning lists back into rows, counting occurrences, walking a string character by character, and sorting text that holds numbers.
kvi5hnuCode Sprout team member10 min readOn this page
Article 36 covered the individual string functions. Real problems usually combine them, often with grouping, joins or a generated series: "list each category's products in one cell", "split this comma-separated column into rows", "how many words are in each title?", "sort these IP addresses properly".
This article collects those techniques. Most have a simple PostgreSQL solution and a different one in each other database, so each section ends with the equivalents. The examples use the shop database.
Splitting a string into parts
SPLIT_PART(string, delimiter, n) returns the nth piece of a string split at a delimiter:
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);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- SPLIT_PART(string, delimiter, n): the nth piece
SELECT name,
SPLIT_PART(name, ' ', 1) AS first_name,
SPLIT_PART(name, ' ', 2) AS last_name,
SPLIT_PART(name, ' ', 3) AS third_piece, -- empty, not NULL
SPLIT_PART(name, ' ', -1) AS last_piece -- counted from the end
FROM customers
WHERE customer_id IN (1, 6)
ORDER BY customer_id;
-- The domain of an email address, and how many contacts use each one
SELECT LOWER(SPLIT_PART(email, '@', 2)) AS domain, COUNT(*) AS contacts
FROM (VALUES ('asha@example.com'), ('ben@Mail.test'), ('chen@example.com'), ('dana')) AS t(email)
GROUP BY LOWER(SPLIT_PART(email, '@', 2))
ORDER BY contacts DESC, domain;
name | first_name | last_name | third_piece | last_piece
--------------+------------+-----------+-------------+------------
Asha Rao | Asha | Rao | | Rao
Farah Haddad | Farah | Haddad | | Haddad
(2 rows)
domain | contacts
-------------+----------
example.com | 2
| 1
mail.test | 1
(3 rows)
SPLIT_PART(name, ' ', 1)andSPLIT_PART(name, ' ', 2)give the first and second words.- Asking for a piece that doesn't exist returns an empty string, not NULL, as the
third_piececolumn shows. The email'dana'has no@, so its domain is empty too, and it forms its own group in the second query. UseNULLIF(SPLIT_PART(...), '')if you want NULL. - A negative position counts from the end (PostgreSQL 14+):
SPLIT_PART(name, ' ', -1)is the last word, whatever the number of words. LOWERnormalises the domains before grouping, soMail.testandmail.testwould count together.
Splitting names into "first" and "last" is fine for display, but real names don't follow one pattern: many people have several given names, family names with spaces, or a single name. If you need name parts, store them separately.
Equivalents:
| Database | Nth piece | Last piece |
|---|---|---|
| PostgreSQL | SPLIT_PART(s, d, n) | SPLIT_PART(s, d, -1) |
| MySQL | SUBSTRING_INDEX(SUBSTRING_INDEX(s, d, n), d, -1) | SUBSTRING_INDEX(s, d, -1) |
| SQL Server | STRING_SPLIT(s, d, 1) with WHERE ordinal = n (2022+) | the same, with the highest ordinal |
| Oracle | REGEXP_SUBSTR(s, '[^,]+', 1, n) | REGEXP_SUBSTR(s, '[^,]+$') |
| SQLite | SUBSTR and INSTR, or a recursive CTE |
Oracle's '[^,]+' pattern skips empty items: for 'a,,c', piece 2 is 'c'. Use REGEXP_SUBSTR(s, '([^,]*)(,|$)', 1, n, NULL, 1) if empty pieces must count.
MySQL's SUBSTRING_INDEX(s, d, n) returns everything before the nth delimiter (or after it, counting from the end, when n is negative), so the nested form keeps the last piece of the first n.
Rows to a list: STRING_AGG
The reverse problem, combining values from many rows into one string, is an aggregate. In PostgreSQL and SQL Server it's STRING_AGG(value, separator):
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);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Rows to a list: STRING_AGG with its own ORDER BY
SELECT category,
STRING_AGG(name, ', ' ORDER BY price) AS products_by_price,
COUNT(*) AS n
FROM products
GROUP BY category
ORDER BY category;
-- DISTINCT inside STRING_AGG, and a list per customer
SELECT c.name,
STRING_AGG(DISTINCT p.category, ' + ' ORDER BY p.category) AS categories_bought,
STRING_AGG(DISTINCT CAST(o.order_id AS text), ',' ORDER BY CAST(o.order_id AS text)) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;
category | products_by_price | n
----------+------------------------------------+---
clothing | Merino socks | 1
lighting | Basecamp lantern, Glow head torch | 2
packs | Day 18 backpack, Trail 30 backpack | 2
tents | Ridge 2 tent, Summit 4 tent | 2
(4 rows)
name | categories_bought | orders
------------+-------------------------------------+---------
Asha Rao | clothing + lighting + packs + tents | 101,103
Ben Okafor | lighting | 102
Chen Wei | tents | 104
Dana Cruz | packs | 105
(4 rows)
STRING_AGG(name, ', ' ORDER BY price)lists each category's products, cheapest first. Without theORDER BYinside the call, the order of items in the list is arbitrary. ThisORDER BYorders the items within each list, while the query's ownORDER BYorders the rows.DISTINCTremoves repeated values. Asha's orders contain products from four categories, some more than once, and each category appears once.- The second query joins four tables, so each order appears once per order line.
DISTINCTon the order IDs collapses those repeats, which shows the join fan-out problem from article 17 appearing inside a list. WithDISTINCT, PostgreSQL requires theORDER BYexpression to match the aggregated value, which is why it orders by the cast text. - Numbers must be converted to text first, or PostgreSQL reports that
STRING_AGGdoesn't accept integers. STRING_AGGskips NULL values, and returns NULL, not an empty string, when the group has no non-NULL values. Wrap it inCOALESCE(..., '')if needed.
Equivalents:
| Database | Syntax |
|---|---|
| PostgreSQL | STRING_AGG(x, ', ' ORDER BY y) |
| SQL Server 2017+ | STRING_AGG(x, ', ') WITHIN GROUP (ORDER BY y) |
| MySQL, MariaDB | GROUP_CONCAT(x ORDER BY y SEPARATOR ', ') |
| Oracle | LISTAGG(x, ', ') WITHIN GROUP (ORDER BY y) |
| SQLite | GROUP_CONCAT(x, ', '), or STRING_AGG(x, ', ' ORDER BY y) since 3.44 |
Length limits cause silent bugs. MySQL's GROUP_CONCAT truncates its result at group_concat_max_len bytes, which defaults to 1,024, with only a warning. Raise it with SET SESSION group_concat_max_len = 1000000 before long lists. Oracle's LISTAGG raises an error when the result exceeds the VARCHAR2 limit, unless you add ON OVERFLOW TRUNCATE (Oracle 12.2+). SQL Server's STRING_AGG fails beyond 8,000 bytes unless the input is cast to NVARCHAR(MAX) or VARCHAR(MAX).
A list to rows
Data sometimes arrives with several values packed into one column, such as tags typed as 'camping, 2-person,lightweight'. To count, filter or join them, they must first become rows:
-- Tags typed into one text column, separated by commas
CREATE TABLE product_tags (
product_id INTEGER PRIMARY KEY,
tags TEXT
);
INSERT INTO product_tags VALUES
(1, 'camping, 2-person,lightweight'),
(2, 'camping,family , 4-person'),
(3, 'lighting, campfire-safe'),
(7, 'wool');
-- A list to rows: one row per tag, trimmed
SELECT pt.product_id, TRIM(tag) AS tag
FROM product_tags pt
CROSS JOIN LATERAL string_to_table(pt.tags, ',') AS tag
ORDER BY pt.product_id, tag;
-- Once the tags are rows, ordinary SQL works on them
SELECT TRIM(tag) AS tag, COUNT(*) AS products
FROM product_tags pt
CROSS JOIN LATERAL string_to_table(pt.tags, ',') AS tag
GROUP BY TRIM(tag)
ORDER BY products DESC, tag
FETCH FIRST 3 ROWS ONLY;
-- Is 'camping' in the list? Split and compare; LIKE gives false matches
SELECT product_id,
'camping' = ANY (SELECT TRIM(t) FROM string_to_table(tags, ',') AS t) AS has_tag,
tags LIKE '%camp%' AS like_camp
FROM product_tags
ORDER BY product_id;
product_id | tag
------------+---------------
1 | 2-person
1 | camping
1 | lightweight
2 | 4-person
2 | camping
2 | family
3 | campfire-safe
3 | lighting
7 | wool
(9 rows)
tag | products
----------+----------
camping | 2
2-person | 1
4-person | 1
(3 rows)
product_id | has_tag | like_camp
------------+---------+-----------
1 | t | t
2 | t | t
3 | f | t
7 | f | f
(4 rows)

string_to_table(text, delimiter)(PostgreSQL 14+) returns one row per piece. Used withCROSS JOIN LATERAL(article 23), it splits each product's tags into rows next to the product's ID. Before PostgreSQL 14, useunnest(string_to_array(text, delimiter)).TRIMremoves the spaces that people typed after some commas. Without it,'camping'and' camping'would count as different tags.- Once the tags are rows, the second query counts them with an ordinary
GROUP BY. - The third query shows why splitting matters for searching.
tags LIKE '%camp%'also matchescampfire-safe, a false positive. Comparing whole tags after splitting, with= ANY (...), gives the right answer.LIKE '%,camping,%'tricks break on spaces and on the first and last items.
Equivalents: SQL Server has STRING_SPLIT(s, ',') (2016+), which returns a table with a value column, used with CROSS APPLY. MySQL has no split function: a common workaround converts the list to a JSON array and uses JSON_TABLE (article 43), or joins to a table of numbers and uses SUBSTRING_INDEX. Oracle uses REGEXP_SUBSTR with CONNECT BY LEVEL, or JSON_TABLE. SQLite needs a recursive CTE (article 25) or the json_each trick.
Don't store lists in columns. A comma-separated column can't have a foreign key to a tags table, can't be indexed per value, can't stop duplicates or misspellings, and needs splitting in every query. The right design is a separate table with one row per product and tag (article 51 explains why). Use the splitting techniques to clean up such data, or to read it from files and other systems.
Counting and walking characters
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);
-- Counting occurrences: compare lengths before and after removing the substring
SELECT name,
LENGTH(name) - LENGTH(REPLACE(name, ' ', '')) AS spaces,
LENGTH(name) - LENGTH(REPLACE(name, ' ', '')) + 1 AS words,
(LENGTH(name) - LENGTH(REPLACE(LOWER(name), 'a', ''))) AS letter_a
FROM products
WHERE product_id IN (1, 4, 5)
ORDER BY product_id;
-- Walking a string one character at a time with generate_series
SELECT pos, SUBSTRING('Ridge' FROM pos FOR 1) AS ch
FROM generate_series(1, LENGTH('Ridge')) AS pos;
-- ...which lets you rebuild it in another order: the letters sorted
SELECT STRING_AGG(SUBSTRING('Ridge' FROM pos FOR 1), '' ORDER BY LOWER(SUBSTRING('Ridge' FROM pos FOR 1))) AS sorted
FROM generate_series(1, LENGTH('Ridge')) AS pos;
name | spaces | words | letter_a
-------------------+--------+-------+----------
Ridge 2 tent | 2 | 3 | 0
Basecamp lantern | 1 | 2 | 3
Trail 30 backpack | 2 | 3 | 3
(3 rows)
pos | ch
-----+----
1 | R
2 | i
3 | d
4 | g
5 | e
(5 rows)
sorted
--------
degiR
(1 row)
Counting occurrences. There's no portable "count this substring" function, but a length trick works in every database: remove every occurrence with REPLACE, and the length difference tells how many characters were removed. Divide by the substring's length when it's longer than one character: (LENGTH(s) - LENGTH(REPLACE(s, 'ab', ''))) / 2. Counting spaces and adding 1 gives the number of words, assuming single spaces between words. Apply LOWER first to count letters regardless of case: the letter_a column finds three a's in Basecamp lantern, and none in Ridge 2 tent.
Walking a string. Joining a string to generate_series(1, LENGTH(s)) gives one row per position, and SUBSTRING(s FROM pos FOR 1) picks out each character. Then any SQL applies: you can filter characters, count them by type, or reassemble them in a different order with STRING_AGG. Sorting the letters of 'Ridge' case-insensitively gives degiR. Sorted letters are a common way to test whether two words are anagrams.
For most character-level tasks, regular expressions (article 42) are shorter: REGEXP_COUNT(s, 'a', 1, 'i') counts a's in PostgreSQL 15+ and Oracle (MySQL has no REGEXP_COUNT), and REGEXP_REPLACE(s, '[^0-9]', '', 'g') keeps only digits.
Sorting text that holds numbers
Text sorts character by character, so numbers inside text sort wrongly: '10.0.0.12' comes before '10.0.0.9', because '1' sorts before '9'. Splitting the text and sorting by the numeric parts fixes it:
-- Text that holds numbers sorts as text; split it and sort by the numbers
CREATE TABLE servers (host TEXT, ip TEXT);
INSERT INTO servers VALUES
('web-1', '10.0.0.12'), ('web-2', '10.0.0.9'),
('db-1', '10.0.1.2'), ('cache', '9.255.0.1');
SELECT host, ip
FROM servers
ORDER BY ip; -- text order
SELECT host, ip
FROM servers
ORDER BY CAST(SPLIT_PART(ip, '.', 1) AS integer),
CAST(SPLIT_PART(ip, '.', 2) AS integer),
CAST(SPLIT_PART(ip, '.', 3) AS integer),
CAST(SPLIT_PART(ip, '.', 4) AS integer);
host | ip
-------+-----------
web-1 | 10.0.0.12
web-2 | 10.0.0.9
db-1 | 10.0.1.2
cache | 9.255.0.1
(4 rows)
host | ip
-------+-----------
cache | 9.255.0.1
web-2 | 10.0.0.9
web-1 | 10.0.0.12
db-1 | 10.0.1.2
(4 rows)
The first query sorts the addresses as text, which puts 9.255.0.1 last and 10.0.0.12 before 10.0.0.9. The second casts each of the four parts to an integer and sorts by them in turn, which gives the numeric order.
The same idea fixes product codes like 'item-9' and 'item-10': sort by CAST(SPLIT_PART(code, '-', 2) AS integer). Better still, store the parts in typed columns, or use a proper type: PostgreSQL's inet type stores IP addresses and sorts them correctly. Some databases offer natural sort collations that compare digit runs as numbers. In PostgreSQL, an ICU collation with kn ("numeric ordering"), such as CREATE COLLATION natural_sort (provider = icu, locale = 'und-u-kn'), makes 'item-9' sort before 'item-10'.
What's current
- PostgreSQL 14 added
string_to_tableand negative positions inSPLIT_PART. - PostgreSQL 15 added
REGEXP_COUNT,REGEXP_INSTR,REGEXP_LIKEandREGEXP_SUBSTR, matching Oracle's function names. - SQL Server 2022 added the
ordinalargument toSTRING_SPLIT, so you can keep each piece's position. - SQLite 3.44 added
STRING_AGGandORDER BYinside aggregates.
Common questions
How do I get the part after the last delimiter?
SPLIT_PART(s, d, -1) in PostgreSQL 14+, SUBSTRING_INDEX(s, d, -1) in MySQL, REGEXP_SUBSTR in Oracle.
Why are the items in my STRING_AGG list in a random order?
Without an ORDER BY inside the aggregate, the order is whatever the database happens to process. Add ORDER BY inside the call, or WITHIN GROUP (ORDER BY ...) in SQL Server and Oracle.
Why is my GROUP_CONCAT result cut off?
MySQL limits it to group_concat_max_len, 1,024 bytes by default. Increase the setting.
How do I split a comma-separated column into rows?
string_to_table with CROSS JOIN LATERAL in PostgreSQL, STRING_SPLIT with CROSS APPLY in SQL Server, JSON_TABLE in MySQL. Then fix the design so the values are stored as rows.
How do I count how many times a word appears in a string?
(LENGTH(s) - LENGTH(REPLACE(s, word, ''))) / LENGTH(word), or REGEXP_COUNT where available.
Is it OK to store comma-separated values in a column? Only for data you never search, join or validate. Otherwise use a separate table with one row per value.
Summary
SPLIT_PARTtakes the nth piece of a string. Missing pieces are empty strings. Other databases useSUBSTRING_INDEX,STRING_SPLITorREGEXP_SUBSTR.STRING_AGG(PostgreSQL, SQL Server),GROUP_CONCAT(MySQL, SQLite) andLISTAGG(Oracle) combine rows into a list. Order the items inside the call, and watch the length limits.string_to_tableorSTRING_SPLITturn a list back into rows. Trim the pieces, and compare whole values rather than usingLIKE.- Count occurrences by comparing lengths before and after
REPLACE. Walk a string by joining it togenerate_series. - Sort numbers stored in text by their numeric parts, or store them in proper types.
- Store multi-valued data as rows, not as delimited text.
Practice questions
Write a query that returns each city and a comma-separated, alphabetical list of the customers who live there, ignoring customers with no city.
Answer
SELECT city, STRING_AGG(name, ', ' ORDER BY name) AS customers
FROM customers
WHERE city IS NOT NULL
GROUP BY city
ORDER BY city;
Leeds: Ben Okafor, Eli Novak. Pune: Asha Rao, Chen Wei. York: Dana Cruz.
What does SPLIT_PART('a,b,,d', ',', 3) return, and what does SPLIT_PART('a,b,,d', ',', 5) return?
Answer
Both return an empty string. The third piece is the empty text between the two adjacent commas, and there's no fifth piece.
Write an expression that counts the words in 'Trail 30 backpack', assuming words are separated by single spaces.
Answer
LENGTH('Trail 30 backpack') - LENGTH(REPLACE('Trail 30 backpack', ' ', '')) + 1
Two spaces were removed, so there are 3 words. An empty string would wrongly count as 1 word, so handle it separately if it can occur.
A column holds tags like 'red,blue'. Why does WHERE tags LIKE '%red%' give wrong results, and what's a correct test in PostgreSQL?
Answer
It also matches tags that contain red inside a longer word, such as 'tired' or 'redwood'. Split the list and compare whole values: WHERE 'red' = ANY (SELECT TRIM(t) FROM string_to_table(tags, ',') AS t). The real fix is a separate tag table.
A MySQL report uses GROUP_CONCAT to list order IDs per customer, and for the biggest customer the list stops after about 200 IDs. Why?
Answer
GROUP_CONCAT truncates its result at group_concat_max_len, which is 1,024 bytes by default, and only issues a warning. Raise the limit with SET SESSION group_concat_max_len = ... before running the query.
Previous: SQL String Functions: Length, Case, Trim, Substring, Replace and Collations
Next: Numbers in SQL: Rounding, Division, Median, Mode and Percentiles

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.