CAST

An introduction to the expression CAST.

CAST is an expression that is used to change the data type of a value. The syntax for a CAST expression is:

`CAST` (string `AS` format).

Possible formats are INTEGER, DECIMAL, DOUBLE, BOOLEAN, DATETIME, DATE, TIME, GYEAR, GYEARMONTH, and DATETIMESTAMP.

In our dataset the revenue for each account company is stored as a decimal value. If we wanted to see the value as an integer we could run the query:

SELECT account,
       CAST(revenue AS INTEGER)
  FROM accounts

The results would be:

account revenue
Acme Corporation 1,100
Betasoloin 251
Codehow 2,715
Condax 5
Conecom 1,521
Dalttechnology 99
Dambase 2,174

Exercises (Continued from previous section)

The exercises below can be run from the “Try query” link below, but they cannot be saved. If you would like to save your queries, see this article for instructions. You can also do the exercises from a complete stand-alone tutorial located here.

Exercise 23

Write a query using the patient, description, and value columns from the observations table to return all the body height measurements for the patients in decimal form.

Try query

Hint

SELECT the columns patient, description, and CAST the value column AS a DECIMAL FROM the observations table WHERE the description column = “Body Height”

See solution