SQL•Type Casting
SQL Data Types and CAST Function with Examples
Learn SQL storage types and explicit type conversion using CAST(column AS type).
Syntax
SELECT CAST(string_col AS INTEGER) FROM table;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| CAST(expr AS type) | Function | Converts expression to target SQL type. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE raw_logs (
id INTEGER PRIMARY KEY,
event_name TEXT,
response_code_text TEXT
);
INSERT INTO raw_logs VALUES
(1, 'login', '200'),
(2, 'upload', '201'),
(3, 'auth_fail', '401');
-- Explicitly cast text column to INTEGER for numeric comparison
SELECT
event_name,
CAST(response_code_text AS INTEGER) AS response_code
FROM raw_logs
WHERE CAST(response_code_text AS INTEGER) >= 400;Expected Output:
event_name response_code ---------- ------------- auth_fail 401
How It Works: Step-by-Step
- Lines 7-10: Stores HTTP status codes as text strings.
- Lines 13-17: CASTs response_code_text to INTEGER for numeric filtering.
Key Concepts
- CAST converts types explicitly across text, integer, and real types.
Common Mistake: Comparing numbers stored as TEXT using greater-than (> )
In text sorting, "100" is less than "20" (alphabetical comparison). Cast to INTEGER first.
❌ Incorrect
WHERE text_num > "20" // "100" < "20" alphabetically!
✅ Correct
WHERE CAST(text_num AS INTEGER) > 20
Related SQL Tutorials & Compiler
SQL Session-Level Variable Mapping Constraints and CTE Declarations
Define and map session-level variables, CTE bind parameters, and column expressions in SQL queries.
SQL WHERE Filtering: Comparison and Logical Operators (AND, OR, IN)
Filter records using the WHERE clause with comparison, AND, OR, NOT, IN, and BETWEEN.
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.