Example 1
Cast text digits to an integer
Casting avoids leaving the value as plain text when you need numeric behavior later in the query.
Engine-specific syntax
Setup
CREATE TABLE raw_scores (score_text VARCHAR(10));
INSERT INTO
raw_scores (score_text)
VALUES
('42');SQL
SELECT
CAST(score_text AS SIGNED) AS score_number
FROM
raw_scores;| score_number |
|---|
| 42 |
Engine-specific syntax
Setup
CREATE TABLE raw_scores (score_text VARCHAR(10));
INSERT INTO
raw_scores (score_text)
VALUES
('42');SQL
SELECT
CAST(score_text AS INT) AS score_number
FROM
raw_scores;| score_number |
|---|
| 42 |
Engine-specific syntax
Setup
CREATE TABLE raw_scores (score_text VARCHAR(10));
INSERT INTO
raw_scores (score_text)
VALUES
('42');SQL
SELECT
CAST(score_text AS INTEGER) AS score_number
FROM
raw_scores;| score_number |
|---|
| 42 |
The cast target syntax differs slightly, but the converted numeric result is the same.