# substr() in SQL (PostgreSQL and SQLite): cut part of a string

Source: https://sqlstreak.com/sql/functions/substr · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** `substr(text, start, length)` returns part of a string, counting from 1: `substr('Biscuit', 1, 3)` is `'Bis'`. Leave out the length to take everything from `start` to the end. The name is the same in PostgreSQL and SQLite; PostgreSQL also accepts `SUBSTRING(text FROM start FOR length)`.

## Syntax

- PostgreSQL: `substr(text, start [, length])  /  SUBSTRING(text FROM start FOR length)` (Yes)
- SQLite: `substr(text, start [, length])  /  substring(text, start [, length])` (Yes)

## Examples

### The first letter of each name

```sql
SELECT name, substr(name, 1, 1) AS initial
FROM pets
ORDER BY name
LIMIT 6;
```

Result (both engines):

| name | initial |
| --- | --- |
| Bean | B |
| Biscuit | B |
| Bruno | B |
| Clover | C |
| Gizmo | G |
| Juniper | J |

### Everything after the first three letters

```sql
SELECT name, substr(name, 4) AS rest
FROM menu_items
ORDER BY id
LIMIT 5;
```

Result (both engines):

| name | rest |
| --- | --- |
| Margherita | gherita |
| Pepperoni Rocket | peroni Rocket |
| Four Cheese Orbit | r Cheese Orbit |
| BBQ Meteor |  Meteor |
| Veggie Nebula | gie Nebula |

### The year from a date, as text

Cast the date to ISO text first; then the year is the first four characters in both databases.

```sql
SELECT substr(CAST(signed_up_on AS TEXT), 1, 4) AS year, COUNT(*) AS users
FROM users
GROUP BY 1;
```

Result (both engines):

| year | users |
| --- | --- |
| 2026 | 300 |

## Edge cases, measured on both engines

| Case | PostgreSQL | SQLite |
| --- | --- | --- |
| From 1, three characters | 'Bis' | 'Bis' |
| From 4 to the end | 'cuit' | 'cuit' |
| Start at 0 | 'Bi' | 'Bi' |
| Negative start | 'Biscuit' | 'uit' |
| Negative length | error: negative substring length not allowed | 'i' |
| Past the end | '' | '' |
| Accented letters count as one | 'ás' | 'ás' |
| NULL | NULL | NULL |

## Common mistakes

- Counting from 0: SQL strings start at position 1.
- Relying on a negative start: SQLite counts it from the end, PostgreSQL doesn't (see the matrix).
- Using substr on a date column in PostgreSQL: it wants text, so CAST the date first.
