SQL | Conversion Function
Improve Article
Save Article
Like Article
- Difficulty Level : Easy
- Last Updated : 29 Sep, 2022
Improve Article
Save Article
In some cases, the Server uses data of one type where it expects data of a different data type. This can happen when the Server can automatically convert the data to the expected data type. This data type conversion can be done implicitly by the Server, or explicitly by the user.
Implicit Data-Type Conversion :
In this type of conversion the data is converted from one type to another implicitly [by itself/automatically].
- QUERY:
SELECT employee_id,first_name,salary FROM employees WHERE salary > 15000;
- OUTPUT :
- QUERY:
SELECT employee_id,first_name,salary FROM employees WHERE salary > '15000';
- OUTPUT :
- Here we see the output of both queries came out to be same,inspite of 2nd query using ‘15000’ as text, it is automatically converted into int data type.
Explicit Data-Type Conversion :
TO_CHAR Function :
TO_CHAR function is used to typecast a numeric or date input to character type with a format model [optional].
SYNTAX :
TO_CHAR[number1, [format], [nls_parameter]]
Using the TO_CHAR Function with Dates :
SYNTAX :
TO_CHAR[date, ’format_model’]
The format model:
- Must be enclosed in single quotation marks and is case sensitive
- Can include any valid date format element
- Has an fm element to remove padded blanks or suppress leading zeros
- Is separated from the date value by a comma
EXAMPLE :
SELECT employee_id, TO_CHAR[hire_date, ’MM/YY’] Month_Hired FROM employees WHERE last_name = ’Higgins’;
OUTPUT :
Elements of the Date Format Model :
Elements of the Date Format Model :
Date 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 :
Specifying Suffixes to Influence Number Display :
EXAMPLE :
SELECT last_name, TO_CHAR[hire_date, ’fmDD Month YYYY’] AS HIREDATE FROM employees;
OUTPUT :
Using the TO_CHAR Function with Numbers :
SYNTAX :
TO_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 :
EXAMPLE :
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 employee_id,first_name,salary FROM employees WHERE salary > '15000';0
OUTPUT :
My Personal Notes arrow_drop_up
Save