Hook: Interviewers love CAST because it reveals whether you can turn messy data into the right type without breaking filters or slowing a query.
Question: What does CAST do in SQL?
Answer: CAST explicitly converts a value from one data type to another, like text to number, text to date, or number to text. You use it when SQL needs the value in a different shape for math, comparison, sorting, or display. If the value cannot be converted, most databases raise an error unless you use a safer alternative such as TRY_CAST or SAFE_CAST.
Interview-Ready Answer: I use CAST when I want to explicitly convert a value to another SQL type, for example turning a string into an integer for filtering or a number into text for output. I prefer it over implicit conversion because I control the target type and avoid surprises. One thing I watch for is invalid data: CAST('abc' AS INTEGER) fails in most databases, so for dirty input I clean first or use a safe cast variant where the database supports it.
CAST really isDetailed Explanation: CAST tells the database to turn one value into another type on purpose. It is the explicit version of conversion: you are saying, 'treat this as an integer, date, decimal, or text'. That matters in SELECT, WHERE, JOIN, ORDER BY, and HAVING because type mismatches can change results or break a query.
INTEGER, DATE, or VARCHAR(20).NULL stays NULL.'1001' into 1001.| Method | Bad input | Best use |
|---|---|---|
| CAST | Errors | Clear, portable conversion |
| Implicit conversion | Engine decides | Convenient, but risky |
| TRY_CAST / SAFE_CAST | Returns NULL | Dirty data |
Some dialects also support CONVERT, but CAST is the standard, portable form. The big idea is simple: CAST makes the type change visible instead of leaving it to the database to guess.
One cast is O(1) for a single value. On a query touching n rows, the cost is usually O(n) because the conversion happens per row. That cost is often small, but a cast in a WHERE clause can block index use when the column itself is wrapped in the function, turning a fast seek into a full scan. A common fix is to cast the literal or parameter to the column's type, not the other way around.
Memory use is usually O(1) extra for the cast itself, but a later sort or hash join may still spill if the query becomes large. Also, do not rely on default lengths or precision: always specify what you mean, like VARCHAR(20) or DECIMAL(10,2), because engines differ in how they handle omitted details.
Memory hook for the whole topic: the value is the same box, but CAST changes the label on the box so the database knows how to use it.
Real-World Example: Imagine a checkout service that imports daily orders from a legacy partner file. Their order_id arrives as text, but the warehouse expects integers and the revenue report expects decimals. The ETL job uses CAST to normalize '1001' into 1001 and '19.95' into a numeric amount before loading the table.
What goes wrong when people misunderstand CAST? A partner sends 'N/A' in a numeric column, the query tries to convert it, and the nightly reconciliation job fails halfway through. The symptom is a failed batch, retry loops in the scheduler, and dashboards showing missing totals or stale numbers. In the logs you usually see a conversion error from the database engine, and customer support notices that orders from the last import never appeared in finance reports.
The practical lesson is: if input can be dirty, guard the cast or use a safe cast form. If you already know the data is clean, CAST is the most direct and readable choice.
-- Demonstrates explicit conversion with CAST.
-- The guarded CASE keeps bad input from crashing the whole query.
WITH sample(value_text, amount_text, date_text) AS (
VALUES
('42', '19.95', '2026-07-11'),
('007', '3.50', '2026-01-02'),
('abc', '5.00', 'not-a-date'),
(NULL, NULL, NULL)
)
SELECT
value_text,
-- Only cast the rows we know are numeric; one bad string can fail the whole query.
CASE
WHEN value_text IN ('42', '007') THEN CAST(value_text AS INTEGER)
ELSE NULL
END AS safe_integer,
-- Text can become a fixed-point number for money-like values.
CAST(amount_text AS DECIMAL(10,2)) AS amount_decimal,
-- CAST(NULL ...) stays NULL, which is useful when a value is genuinely missing.
CAST(NULL AS INTEGER) AS null_is_still_null,
-- Date conversion works when the text is in a valid date format.
CASE
WHEN date_text IN ('2026-07-11', '2026-01-02') THEN CAST(date_text AS DATE)
ELSE NULL
END AS safe_date,
-- Casting a number to text is common for display or concatenation.
CAST(123 AS VARCHAR(10)) AS number_as_text
FROM sample
WHERE
-- Filtering on a casted value is okay if the CAST branch is guarded.
CASE
WHEN value_text IN ('42', '007') THEN CAST(value_text AS INTEGER)
ELSE NULL
END = 42
OR value_text IS NULL;
-- Bad input example:
-- SELECT CAST('abc' AS INTEGER);
-- Most databases will reject this because 'abc' cannot be converted to a number.Follow-up & Tricky Questions:
CAST raises an error and the query fails. If you need to survive dirty input, use TRY_CAST or SAFE_CAST where available.CAST in a join? Yes, but be careful: casting join keys can make the join slower and can hide data-quality problems. It is usually better to store both columns in the same type.WHERE sometimes make the query slow? Because the engine may need to convert every row before filtering, which can prevent an index seek. That turns a selective lookup into a scan.CAST different from CONVERT? CAST is the standard SQL form. CONVERT is vendor-specific in many systems and sometimes adds style or format options.CAST on NULL fail? No, CAST(NULL AS INTEGER) still returns NULL. Missing data stays missing; only bad non-null data causes the conversion error.CAST always round numbers? Do not assume that. Conversion rules depend on the target type and the database, so for interviews say that exact numeric behavior varies and should be checked in the engine you use.Common Mistakes:
WHERE. Correction: cast the literal or parameter instead, so the database can still use the index.VARCHAR(20) or DECIMAL(10,2), instead of relying on defaults.NULL. Correction: plain CAST usually errors; only safe variants return NULL on failure.CAST as a data-cleaning shortcut. Correction: it converts valid data, but it does not fix invalid values; clean or validate first.Memory Hook: CAST is like putting the same object into a different labeled box: the thing is unchanged, but the database now knows how to treat it.
Cheat Sheet:
CAST = explicit type conversion.NULL stays NULL.WHERE and JOIN clauses because casts can hurt index use.TRY_CAST or SAFE_CAST if your database supports them.Practice Tasks:
'12.50' into DECIMAL(10,2) and sort by the numeric value.1001 without casting the indexed column.NULL.