Difference between revisions of "CAST"
From SQLZOO
(Created page with "<table align='right' border='1'> <caption>Compatibility</caption> <tr><th colspan='3'>CAST(expr AS type)</th></tr> <tr><td align='center'>'''Engine'''</td><td align='center'>'...") |
|||
| Line 20: | Line 20: | ||
You can also CAST a date to a string to extract components using SUBSTRING or make up another date. | You can also CAST a date to a string to extract components using SUBSTRING or make up another date. | ||
<source lang='sql' class='def'> | <source lang='sql' class='def'> | ||
| − | SELECT CAST(population/1000000 AS DECIMAL(8,1)) AS a | + | SELECT CAST(population/1000000 |
| + | AS DECIMAL(8,1)) AS a | ||
,population/1000000 AS b | ,population/1000000 AS b | ||
FROM bbc | FROM bbc | ||
Revision as of 11:54, 13 July 2012
| CAST(expr AS type) | ||
|---|---|---|
| Engine | OK | Alternative |
| ingres | Yes | |
| mysql | Yes | |
| oracle | Yes | |
| postgres | Yes | |
| sqlserver | Yes | |
CAST
CAST allows you to convert from one type to another.
Often a CAST is implicit - for example if you concatenate a string with a number the number will be automatically changed to a string. However sometimes you need to make the CAST explicit.
CAST(expr TO type)
In this example we get the population in millions by casting the floating point value to DECIMAL(8,1) - this ensures one decimal place of accuracy. You can also CAST a date to a string to extract components using SUBSTRING or make up another date.
SELECT CAST(population/1000000 AS DECIMAL(8,1)) AS a ,population/1000000 AS b FROM bbc
See also