This lesson on CONVERTING DATA TYPES is hands-on and example-driven. You will learn how to use the SQL CAST function to explicitly change the data type of a value. This skill allows you to manage data precision, such as converting floating-point numbers to integers or formatting numerical data as text strings for display or concatenation.
What You'll Be Able To Do
- Explain the necessity of explicit type conversion using CAST.
- Apply CAST syntax to convert a numerical value into an integer.
- Describe the resulting loss of granularity when casting a decimal to an integer.
- Format a number using CAST to a decimal type with specified precision.
- Transform numerical data into a variable character (string) format.
Detailed Concept Walkthrough
1. Using the CAST Function
CAST is the standard SQL function used to explicitly change the data type of an expression or column value. This is essential when operations require specific types, such as ensuring a calculation uses integer math or preparing a number for string concatenation.
- Mechanism: The function takes the value you want to convert and the target data type as arguments, following the structure
CAST(expression AS target_type). The database engine attempts to interpret the input value according to the rules of the specified target type. - Syntax Rule: The
ASkeyword is mandatory; it clearly separates the input expression from the desired output type, making the conversion explicit and readable. The target type must be a valid SQL data type supported by the specific database system you are using (e.g.,INTEGER,VARCHAR,DECIMAL). - Execution Flow: When executed within a
SELECTstatement, the conversion happens row-by-row, transforming the data in memory before it is returned to the user. If the conversion fails (e.g., trying to cast the text 'hello' to an integer), the query will typically return an error or a NULL value, depending on the database configuration.
SELECT
CAST(42.75 AS INTEGER) AS integer_result, -- Converts to a whole number
CAST(100 AS VARCHAR(10)) AS string_result, -- Converts number to text
CAST('2023-01-01' AS DATE) AS date_result; -- Converts text representation to a date type
Key Takeaway: Use CAST(expression AS type) to force the database to treat data as a different type.
2. Casting to Integer and Granularity Loss
Converting a floating-point or decimal number to an INTEGER removes all fractional components, resulting in a whole number. This process is crucial for counting or indexing but inherently sacrifices the granularity of the original data.
- Mechanism: When casting to
INTEGER, the database typically truncates the decimal part rather than performing mathematical rounding (though behavior can vary by system). For example, casting 4.9 to an integer often results in 4, not 5, unless a specific rounding function is applied beforehand. - Under the Hood: Integers require significantly less memory storage than floating-point or decimal types because they only store the whole number value. This efficiency gain is traded off against the loss of precision, which must be carefully considered in financial or scientific applications.
- Best Practice: Always be aware of the source data type when casting to
INTEGER, especially if the original data represents currency or measurements where the decimal component is meaningful. If mathematical rounding is required, use specific functions likeROUND()before applying theCAST.
SELECT
CAST(42.99 AS INTEGER) AS TruncatedValue, -- Result is 42 (truncation)
CAST(42.01 AS INTEGER) AS LowValue,
-- If rounding is needed before casting:
CAST(ROUND(42.99) AS INTEGER) AS RoundedValue; -- Result is 43
Key Takeaway: Casting to INTEGER removes decimal precision, usually by truncation, which is irreversible.
3. Controlling Precision and Formatting
CAST allows you to define the exact precision of a number using DECIMAL(p, s) or to convert numerical data into a text format using VARCHAR. This control is vital for standardizing output formats and preparing data for display.
- Mechanism: When casting to
DECIMAL(p, s),pspecifies the total number of digits (precision) andsspecifies the number of digits after the decimal point (scale). If the input number exceeds the defined precision, the database will either truncate or round the value to fit the specified scale. - Variable Characters: Casting to
VARCHAR(orTEXT/STRING) transforms the numerical representation into a sequence of characters. This is necessary when you need to combine numbers with text (concatenation) or when the data needs to be treated as a label rather than a value for calculation. - Nuance: Specifying the length of the
VARCHAR(e.g.,VARCHAR(50)) is a best practice, as it helps the database allocate appropriate memory and prevents potential truncation errors if the resulting string is too long. If the number is cast to a string, leading or trailing zeros might be added or removed depending on the system's default formatting rules.
SELECT
CAST(123.4567 AS DECIMAL(5, 2)) AS LimitedDecimal, -- Total 5 digits, 2 after decimal (123.46)
CAST(987.65 AS DECIMAL(3, 1)) AS OverflowExample,
CAST(12345 AS VARCHAR(10)) AS TextOutput; -- Result is the string '12345'
Key Takeaway: Use DECIMAL(p, s) to enforce specific numerical precision and VARCHAR to convert numbers into displayable text.
Topics Covered in CONVERTING DATA TYPES
- CAST Function Introduction (0:13 - 0:25) — The CAST function explicitly converts data from one type to another in SQL.
- Converting to Integer (0:25 - 0:46) — Casting to an integer results in a whole number, causing a loss of granularity by removing the decimal portion.
- Precision Loss Warning (0:46 - 0:51) — Losing decimal precision is a critical consequence of converting floating-point numbers to integers.
- Defining Decimal Precision (0:51 - 1:16) — You can limit the number of decimal places by casting to a decimal type with specified precision and scale.
- Converting to String (1:17 - 1:29) — Numerical data can be transformed into a variable character text string using CAST.
- Review and Summary (1:29 - 1:51) — Reviewing the different conversion types demonstrates the flexibility of the CAST function.
SQL Cheat Sheet
-
CAST(expression AS type)— Explicitly converts one data type to anotherCAST(42.5 AS INTEGER) -
INTEGER— Converts a number to a whole numberCAST(4.9 AS INTEGER) -
DECIMAL(p, s)— Converts to a number with defined total digits (p) and scale (s)CAST(1.234 AS DECIMAL(3, 1)) -
VARCHAR(n)— Converts data into a variable length text stringCAST(100 AS VARCHAR(5))
Comparison Table
| Target Type | Primary Effect | Precision Handling |
|---|---|---|
| INTEGER | Creates a whole number. | Decimal part is lost (truncated). |
| DECIMAL(p, s) | Creates a fixed-precision number. | Rounds or truncates to fit scale (s). |
| VARCHAR(n) | Creates a text string. | Numerical value is preserved as text. |
Common Pitfalls
- Mistake: Assuming CAST to integer automatically performs mathematical rounding. Avoid: Use ROUND() function before casting if rounding is required.
- Mistake: Casting a large number to a DECIMAL(p, s) that is too small. Avoid: Ensure the precision p is large enough to hold the whole number part.
- Mistake: Forgetting the AS keyword in the CAST syntax. Avoid: Always structure the function as CAST(value AS target_type).
FAQs
- Why do I need to use CAST? CAST forces the database to treat data explicitly as a different type, which is necessary for specific operations like concatenation or precision control.
- What happens if I cast a decimal number like 4.9 to an integer? The database typically truncates the decimal part, meaning the result will be 4, losing the fractional value.
- What is a 'variable character' type? It is a common SQL term (often VARCHAR) for a text string that can hold letters, numbers, and symbols.
- Does casting a number to VARCHAR change the value? No, the numerical value remains the same, but it is now stored and treated as text, meaning you cannot perform mathematical operations on it.