sql / intermediate
Snippet
Explicit Type Conversion Using the CAST Operator
The ANSI SQL CAST operator explicitly converts a value or column expression from one data type into another (e.g., converting text or floating-point values into fixed numeric precision or dates), ensuring type safety across heterogeneous database systems.
snippet.sql
sql
1
2
3
4
5
6
SELECTproduct_id,CAST(sale_price AS DECIMAL(10, 2)) AS formatted_price,CAST(created_at AS DATE) AS sale_dateFROM product_salesWHERE CAST(sale_price AS DECIMAL(10, 2)) > 50.00;
Breakdown
1
SELECT
Initiates the query column projection list.
2
product_id,
Selects the primary product identifier without modification.
3
CAST(sale_price AS DECIMAL(10, 2)) AS formatted_price,
Converts sale_price to a exact numeric format with 2 decimal places.
4
CAST(created_at AS DATE) AS sale_date
Extracts only the date portion from a timestamp expression.
5
FROM product_sales
Identifies the source table containing product sales records.
6
WHERE CAST(sale_price AS DECIMAL(10, 2)) > 50.00;
Filters rows using explicit type casting within the conditional predicate.