SUBSTR
Part of the Beyond the Basics section of Coddy's SQL journey — lesson 7 of 27.
SUBSTR(s, start, length) extracts a piece of a string.
startis 1-indexed: the first character is position1, not0.lengthis optional. Leave it off to get everything fromstartto the end.- A negative
startcounts from the end of the string.
SUBSTR('hello world', 1, 5) -- 'hello'
SUBSTR('hello world', 7) -- 'world'
SUBSTR('hello world', -5) -- 'world'Useful for pulling a year out of '2026-04-15', an area code out of a phone number, or the file extension off a path.
Challenge
EasyAvailable tables and columns:
<strong>files</strong>:<strong>id</strong>,<strong>filename</strong>
Each filename is exactly four characters followed by a three-character extension (e.g. 'note.txt'). Return id, the four-character base as base, and the three-character extension as ext. Order by id.
Cheat sheet
SUBSTR(s, start, length) extracts a substring:
startis 1-indexed (first character = position1)lengthis optional — omit to get everything fromstartto the end- Negative
startcounts from the end of the string
SUBSTR('hello world', 1, 5) -- 'hello'
SUBSTR('hello world', 7) -- 'world'
SUBSTR('hello world', -5) -- 'world'Try it yourself
SELECT id,
-- base = first 4 chars, ext = last 3 chars
FROM files
ORDER BY id
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Beyond the Basics
2String Functions
LENGTH, UPPER, LOWERSUBSTRINSTRREPLACE and TRIMConcatenating with ||Recap - Invoices