# Topic 25: Type Conversion
CAST, PostgreSQL :: shorthand, implicit vs explicit coercion, and avoiding type conversion performance traps.
1. Definition
Type conversion translates a value from one data type to another, either explicitly via CAST() or implicitly by the query engine during evaluation.
2. Explain Like I'm 5
Type conversion is an electrical adapter: turning a string of text containing digits "123" into a real number 123 so you can do math with it.
3. Animation & Visual Simulation
Interactive Engine TraceType Conversion Visual Simulator
SELECT id, CAST(total_cents AS NUMERIC) / 100 AS total_usd
FROM orders;Active InputStep 1: Input & Parsing Stage
Initiating Type Conversion
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Parsing JSON string numbers or converting dates to human-readable timestamps.
| Input Text | Target Type | Result |
|---|---|---|
| '2026-01-01' | DATE | 2026-01-01 |
| '42.50' | NUMERIC(5,2) | 42.50 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT CAST('2026-01-01' AS DATE), CAST(100 AS VARCHAR(10));SELECT '123'::INT + 5 AS total, '{"key": "value"}'::JSONB AS payload;6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| ANSI Standard | CAST(expression AS target_type) is the universal ANSI SQL standard. |
| Failed Coercion Error | Attempting to cast invalid text (e.g. 'abc'::INT) aborts the transaction with a runtime error. |
| Index Invalidation on Implicit Cast | If a column is VARCHAR and you compare col = 123, the engine may implicitly cast col to INT, invalidating the B-Tree index! |
| Implicit cast index invalidation | Comparing a string column to an integer literal can trigger implicit casting that disables B-Tree index seeks. |
| Safe casting with error handling | Use TRY_CAST or regex checks to prevent queries from aborting on invalid string format conversions. |
7. Deep Dive: The Silent Index-Killer: Implicit Type Coercion
When you compare an indexed VARCHAR column against an integer literal (WHERE phone = 9876543210), SQL engines coerce the table column to an integer: WHERE CAST(phone AS INT) = 9876543210. This wraps the column in a function and forces a full table scan!
-- SLOW FULL TABLE SCAN (Implicit coercion invalidates index): WHERE phone_varchar = 9876543210; -- FAST B-TREE INDEX SEEK (Types match exactly): WHERE phone_varchar = '9876543210';
8. Advantages & Disadvantages
Advantages
- •Enables dynamic data transformation.
- •Resolves data type mismatches between client applications and schemas.
Disadvantages & Trade-offs
- •Implicit type conversion in WHERE clauses destroys query performance.
9. Common Interview Questions
Q1.Why can comparing an indexed VARCHAR column to an integer literal cause a full table scan?
In SQL type coercion rules, integers have higher precedence than strings. If phone_number is VARCHAR and the query executes WHERE phone_number = 123456, the database engine must implicitly convert the string column to an integer: WHERE CAST(phone_number AS INT) = 123456. Because the column is wrapped in an implicit cast function, the B-Tree index is disabled, forcing a full table scan!
Q2.What is the difference between standard ANSI CAST() and PostgreSQL :: shorthand?
Standard SQL uses CAST(expression AS type): CAST('123' AS INTEGER). PostgreSQL provides the concise :: operator shorthand: '123'::INTEGER. They are functionally identical under the hood, but CAST() is 100% portable across MySQL, Oracle, SQL Server, and SQLite, while :: is PostgreSQL-specific.
Q3.What is the difference between Implicit and Explicit Type Coercion?
Implicit coercion happens automatically behind the scenes (e.g. adding INT to FLOAT promotes the INT to FLOAT). Explicit coercion is specified directly by the developer using CAST() or ::. Relying on implicit coercion in WHERE clauses or JOIN conditions is dangerous because it often silently invalidates indexes or causes unexpected precision loss.
Q4.How do you safely cast strings to numbers without throwing fatal query errors on malformed data?
In standard databases, casting 'abc' to INT throws a fatal runtime exception that aborts the entire transaction. PostgreSQL provides regular expression validation or custom functions (SELECT CASE WHEN val ~ '^\d+$' THEN val::INT END). Engines like Snowflake, BigQuery, and SQL Server provide TRY_CAST(val AS INT), which returns NULL instead of throwing an error.
Q5.How does JSONB type casting work in PostgreSQL?
PostgreSQL provides specialized JSON operators: -> extracts a JSON object or array element (preserving JSON type), ->> extracts a JSON element as text, and #> extracts nested paths. Once extracted as text with ->>, it can be cast directly to relational types: (user_data->>'age')::INT.
10. Interview-Ready Answer
“Type conversion translates data types using ANSI CAST or PostgreSQL :: shorthand. Developers must be careful with implicit type coercion in WHERE clauses, as mismatched types can prevent B-Tree index utilization and force full table scans.”
11. Quick Test
Which query uses standard ANSI SQL syntax to convert a string to an integer?