CodeBlanks Logo Icon CodeBlanks

SUBSTRING

Slice a part of a string.

SUBSTRING

With SUBSTRING you take a part of a text. You specify the start and length to pick the slice you want.

SELECT SUBSTRING(name, 1, 3) AS ilk_uc FROM customers;

This query returns the first 3 characters of each name.

SUBSTRING(name, 1, 3) AS ilk_uc is selected from customers.

SUBSTRING — details

Some databases use SUBSTR or LEFT. The start index is 1-based, not 0. Without length it goes to the end.

Practice SUBSTRING

Select the first 2 characters of name aliased as first from customers.

Starter code

query.sql
-- first two letters
SELECT
FROM customers

Sample solution

query.sql
SELECT SUBSTRING(name, 1, 2) AS ilk
FROM customers

Expected output

ilk
Ay
Al

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 SUBSTRING: match the terms

Term Meaning
SUBSTRING substring
UPPER uppercase
LENGTH length
TRIM trim

2 Take substring

Question
SELECT ____(name, 1, 3) FROM customers;
Answer
SELECT SUBSTRING(name, 1, 3) FROM customers;

Explanation: SUBSTRING is the right answer.

3 What is the SUBSTRING start index?

  • 1 Correct answer
  • 0
  • -1
  • 2

Explanation: In SQL the start is 1-based.

All lessons in Beginner