# REPLACE() in SQL: swap text inside a string

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


**Short answer:** `REPLACE(text, from, to)` returns the text with every occurrence of `from` swapped for `to`: `REPLACE('555-0101', '-', '')` is `'5550101'`. It's case-sensitive and the same in PostgreSQL and SQLite.

## Syntax

- PostgreSQL: `REPLACE(text, from_text, to_text)` (Yes)
- SQLite: `REPLACE(text, from_text, to_text)` (Yes)

## Examples

### Phone numbers without the dash

```sql
SELECT id, phone, REPLACE(phone, '-', '') AS digits
FROM adoption_requests
WHERE NULLIF(TRIM(phone), '') IS NOT NULL
ORDER BY id
LIMIT 5;
```

Result (both engines):

| id | phone | digits |
| --- | --- | --- |
| 1 | 555-0101 | 5550101 |
| 4 | 555-0104 | 5550104 |
| 5 | 555-0105 | 5550105 |
| 7 | 555-0107 | 5550107 |
| 9 | 555-0109 | 5550109 |

### URL slugs from names

```sql
SELECT name, LOWER(REPLACE(name, ' ', '-')) AS slug
FROM menu_items
ORDER BY id
LIMIT 5;
```

Result (both engines):

| name | slug |
| --- | --- |
| Margherita | margherita |
| Pepperoni Rocket | pepperoni-rocket |
| Four Cheese Orbit | four-cheese-orbit |
| BBQ Meteor | bbq-meteor |
| Veggie Nebula | veggie-nebula |

### Several replacements: nest them

```sql
SELECT name, REPLACE(REPLACE(LOWER(name), ' ', '_'), '&', 'and') AS key
FROM staff
ORDER BY id
LIMIT 4;
```

Result (both engines):

| name | key |
| --- | --- |
| Rosa Vega | rosa_vega |
| Omar Haddad | omar_haddad |
| Lia Moreau | lia_moreau |
| Ben Carter | ben_carter |

## Edge cases, measured on both engines

| Case | PostgreSQL | SQLite |
| --- | --- | --- |
| Every occurrence | 'abc' | 'abc' |
| Case matters | 'Ab' | 'Ab' |
| Overlapping matches | 'ba' | 'ba' |
| Searching for an empty string | 'abc' | 'abc' |
| Not found | 'abc' | 'abc' |
| NULL replacement | NULL | NULL |
| NULL text | NULL | NULL |

## Common mistakes

- Expecting a case-insensitive replace: `REPLACE(LOWER(x), …)` changes the case of everything; PostgreSQL's `regexp_replace(x, 'a', 'b', 'gi')` keeps it.
- A NULL replacement: the whole result becomes NULL, not just the match.
- Confusing it with SQLite's `REPLACE INTO …` statement, which is an upsert, not a text function.
