Type Casting & Conversion (CAST, ::, TRY_CAST)
Convert types safely with CAST/:: and tolerate dirty data with TRY_CAST patterns.
In plain words
Casting changes a value from one type to another, like the text '42' to the number 42. If it can't be converted, you get an error, or NULL with TRY_CAST.
Think of it like…
Converting currencies at a bank counter: a valid note converts cleanly (CAST), a torn or fake note gets refused and holds up the queue (error), and a lenient counter just hands it back and moves on (TRY_CAST returning NULL).
Where you’ve seen it
A CSV import put quantities in a text column: SELECT SUM(CAST(qty AS integer)) FROM staging_orders fails on the first row containing 'N/A'. In Snowflake, SUM(TRY_CAST(qty AS INTEGER)) skips it; in PostgreSQL, you filter with a regular expression first: WHERE qty ~ '^[0-9]+$'.
Words you’ll hear
- CAST / ::
- Explicit conversion; standard CAST works everywhere, :: only in PostgreSQL.
- TRY_CAST / SAFE_CAST
- Convert, or return NULL instead of failing.
- Implicit cast
- A conversion the database does automatically when types differ.
- Integer division
- Dividing two integers drops the fraction: 7 / 2 = 3.
Visual diagram
Theory & example queries
Explicit casts and their surprises
CAST(x AS numeric) is standard SQL; in PostgreSQL x::numeric is equivalent and common. Casting text to a number or date requires the text to be valid; otherwise the whole query fails. Casting to a narrower type can also fail (a number too large for integer) or change values: casting 2.7 to integer gives 3 in PostgreSQL (it rounds) but 2 in SQL Server (it truncates).
Integer arithmetic stays integer: 7 / 2 is 3 and 1 / 3 is 0. For ratios and percentages, cast at least one side first: clicks::numeric / impressions, or multiply by 100.0. Date strings convert reliably only in ISO format ('2026-11-19'); for other formats, use TO_DATE with an explicit pattern.
SELECT 7 / 2 AS int_div, 7::numeric / 2 AS exact, ROUND(100.0 * 3 / 7, 1) AS pct;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Division and percentage results1 sample row
| int_div | exact | pct |
|---|---|---|
| 3 | 3.5 | 42.9 |
Note: PostgreSQL semantics: integer division returns 3, numeric division returns 3.5, and ROUND produces one decimal place.
returns 3, 3.5 and 42.9.
Key takeaway: Watch for integer division and database-specific rounding.
Dirty data and implicit casts
TRY_CAST and SAFE_CAST return NULL for values that don't convert, so you can clean data in one pass and count the failures with COUNT(*) FILTER (WHERE TRY_CAST(x AS int) IS NULL AND x IS NOT NULL). PostgreSQL has no TRY_CAST: filter with a regular expression first, or write a small function that catches the conversion error.
Implicit conversion happens when you compare different types. In MySQL, comparing a VARCHAR phone column to a number (WHERE phone = 9876543210) converts every row's value, so the index can't be used and odd matches can happen. Compare like with like, and when a cast is needed in WHERE, cast the constant (WHERE created_at >= '2026-11-01'::timestamptz) rather than the column.
SELECT SUM(qty::int)FROM ( SELECT TRIM(qty) AS qty FROM staging_orders ) sWHERE qty ~ '^[0-9]+$';PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Sum of safe integer quantities1 sample row
| sum |
|---|
| 42 |
Note: Assumes the staging rows that pass the digits-only filter sum to 42; invalid or blank quantities are excluded.
Key takeaway: Use safe casts or pre-filters for dirty data; avoid implicit casts on indexed columns.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Profile the values
Look for values that won't convert: blanks, words like 'N/A', thousands separators, extra spaces.
SELECT qtyFROM stagingWHERE qty !~ '^[0-9]+$'When to use it & trade-offs
What it is
CAST(value AS type) converts a value to another type; PostgreSQL also has the shorthand value::type. A cast that can't work, like 'abc'::int, raises an error. TRY_CAST (SQL Server, Snowflake, DuckDB) and SAFE_CAST (BigQuery) return NULL instead. Databases also convert some types automatically (implicit casts), which is convenient but can hide bugs and slow queries.
Why it matters: Imported data is full of numbers stored as text, dates in odd formats and values that won't convert, and one bad row can make a whole query fail. Integer division (7 / 2 = 3) and implicit conversions that disable indexes are classic bugs that interviewers like to probe.
When to reach for it
- Importing CSV and spreadsheet data
- Computing ratios and percentages
- Converting date strings to dates
When to avoid or be careful
- Dividing integers when you need decimals
- Comparing text columns to numbers
- Casting the column instead of the constant in WHERE
CAST vs TRY_CAST vs storing the right type
Strengths: Standard and strict: bad data fails loudly.
Watch out: One bad row stops the whole query.
Strengths: Bad values become NULL; the query completes.
Watch out: Not in PostgreSQL or MySQL; silent NULLs need counting.
Strengths: No casts needed; validation happens on write.
Watch out: Requires a migration and cleaning existing data.
Interview signals & numbers to know
When this topic comes up
- “invalid input syntax for type integer”
- “My percentage always shows 0”
- Numbers stored as text
- TRY_CAST vs CAST
- Data cleaning
Benchmarks & rules of thumb
- 7 / 2
- = 3 with integers
- 2.7 → int
- 3 in PostgreSQL, 2 in SQL Server
- 0
- TRY_CAST functions built into PostgreSQL
Common mistakes & follow-ups
Common interview mistakes
- Calculating a conversion rate with integers and getting 0 for every row.
- Casting a whole text column to int in one query and failing on a single 'N/A'.
- Comparing a VARCHAR column to a number in MySQL and losing the index.
Likely interviewer follow-ups
- How would you convert a text column with some invalid values to integers?
- Why does SELECT 1 / 3 return 0?
- What's the difference between CAST and TRY_CAST?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Type Casting & Conversion (CAST, ::, TRY_CAST) with hands-on SQL practice and interview Q&A.