SQL CAST

The SQL CAST function is used to convert one data type into another. It is particularly useful when dealing with data that needs to be presented or calculated in a different format. The CAST function is commonly used in SELECT statements, especially for type conversions involving numbers, dates, and strings.

In this tutorial, we will explore the SQL CAST function, its syntax, and how to use it with practical examples.


Syntax of SQL CAST Function

The basic syntax of the SQL CAST function is:

</>
Copy
CAST(expression AS target_data_type)

Explanation:

  • expression: The value or column that needs to be converted.
  • target_data_type: The data type to which the expression should be converted (e.g., INT, VARCHAR, DECIMAL, DATE).

Step-by-Step Examples Using SQL CAST

1 Converting String to Integer

Suppose we have a table employees that stores employee details, including salaries as text values. We want to convert the salary from VARCHAR to INT for calculations.

In SQL Server:

</>
Copy
CREATE TABLE employees (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    salary VARCHAR(10)
);

Insert some sample data:

</>
Copy
INSERT INTO employees (name, salary)
VALUES 
('Arjun', '50000'),
('Ram', '60000'),
('Priya', '70000');

Now, we will convert the salary column from VARCHAR to INT using CAST:

</>
Copy
SELECT name, salary, CAST(salary AS INT) AS salary_int
FROM employees;