REQUEST COMPLIMENTARY SQLS*PLUS LICENCE
Sql cast – examples
Sql cast: in SQL language implementations the implicit type conversion can be performed. For example, in SQL Server and Sybase ASE. Transact-SQL when comparing or combining values of smallint and int types, data of smallint type are implicitly converted to int type.
You will now learn how to use the CAST function in SQL Server (Transact-SQL) with syntax and examples.
Description of the Sql cast function
In SQL Server (Transact-SQL), the CAST function converts an expression from one data type to another data type.
Syntax of the Sql cast function
Syntax of the CAST function in SQL Server (Transact-SQL):
CAST( expression AS type [ (length) ] )
Parameters or arguments
- expression– value for conversion to another data type.
- type – data type to which you want to convert the expression. It can be one of the following: bigint, int, smallint, tinyint, bit, decimal, numeric, money, smallmoney, float, real, datetime, smalldatetime, char, varchar, text, nchar, nvarchar, ntext, binary, varbinary, or image.
- length – is optional. The length of the resulting data type for char, varchar, nchar, nvarchar, binary, and varbinary.
Note:
- When converting from float or numeric to integer, the CAST function truncates the result. For other conversions the CAST function will round up the result.
- See also CONVERT function.
Application
The CAST function can be used in future versions of SQL Server (Transact-SQL):
SQL Server vNext, SQL Server 2016, SQL Server 2015, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005
Example 1:
Let’s look at some examples of the SQL Server function of CAST to understand how to use the CAST function in SQL Server (Transact-SQL). For example:
SELECT CAST(12.81 AS int);
--Result: 12 (Result truncated)
SELECT CAST(12.81 AS float);
--Result: 12.81 (Result not truncated)
SELECT CAST(14.6 AS varchar);
--Result: '14.6'
SELECT CAST(14.6 AS varchar(4));
--Output: '14.6' SELECT CAST(14.6 AS varchar(4))
SELECT CAST('14.6' AS float); -Output: '14.6' SELECT CAST(14.6' AS varchar(4));
--Output: '14.6' SELECT CAST('14.6' AS float)
SELECT CAST('25.12.2017' AS datetime);
--Result: '2017-12-25 00:00:00:00.000'
Example 2:
Print the average price of laptops with the preceding text “average price = “.
Attempt to execute the request
SELECT 'Average price = '+AVG(price)
FROM Laptop;
will lead to an error message:
Implicit conversion from data type varchar to money is not allowed. Use the CONVERT function to run this query.
(“Implicit conversion from data type varchar to money is not allowed. Use the CONVERT function to run this query”).
This message means that the system cannot perform an implicit conversion of varchar to money type. In such situations, explicit type conversion may help. As indicated in the error message, you can use the CONVERT function. However, this function is not standardized, so for portability purposes it is recommended to use the CAST standard expression. That’s where we’ll start.
So, if you rewrite our query in the form of
SELECT 'Average price = '+ CAST(AVG(price) AS CHAR(15))
FROM Laptop;,
we’ll get what we need:
Average price = 1003.33
We used an explicit CAST type conversion expression to convert the average price value to a string representation.
The syntax of CAST expression is very simple.
CAST(<expression> AS <data type>)
Attention:
Firstly, you should keep in mind that not all type conversions are possible (the standard contains a table of acceptable data type conversions). Secondly, the result of the CAST function for the value of the expression equal to NULL will also be NULL.
Let’s look at another example.
Example 3:
Determine the average year that ships are launched from the Ships table.
Request:
SELECT AVG(launched)
FROM Ships;
will result in 1926. Basically, everything is right, because we got what we asked for as a result – a year. However, the arithmetic mean will be about 1926,2381.
Here we should remind you that the aggregate functions (except COUNT, which always returns an integer) inherits the data type of the processed values. Since the field launched is an integer, we have received the average value with the discarded fractional part (note – not rounded).
And if we are interested in the result with a given accuracy, say, to two decimal places? Applying the CAST expression to the mean will not give us anything for the above reason. Indeed,
SELECT CAST(AVG(launched) AS NUMERIC(6,2))
FROM Ships;
will return to 1926.00. Consequently, CAST must be applied to an aggregate function argument:
SELECT AVG(CAST(launched AS NUMERIC(6,2)))
FROM Ships;
Result – 1926.90909. Wrong again. The reason is that when calculating the average value, an implicit type conversion was performed. Let’s take one more step:
SELECT CAST(AVG(CAST(launched AS NUMERIC(6,2))) AS NUMERIC(6,2))
FROM Ships;
The result is what we need – 1926.91. However, this decision looks very cumbersome. We’ll make an implicit type conversion work for us:
SELECT CAST(AVG(launched*1.0) AS NUMERIC(6,2))
FROM Ships;
Now we used an implicit conversion of an integer argument to an exact numeric type (EXACT NUMERIC) multiplying it by a real unit and then we applied an explicit type conversion of the result of an aggregate function.
Sql Training Online – Cast Function
MORE NEWS
PreambleNoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...
PreambleMongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...
5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...
The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...
PreambleMS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...
First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...
PreambleAtom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...
PreambleMongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...
FlexibilityOne of the most advertised features of MongoDB is its flexibility. Flexibility, however, is a double-edged sword. More flexibility means more...
PreambleSQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...
PreambleWriting an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...
PreambleOracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...
PreambleIBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...
What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....
PreambleIf you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...
PreambleStarting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...