Skip to content
SQLSimplified
string

SUBSTRING()

Extracts a portion of a string, starting at a given position and running for a given length.

Description

SUBSTRING pulls out a piece of a string, starting at a specified position and continuing for a specified number of characters. It's useful for tasks like grabbing a prefix, extracting a code embedded in a longer string, or truncating text to a preview length.

Syntax

SUBSTRING(string, start, length)

Parameters

NameDescriptionOptional
stringThe text value or column to extract from.No
startThe position of the first character to extract. Positions start at 1, not 0.No
lengthThe number of characters to extract from the start position. If omitted, everything to the end of the string is returned.Yes

Return Type

SUBSTRING returns a VARCHAR (text) value.

Examples

Library (Books/Authors/Publishers)

Loading database engine...

Library (Books/Authors/Publishers)

Loading database engine...

SQL positions start at 1, not 0

Unlike many programming languages where string indexing starts at 0, SQL's SUBSTRING treats the first character as position 1. SUBSTRING(title, 0, 3) is likely a mistake, not the same as starting at the beginning.

Common Mistakes

  • Using 0-indexed thinking. Coming from languages like Python or JavaScript, it's easy to assume position 0 is the first character, but in SQL the first character is at position 1.
  • Omitting the length when you meant to limit it. SUBSTRING(title, 1) (no length) returns the entire rest of the string, not just one character.
  • Requesting a length longer than the remaining string. This isn't an error; SUBSTRING just returns as many characters as are available, which can be shorter than the requested length.

See also: LENGTH, CONCAT, UPPER.

Search

Search lessons, functions, examples, and practice problems