SUBSTRING example
We want to show the first five characters of each product name:
SELECT name,
SUBSTR(name, 1, 5) AS start
FROM products
ORDER BY id
LIMIT 6;Check the result with small data
Every code starts with a two-letter country code.
WITH codes(code) AS (
VALUES ('GB-1024'), ('IE-0099')
)
SELECT code, SUBSTR(code,1,2) AS country
FROM codes ORDER BY code;| code | country |
|---|---|
| GB-1024 | GB |
| IE-0099 | IE |
In SQLite, SUBSTR(text, 1, 2) starts at the first character and takes two. Other engines use the name SUBSTRING.
Check your understanding: What would SUBSTR(code, 4, 4) return?
Show answer
'1024' for GB-1024 and '0099' for IE-0099: SUBSTR starts at the fourth character, right after the hyphen, and takes four.
How SUBSTRING is used
SQLite supports substr and also accepts substring as an alias in recent versions. PostgreSQL has several forms of substring. MySQL offers SUBSTRING and SUBSTR.
Common mix-ups with SUBSTRING
Starting at zero
SELECT SUBSTR(name, 0, 5) FROM products;These SQL functions count positions from one. Use 1 to start at the first character. Some engines allow negative positions with their own rules, but do not assume that variant is portable.
Key differences between engines
The name, the argument style and the regular-expression variants differ. For a first lesson, use the position-and-length form your engine supports. Do not copy an advanced PostgreSQL form into MySQL or SQLite without checking it.
Extracting by position means knowing the format
Positional extraction suits data with a fixed structure, such as the year in a code that always starts with four digits. If the prefix changes length or an optional separator appears, the same position cuts out a different part. Before using it to import data, check that the format really guarantees those positions, and decide what to do with shorter values.
The positive start position in the example counts from one. Zero or negative positions and negative lengths do not behave the same everywhere, so do not copy a technique from one engine to another without checking it. A null string does not turn into an empty fragment either. Keep the original next to the fragment while you are diagnosing.
What counts as a character may not be what a person sees as one. A combining accent or an emoji made up of several units may need Unicode rules beyond a simple extraction. For fixed-format ASCII codes that complexity rarely matters, but for names and free text, cutting by length can split a visible character. Test with data representative of your domain rather than generalising from a plain English string.
Technical questions: SQLite: scalar functions (opens in a new tab).