Menu
Coddy logo textTech

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.

  • start is 1-indexed: the first character is position 1, not 0.
  • length is optional. Leave it off to get everything from start to the end.
  • A negative start counts 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 icon

Challenge

Easy

Available 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:

  • start is 1-indexed (first character = position 1)
  • length is optional — omit to get everything from start to the end
  • Negative start counts 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Beyond the Basics