Lessons › SQL › Chapter 4: Shaping data
SQL lesson
CAST() and type conversion
Sometimes numbers are stored as text, like '149.99'. SQL can't add them up or sort them properly. CAST changes them: CAST(revenue AS NUMERIC) gives a real number. AS DATE gives a real date.
Try this lesson free →Example
Turn text into numbers
SELECT order_id,
CAST(revenue AS NUMERIC) AS revenue_numeric,
CAST(quantity AS INTEGER) AS quantity_int,
CAST(order_date AS DATE) AS order_date_typed
FROM orders| order_id | revenue_numeric | quantity_int | order_date_typed |
|---|---|---|---|
| O2001 | 149.99 | 3 | 2024-03-01 |
| O2002 | 89.5 | 1 | 2024-03-05 |
| O2003 | 320.0 | 5 | 2024-03-10 |
| O2004 | 45.75 | 2 | 2024-03-12 |
| O2005 | 210.3 | 4 | 2024-03-18 |
Step by step
- Stored as text, so SQL can't add it up or sort it properly.
SELECT order_id, CAST(revenue AS NUMERIC) AS revenue_numeric, CAST(quantity AS INTEGER) AS quantity_int, CAST(order_date AS DATE) AS order_date_typed FROM orders - CAST turns it into a real number.
SELECT order_id, CAST(revenue AS NUMERIC) AS revenue_numeric, CAST(quantity AS INTEGER) AS quantity_int, CAST(order_date AS DATE) AS order_date_typed FROM orders - INTEGER is a whole number. DATE is a real date.
SELECT order_id, CAST(revenue AS NUMERIC) AS revenue_numeric, CAST(quantity AS INTEGER) AS quantity_int, CAST(order_date AS DATE) AS order_date_typed FROM orders
Practice
1. Using shipments_raw, the weights came in as text. Show each shipment_id with weight_text converted to a number (NUMERIC). Name it weight_kg.
SELECT shipment_id, CAST(weight_text AS NUMERIC) AS weight_kg FROM shipments_raw2. Using orders_raw, price and quantity are both stored as text. Show each order_id with its order total: unit_price_text as a number (NUMERIC) times quantity_text as a whole number (INTEGER). Name it order_total.
SELECT order_id, CAST(unit_price_text AS NUMERIC) * CAST(quantity_text AS INTEGER) AS order_total FROM orders_raw3. Using inventory_raw, stock_text is stored as text. How many units are in stock across all warehouses? Convert stock_text to a whole number (INTEGER) and add it up. Name it total_stock.
SELECT SUM(CAST(stock_text AS INTEGER)) AS total_stock FROM inventory_raw4. Using products_raw, price_text is stored as text, so sorting it puts '8.50' above '120.00'. Show product_id and price_text, most expensive first, by sorting on price_text converted to a number (NUMERIC).
SELECT product_id, price_text FROM products_raw ORDER BY CAST(price_text AS NUMERIC) DESC5. Using promotions_raw, discount_text is stored as text. Show the promo_name of every promotion with a discount of 20 or more, comparing discount_text as a whole number (INTEGER).
SELECT promo_name FROM promotions_raw WHERE CAST(discount_text AS INTEGER) >= 20Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →