# CAST in SQL: convert types in PostgreSQL and SQLite

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


**Short answer:** `CAST(value AS type)` converts a value to another type: `CAST('42' AS INTEGER)` is the number 42. PostgreSQL refuses anything it can't convert exactly; SQLite converts as much as it can and keeps going, which matters for messy text and for dates.

## Syntax

- PostgreSQL: `CAST(value AS type)  /  value::type` (Yes, plus the :: shorthand)
- SQLite: `CAST(value AS type)` (Yes (no ::))

## Examples

### Budget text into numbers

Strip the $ and the spaces first; blanks become NULL so the cast doesn't trip on them.

```sql
SELECT id, budget AS raw,
       CAST(NULLIF(REPLACE(TRIM(budget), '$', ''), '') AS INTEGER) AS budget_usd
FROM adoption_requests
ORDER BY id
LIMIT 6;
```

Result (both engines):

| id | raw | budget_usd |
| --- | --- | --- |
| 1 | $120 | 120 |
| 2 | 80 | 80 |
| 3 | $150 | 150 |
| 4 | NULL | NULL |
| 5 | $60 | 60 |
| 6 | $95 | 95 |

### Avoid integer division

```sql
SELECT category, COUNT(*) AS items,
       CAST(COUNT(*) AS REAL) / (SELECT COUNT(*) FROM menu_items) AS share
FROM menu_items
GROUP BY category
ORDER BY items DESC;
```

Result (both engines):

| category | items | share |
| --- | --- | --- |
| pizza | 5 | 0.45454545454545453 |
| side | 3 | 0.2727272727272727 |
| drink | 2 | 0.18181818181818182 |
| dessert | 1 | 0.09090909090909091 |

### Numbers into text

```sql
SELECT name, 'Item #' || CAST(id AS TEXT) AS label
FROM menu_items
ORDER BY id
LIMIT 4;
```

Result (both engines):

| name | label |
| --- | --- |
| Margherita | Item #1 |
| Pepperoni Rocket | Item #2 |
| Four Cheese Orbit | Item #3 |
| BBQ Meteor | Item #4 |

## Edge cases, measured on both engines

| Case | PostgreSQL | SQLite |
| --- | --- | --- |
| Clean number text | 42 | 42 |
| Number followed by junk | error: invalid input syntax for type integer: "42abc" | 42 |
| Decimal text to integer | error: invalid input syntax for type integer: "3.99" | 3 |
| Decimal number to integer | 4 | 3 |
| Date text to DATE | '2026-03-15' | 2026 |
| Text with no number at all | error: invalid input syntax for type real: "abc" | 0 |
| 1 to boolean | true | 1 |
| NULL | NULL | NULL |

## Common mistakes

- `CAST(d AS DATE)` in SQLite: there is no date type, so it converts the text to a number (2026). Keep ISO text and use the date functions.
- Expecting the same rounding: casting 3.99 to INTEGER rounds in PostgreSQL and truncates in SQLite (see the matrix).
- Casting messy text in PostgreSQL without cleaning it: one bad row stops the whole query.
