MySQL

Chapter 7 - DQL (Data Query Language)

CAST

In MySQL, the CAST function is used to convert a value from one data type to another. This is helpful when you need to ensure data types are compatible for comparison, calculations, or other operations. The CAST function can convert values into different types, such as CHAR, DECIMAL, DATE, DATETIME, and SIGNED or UNSIGNED integers. Understanding how to use CAST is crucial when working with mixed data types or performing operations that require specific formats.

Here’s a guide on using the CAST function in MySQL, along with examples:

  1. Basic Syntax for CAST():

    • The CAST() function allows you to explicitly convert a value to a specific data type.
    • Syntax:
    SELECT CAST('2023-09-01' AS DATE) AS converted_date;
    • This query converts the string '2023-09-01' into a DATE data type.
  2. Casting to CHAR (String):

    • You can cast a numeric or date value to a CHAR type, which converts it into a string.
    • Example:
    SELECT CAST(salary AS CHAR) AS salary_as_string FROM employees;
    • This query converts the salary column (assumed to be numeric) into a string.
  3. Casting to DECIMAL:

    • Casting a value to DECIMAL is useful when you need to perform calculations with floating-point precision.
    • Example:
    SELECT CAST(salary AS DECIMAL(10, 2)) AS salary_with_precision FROM employees;
    • This query casts the salary column to a DECIMAL type with two decimal places.
  4. Casting to SIGNED and UNSIGNED Integers:

    • You can cast values to SIGNED or UNSIGNED integers to control whether the value can be negative or not.
    • Example:
    SELECT CAST(salary AS UNSIGNED) AS unsigned_salary FROM employees;
    • This query converts the salary column to an unsigned integer, ensuring no negative values.
  5. Casting Dates to Strings:

    • You can cast a date to a string format using CAST(). This is helpful when you need to work with date values as text.
    • Example:
    SELECT CAST(hire_date AS CHAR) AS hire_date_string FROM employees;
    • This query converts the hire_date into a string format.
  6. Casting Numeric to DATETIME:

    • When dealing with numeric values that represent a timestamp, you can cast them to DATETIME format.
    • Example:
    SELECT CAST(UNIX_TIMESTAMP() AS DATETIME) AS current_datetime;
    • This query converts the current Unix timestamp into a DATETIME value.
  7. Casting VARCHAR to DATE:

    • If a VARCHAR column contains date values in string format, you can cast it to DATE for date operations.
    • Example:
    SELECT CAST('2023-09-15' AS DATE) AS valid_date;
    • This query converts the string '2023-09-15' into a DATE type.
  8. Combining CAST with Calculations:

    • You can combine CAST() with arithmetic operations to ensure consistent data types during calculations.
    • Example:
    SELECT first_name, last_name, CAST(salary AS DECIMAL(10, 2)) * 1.10 AS increased_salary FROM employees;
    • This query casts the salary to DECIMAL and calculates a 10% increase.
  9. Casting Boolean Values:

    • In MySQL, boolean values are represented as integers (0 for false, 1 for true), but you can cast them explicitly for clarity.
    • Example:
    SELECT first_name, CAST(1 AS BOOLEAN) AS is_active FROM employees;
    • This query casts the integer 1 to a boolean TRUE.
  10. Performance Considerations:

    • While using CAST ensures data type consistency, frequent casting in large datasets can affect performance. It’s good practice to minimize casting in performance-critical queries.

The CAST function in MySQL is a powerful tool for converting data types, ensuring that your data is formatted correctly for the operations you need to perform. It is particularly useful when dealing with mixed data types or when preparing data for calculations and comparisons.

Tansy SQL Course | CAST | Chapter 7 | Lesson 39 - Video Thumbnail

Test code

In this instance, the CAST function is applied to the order date, facilitating the conversion of datetime data type into the date format.

SELECT order_id, order_number, CAST(order_date AS DATE) FROM act_order;
Try it now

In this case, the CAST function is used to convert numeric data type with decimals into an integer data type, eliminating any decimal points.

SELECT employee_id, employee_number, CAST(salary AS INT) 
FROM org_employee;
Try it now

RDBMS Overview

Syntax of CAST


CAST(expression AS target_type)
  • expressionis the value you wish to convert.
  • target_typeis the data type you want the result to be.

Examples of CAST

Converting a price to an integer:

SELECT CAST(price AS INT) FROM products;

Formatting a date as a string:

SELECT CAST(order_date AS VARCHAR(10)) FROM orders;

TheCASTfunction is part of the ANSI SQL standard and is supported by various SQL databases like MySQL, PostgreSQL, SQL Server, and SQLite, ensuring consistency in its use and behavior across these systems.


Limitations of the CAST Function in SQL

  1. Data Loss:Casting from a higher precision or larger capacity data type to a lower one can result in data loss or truncation, such as fromFLOATtoINT.
  2. Performance:TheCASTfunction can increase computational overhead and affect query performance, especially with large datasets.
  3. Data Type Compatibility:Not all data type conversions are supported, and incompatible conversions will result in errors.
  4. Syntax and Support:Different SQL systems may have varying levels of support forCAST, potentially leading to inconsistencies.
  5. Implicit Conversion Risks:Implicit conversions withoutCASTcan lead to unexpected results if the rules for conversion are not well understood.
  6. Locale and Format:Locale settings can affect the behavior ofCASTwith locale-sensitive data types like dates and times.
  7. Storage Format:Data stored in non-standard formats may require additional manipulation beyondCAST.
  8. Precision and Scale:Consideration of precision and scale is necessary when casting to decimal types to avoid errors.
  9. SQL Injection:Dynamic SQL usingCASTcan be vulnerable to SQL injection if user input is not properly sanitized.
  10. Default Values:UnlikeCOALESCEorISNULL,CASTdoes not handle NULLs or provide a default value if conversion fails.

CAST EXAMPLE1

i

i

In this instance, the CAST function is applied to the order date, facilitating the conversion of datetime data type into the date format.

CAST EXAMPLE2

i

i

In this case, the CAST function is used to convert numeric data type with decimals into an integer data type, eliminating any decimal points.

Comments(0 comments)

Comments Not Found