Skip to Main Content
SQL in a Nutshell
book

SQL in a Nutshell

by Kevin Kline
December 2000
Intermediate to advanced content levelIntermediate to advanced
224 pages
9h 52m
English
O'Reilly Media, Inc.
Content preview from SQL in a Nutshell

Name

CAST

Synopsis

The CAST command explicitly converts an expression of one datatype to another.

Vendor

Command

SQL Server

Supported

MySQL

Not supported

Oracle

Not supported

PostgreSQL

Supported

SQL99 Syntax and Description

CAST(expression AS data_type[(length)])

The CAST function converts any expression, such as a column value or variable, into another defined datatype. The length of the datatype may be supplied optionally for those datatypes (such as CHAR or VARCHAR) that support lengths.

Tip

Be aware that some conversions, such as DECIMAL values to INTEGER, result in rounding operations. Also, some conversion operations may result in an error if the new datatype does not have sufficient space to display the converted value.

Example

This example retrieves the year-to-date sales as a CHAR and concatenates it with a literal string and a portion of the book title. It converts ytd_sales to CHAR(5), plus it shortens the length of the title to make the results more readable:

SELECT CAST(ytd_sales AS CHAR(5)) + "Copies sold of " + CAST(title AS 
VARCHAR(30))
FROM titles
WHERE ytd_sales IS NOT NULL
  AND ytd_sales > 10000
ORDER BY ytd_sales DESC

This results in the following:

--------------------------------------------------- 
22246 Copies sold of The Gourmet Microwave
18722 Copies sold of You Can Combat Computer Stress
15096 Copies sold of Fifty Years in Buckingham Pala
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

SQL in a Nutshell, 3rd Edition

SQL in a Nutshell, 3rd Edition

Kevin Kline

Publisher Resources

ISBN: 1565927443