Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 33/ 160
02. Aggregations, Functions & Data Manipulation

Type Casting & Conversion (CAST, ::, TRY_CAST)

Convert types safely with CAST/:: and tolerate dirty data with TRY_CAST patterns.

BeginnerCAST · :: Operator3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Getting a real ratioQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  7 / 2 AS int_div,3  7::numeric / 2 AS exact,4  ROUND(100.0 * 3 / 7, 1) AS pct;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/4
3OutputInspect the representative rows, affected-row count, plan, or command status.
Division and percentage results1 sample row
Division and percentage results
int_divexactpct
33.542.9

Note: PostgreSQL semantics: integer division returns 3, numeric division returns 3.5, and ROUND produces one decimal place.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Safe conversion in PostgreSQLQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  SUM(qty::int)3FROM4  (5    SELECT6      TRIM(qty) AS qty7    FROM8      staging_orders9  ) s10WHERE11  qty ~ '^[0-9]+$';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Sum of safe integer quantities1 sample row
Sum of safe integer quantities
sum
42

Note: Assumes the staging rows that pass the digits-only filter sum to 42; invalid or blank quantities are excluded.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Use safe casts or pre-filters for dirty data; avoid implicit casts on indexed columns.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Inspection

Profile the values

Look for values that won't convert: blanks, words like 'N/A', thousands separators, extra spaces.

SQL at this step
1SELECT2  qty3FROM4  staging5WHERE6  qty !~ '^[0-9]+$'
What to watch at this step
Find
bad values first
Tip: use ← → to move between steps

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

CAST / ::
Best for: Values you know are valid

Strengths: Standard and strict: bad data fails loudly.

Watch out: One bad row stops the whole query.

TRY_CAST / SAFE_CAST
Best for: Cleaning imported or user-entered data

Strengths: Bad values become NULL; the query completes.

Watch out: Not in PostgreSQL or MySQL; silent NULLs need counting.

Correct column types
Best for: Anything stored long-term

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?
Interview tip: Mention integer division and dirty data whenever casting comes up. Those are the two problems people actually hit.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Date Arithmetic, Intervals & Formatting (AGE, NOW(), CURRENT_DATE, TO_CHAR)
Next topic
Upserts (INSERT ... ON CONFLICT DO UPDATE / DO NOTHING, MERGE)