In SQL data type conversion is important for effective database management and accurate query results. Data type conversion ensures that data from different sources or columns can be correctly interpreted and manipulated, especially when dealing with different formats like numbers, text, dates, and other data types.
This article provides an in-depth explanation, including examples of when and how they are used, as well as relevant SQL functions like TO_CHAR, TO_NUMBER, and TO_DATE.
Types of Data Type Conversion in SQLThere are two main types of data type conversion in SQL.
Implicit data type conversion, also known as automatic type casting, occurs when SQL automatically converts one data type to another without requiring any intervention from the user. The DBMS does this whenever it detects a need for the conversion, based on the context of the operation.
From To VARCHAR2 or CHAR NUMBER VARCHAR2 or CHAR DATE DATE VARCHAR2 NUMBER VARCHAR2 Example of Implicit Data Type ConversionConsider the following example where we retrieve employees whose salary is greater than 15,000.
create table employees( employee_id INT PRIMARY KEY , first_name VARCHAR(50) , salary INT); INSERT INTO employees(employee_id,first_name,salary) VALUES (100,'Steven',24000), (101,'Neena',17000), (102,'Lex',17000), (103,'John',11000), (104,'Robert',12000), (105,'Leo',10000);
Here, we want to retrieve the employee_id, first_name, and salary from the employees table whose salary is greater than 15000 then the query is
Query:
SELECT employee_id,first_name,salary FROM employees WHERE salary > 15000;
Output:
In the second query, we provide the value '15000' as a string, and SQL automatically converts it to an integer to match the column data type.
Query:
SELECT employee_id,first_name,salary FROM employees WHERE salary > '15000';
Output:
Despite the second query using '15000' as a string, SQL automatically converts it into an integer before comparing it to the salary column, which is an integer type. The results for both queries will be the same.
Explicit Data-Type ConversionExplicit data type conversion, or type casting, occurs when the user explicitly specifies the conversion of a value from one type to another. This is necessary when SQL cannot automatically infer the correct conversion or when you want to ensure the data is handled in a specific way.
SQL provides several functions for explicit type conversion, including:
Let's use the TO_CHAR function to convert a numeric value (salary) into a formatted string.
SELECT employee_id, TO_CHAR(salary, '$99,999.00') AS formatted_salary
FROM employees
WHERE last_name = 'Ernst';
In this query:
The TO_CHAR function is used to format the salary field as a string with a dollar sign and thousands separator.
Output:
employee_id formatted_salary 1001 $24,500.00 1002 $30,000.00 SQL Functions for Explicit Data Type Conversion 1. TO_CHAR FunctionTO_CHAR function is used to typecast a numeric or date input to a character type with a format model (optional).
Using the TO_CHAR Function with DatesTO_CHAR(expression, 'format_model')
TO_CHAR(date, ’format_model’)
The format model:
Example:
SELECT employee_id, TO_CHAR(hire_date, ’MM/YY’) Month_Hired FROM employees WHERE last_name = ’Higgins’;
Output :
EMPLOYEE_ID MONTH_HIRED 205 06/94Elements of the Date Format Model
YYYY Full-year in Numbers YEAR Year spelled outYY
Two-digit value of year
MM Two-digit value for the month MONTH Full name of the month MON Three Letter abbreviation of the monthD
Number of Days in a Week
DY Three-letter abbreviation of the day of the week DAY Full Name of the Day DD Numeric day of the monthDate Format Elements - Time Formats
Use the formats listed in the following tables to display time information and literals and to change numerals to spelled numbers.
Other Formats
ELEMENT DESCRIPTION / . , Punctuation is reproduced in the result "of the" The quoted string is reproduced in the resultSpecifying Suffixes to Influence Number Display
ELEMENT DESCRIPTION TH Ordinal Number (for example DDTH for 4TH SP Spelled outnumber (for example DDSP for FOUR SPTH or THSP spelled out ordinal numbers (for example DDSPTH for FOURTHExample :
SELECT last_name, TO_CHAR(hire_date, ’fmDD Month YYYY’) AS HIREDATE FROM employees;
Output :
LASTNAME HIIREDATE Austin 25 January 2005 Shubham 20 June 2004 Nishant 15 January 1999 Ankit 15 July 1995 Vanshika 5 August 2004 Kusum 10 June 1994 Faviet 11 March 2005 King 9 April 1996 2. Using the TO_CHAR Function with NumbersTO_CHAR(number, ’format_model’)
These are some of the format elements you can use with the TO_CHAR function to display a number value as a character :
9 Represent a number 0 Forces a zero to be displayed $ places a floating dollar sign L It uses the floating local currency symbol . Print a decimal point , Prints a Thousand indicatorExample :
SELECT TO_CHAR(salary, ’$99,999.00’) SALARY FROM employees WHERE last_name = ’Ernst’;
Output :
Using the TO_NUMBER and TO_DATE Functions :
Convert a character string to a number format using the TO_NUMBER function :
TO_NUMBER(char[, ’format_model’])
Convert a character string to a date format using the TO_DATE function:
TO_DATE(char[, ’format_model’])
These functions have an fx modifier. This modifier specifies the exact matching for the character argument and date format model of a TO_DATE function.
Example :
SELECT last_name, hire_date FROM employees WHERE hire_date = TO_DATE(’May 24, 1999’, ’fxMonth DD, YYYY’);
Output :
LASTNAME HIREDATE Kumar 24-MAY-1999 ConclusionData type conversion in SQL, both implicit and explicit, is an important concept that helps you manipulate and present data effectively. Implicit conversion simplifies the process by automatically adjusting mismatched data types, while explicit conversion provides more control over how data is transformed. By using functions like TO_CHAR, TO_NUMBER, and TO_DATE, you can handle various types of data more efficiently and ensure the consistency of your database operations.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4