0% found this document useful (0 votes)
3 views26 pages

01.Murachs MySQL 2019 Chapter 08

This document provides an overview of MySQL data types, including character, numeric, date and time, large object (LOB), spatial, and JSON types. It explains how to work with these data types, including converting between them and their storage requirements. The chapter emphasizes the importance of selecting the appropriate data type for different kinds of information to optimize database performance and storage efficiency.

Uploaded by

Thai Vu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

01.Murachs MySQL 2019 Chapter 08

This document provides an overview of MySQL data types, including character, numeric, date and time, large object (LOB), spatial, and JSON types. It explains how to work with these data types, including converting between them and their storage requirements. The chapter emphasizes the importance of selecting the appropriate data type for different kinds of information to optimize database performance and storage efficiency.

Uploaded by

Thai Vu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

How to work

with data types


So far, you have been using SQL statements to work with the three most
common types of data: strings, numbers, and dates. Now, this chapter takes a
more in-depth look at the data types that are available with MySQL and shows
some basic skills for working with them. When you complete this chapter,
you' ll have a thorough understanding of the data types, and you'll know how to
use some functions to convert one data type to another.

The data types .................................................................... 232


Ove1·view .................... ................................... ............ ................................... 232
The character types ... ........ ........................................................................... 234
The integer types ....... ........................................................ ..... .....................236
T he fixed-point and floating-point types ..................................................... 238
The d.ate and time types ..................... ......................................................... 240
The ENUM and SET types ....................... ...................... ....... ............... ..... 244
T he large object types .. ............................................... .......... ................. ..... 246
How to convert data ........................................................... 248
How implicit data conversion works .......................................................... 248
How to convert data using the CAST and CONVERT functions .... ........... 250
How to convert data using the FORMAT and CHAR functions ................ 252
Perspective ......................................................................... 254
232 Section 2 More SQL skills cts you need them

The data types


A column's data type specifies the kind of information the column is
intended to store. In addition, a column's data type determines the operations
that can be performed on the column.

Overview
The MySQL data types can be divided into the five categories shown in
figure 8-1. To start, the character data types are intended for storing a string of
one or more characters, which can include letters, numbers, sy1nbols, or special
characters. The terms character, string, and text are used interchangeably to
describe this type of data.
The numeric data types are intended for storing numbers that can be used
for mathematical calculations. As you'll see in this chapter, MySQL can store
numbers in a variety of formats. At a basic level, you can divide numbers into
two categories: integers and real numbers. Integers are numbers that don't have a
decimal point, and real numbers are numbers that have a decimal point.
The date and time data types are intended for storing dates, times, or
both dates and times. These data types are typically referred to as date/time or
temporal data types.
Since the first three categories are the most widely used, this book focuses
on these data types. However, MySQL also provides large object (LOB) data
types that are useful for storing images, sound, video, and large amounts of
character data. In addition, MySQL provides spatial data types that are useful
for storing geographical values such as global positioning system (GPS) data.
These data types are referred to as geometry types because they define a point or
group of points that represent any location or area in the world.
Finally, MySQL provides the ISON data type, which is used to store
JavaScript Object Notation (ISON) documents. Although you can store JSON
documents in a character column, the JSON data type provides two advantages.
First, when you store a JSON document in a JSON column, the document is
automatically validated. Then, if it's invalid, an error occurs. Second, the internal
storage format provides for quick access to the document.
Clzapter 8 How to work with data types 233

Data types
Category Description
Character Strings of character data
Numeric Numbers that don't include a decimal point (integers) and
numbers that include a decimal point (real numbers)
Date and time Dates, times, or both
Large Object (LOB) Large strings of character or binary data
Spatial Geographical values
JSON JSON documents

Description
• MySQL provides data types for storing many types of data.
• Numbers that don' t include a decimal point are known as integers.
• Numbers that include a decimal point are known as real numbers.
• The date and time data. types are often referred to as the date/time or temporal data
type.';.
• The large object (LOB) data types are ·useful for storing images, sound, video, and
large amounts of text.
• The spatial data types are useful for storing geometric or geographical values
such as global positioning system (GPS) data. These data types are referred to as
geometry types.
• The ISON data type is used for storing JavaScript Object Notation (ISON)
documents.

Figure 8-1 Data type overview


234 Section 2 More SQL skills cts you need them

The character types


Figure 8-2 presents the two most common character data types supported by
MySQL: CHAR and VARCHAR. These data types store strings of characters.
You use the CHAR type to store fixed-length st1·ings. Data stored using this
data type always occupies the same number of bytes regardless of the actual
le·ngth of the string. This data type is typically used to define columns that have
a fixed number of characters. For example, the vendor_state column in the
Vendors table is defined as CHAR(2) because it always contai11s two characters.
However, if two chru·acters are stored in a CHAR(lO) column, MySQL appends
eight spaces to the string so it contains 10 char·acters.
You use the VARCHAR data type to store variable-length strings. Data
stored using this data type occupies only the number of bytes needed to store
the string plus an extra byte to store the length of the string. This data type
is typically used to define colt1mns whose lengths vary from one row to the
next. For example, the vendor_name column in the Vendors table is defined as
VARCHAR(50) because the length of each vendor's name varies.
With MySQL 8.0 and later, the CHAR and VARCHAR types use the
uif81nb4 character set by default. This character set uses up to four bytes to
store each character. As a 1·esult, it's referred to as a multiple-byte c·haracter set.
This allows the utf8mb4 character set to support the characters specified by the
Unicode standard, which includes most characters from most of the world's
languages. To do that, this character set uses 1 byte for characters that are used
in English and by most western European languages. It uses 2 bytes for most
European and Middle Eastern script letters. And it uses 3 bytes for Korean,
Chinese, and Japanese ideographs. To store emojis and other icons, it uses 4
bytes.
When you use the utf8mb4 character set with a CHAR type, MySQL must
reserve four bytes for each character. As a result, MySQL must t1se 8 bytes for
the CHAR(2) type, and it must use 40 bytes for the CHAR(l 0) type.
However, when you use the VARCHAR type, MySQL doesn't need to
reserve space for each character. As a result, if you are using English letters and
symbols, MySQL only uses one byte per character, plus one byte to store the
length of the string. For example, when you store a string of 'CA', MySQL only
uses 3 bytes. This shows that you can typically save storage space by using the
VARCHAR type.
With MySQL 5.6 and 5.7, the CHAR and VARCHAR types used the
uif8,nb3 character set. This character set is similar to the utf8mb4 character set,
but it can only use up to 3 bytes to store each chru·acter. Because of that, it's not
able to store the emojis that are becoming so prevalent. Note that this character
set is deprecated in MySQL 8.0 and will be removed in a future release.
With MySQL 5.5 and earlier, the CHAR and VARCHAR types used
the latinl character set by default. This character set uses one byte to store
each character. As a result, it's referred to as a single-byte character set. This
character set supports all of the characters that are used in English and by most
western European languages. However, it doesn't support other characters such
as Middle Eastern script letters and Korean, Chinese, and Japanese ideographs.
Clzapter 8 How to work with data types 235

The character types


Type Bytes Description
CHAR(M) Mx4 Fixed-length strings of character data where M is the number of
characters, between O and 255. With the utf8mb4 character set,
MySQL must reserve four bytes for each character in a CHAR
column because that's the maximum possible length.
VARCHAR (M) L+l Variable-lengtl1 strings of character data where M is the 1naxi-
mum number of characters, between O and 255. For English and
Latin characters, the number of bytes used to store the string is
equaJ to length of the string (L) plus 1 byte to record its length.

How the character types work with utf8mb4


Data type Original value Value stored Bytes used
CHAR (2) 'CA' 'CA ' 8
CHAR ( lO ) 'CA' 'CA I
40
VARCHAR ( 1 0 ) 'CA ' ' CA ' 3
VARCHAR ( 2 0) ' California' 'Califo rni a' 11
VARCHAR ( 2 0 ) 'Ne w Yor k' ' New Yo rk' 9
VARCHAR ( 2 0 ) "Murac h's MySQL" "Mu rac h's MyS QL" 15

How the utf8mb4 character set works


• Basic Latin letters, digits, and punctuation signs use one byte.
• Most European and Middle East script letters use 2 bytes.
• Korean, Chinese, and Japanese ideographs use 3 bytes.
• E1nojis and other icons use 4 bytes.

Description
• The CHAR type js t1sed for fixed-length strings. A column with trus type t1ses the
same amount of storage for each value regardless of the actual length of the st1ing.
• The VARCHAR type is used for variable-length strings. A column with this type uses
a varying amount of storage for each value depending on the length of the string.
• By default, MySQL 8.0 and later use the utj8mb4 character set for the CHAR and
VARCHAR types. This character set is a multiple-byte character set. It typically
uses 1 byte per character, but can use up to 4 bytes per character. However, the
utf8mb4 format provides for all characters in most languages by providing support
for all of the characters in the Unicode stan.dard.
• By default, MySQL 5.6 and 5.7 use the utj8mb3 character set for the CHAR and
VARCHAR types, which can use up to 3 bytes per character.
• By default, MySQL 5.5 and earlier use the latinl character set for the CHAR and
VARCHAR types. This character set is a single-byte character set that supports all
of the characters that are used in English and by most western European languages.
• To learn how to change the character set, please see chapter 11 .

Figure 8-2 The character types


236 Section 2 More SQL skills cts you need them

In most cases, it makes sense to use the utf8mb4 character set. That way,
your database supports most characters in most languages as well as emojis.
Howeve1·, if you want to use the CHAR type and you only need to support
English and western European languages, you may want to use the latinl
character set to keep storage requirements to a minimum. In chapter 11 , you'll
learn how to change the character set for a database.
Although you typically store numeric values using numeric types, the
character types may be a better choice for some numeric values. For example,
you typically store zip codes, telephone numbers, and social security numbers
in character columns even if they contain only numbers. That's because their
values aren't used in numeric operations. In addition, if you store these numbers
in numeric colun111s, MySQL may strip leading zeros in some situations, which
isn't what you want.
In figure 8-2, the first five examples use single quotes to specify a string
literal. However, the sixth example t1ses double quotes to specify a string literal.
This allows the string literal to include a single quote, and it shows that you
can use single or double quotes for string literals. Although it's common to use
single quotes, double quotes are useful if you need to include a single quote in
the string.

The integer types


Figure 8-3 shows the integer types, which are numbers that don't include a
decim.al point. The integer data types differ in the amount of storage they use and
the range of values they can store. Since the INT type can store a wide range of
numbers and only requires 4 bytes of storage, it's the most commonly used of
the integer types.
By default, the integer types can store positive and negative numbers.
However, you can include the UNSIGNED attrib·ute for an integer type to
prevent negative values from being stored in the column. In that case, the range
of acceptable positive values for the column is doubled.
If the ZEROFILL attribute for the integer is set, the UNSIGNED attribute is
automatically set, and the integer is displayed with zeros padded from the left,
up to the maximt1m display size. For the INT type, for instance, the maximum
display size is 10 digits. If the default display size is too wide, you can specify a
smaller display size by coding it in parentheses after the data type. In this figure,
for instance, the last example specifies a display size of 4 digits. This only
affects how MySQL displays the value, not how it stores the value.
The INTEGER type is a synonym for the INT type. As a result, you can use
these types interchangeably. However, it's a common programming practice to
use INT as an abbreviation for INTEGER.
The BOOL and BOOLEAN types are synonyms for TINYINT(l). When you
work with these types, you can use a value of O to store false values and a value
of 1 to store true values. To make that more intuitive, you can use the FALSE
keyword, which is an alias for 0, and the TRUE keyword, which is an alias for 1.
Clzapter 8 How to work with data types 237

The integer types


Type Bytes Value ranges
BIGINT 8 Signed: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Unsigned: 0 to L8,446,744,073,709,55 1,615
INT 4 Signed: -2,147,483,648 to 2, 147,483,647
Unsigned: 0 to 4,294,967,295
MEDIUMINT 3 Signed: -8,388,608 5to 8,388,607
Unsigned: 0 and 16,777,215
SMALLINT 2 Signed: -32,768 and 32,767
Unsigned: 0 and 65,535
TINYINT l Signed: -128 and 127
Unsigned: 0 and 255

How the UNSIGNED and ZEROFILL attributes work


Data type Original value Value stored Value displayed
INT 99 99 99
INT -99 -99 -99
INT UNSIGNED 99 99 99
INT UNSIGNED -99 None None
INT ZEROFILL 99 99 0000000099
INT(4) ZEROFILL 99 99 0099

Description
• The integer types store numbers without any digits to the right of the decimal point.
• If the UNSIGNED attribute for the integer is set, it changes the range of acceptable
values. If you try to store a negative integer in a column with the UNSIGNED attri-
bute, an error occurs.
• If the ZEROFILL attribute for the integer is set, MySQL displays the integer with
zeros padded from the left, up to the maximum display size.
• If the ZEROFILL attribute is set, MySQL automatically sets the UNSIGNED
attribute.
• To specify a display size, you can code it in _parentheses after the data type. This
only affects how MySQL displays the value, not how it stores the value.
• The INTEGER type is a synonym for the INT type.
• The BOOL and BOOLEAN types are synonyms for TINYINT(l). You can use
these types to store TRUE and FALSE values, where 1 represents a true value and 0
represents a false value.

Figure 8-3 The integer types


238 Section 2 More SQL skills cts you need them

The fixed-point and floating-point types


Figure 8-4 presents the data types for storing real numbers, which are
numbers that have digits to the right of the decimal point. To start, you can use
the DECIMAL type to store.fixed-point numbers, which are numbers that have a
fixed number of digits to the right of the decimal point.
The number of digits a value has to the tight of the decimal point is called
its scale, and the total number of digits is called its precision. You can customize
the precision and scale of the DECIMAL type so they're right for the data to be
stored. For instance, if you need to store monetary values, it's common to use
two digits to the right of the decimal place as shown in the first three examples.
When you use the DECIMAL type, MySQL uses a varying number of bytes
to store the value. In general, it packs 9 digits into 4 bytes. However, it stores
the digits to the left and right of the decimal point separately, and it can use
fewer than 4 bytes if there are fewer than 9 digits. As a result, DECIMAL(9,
2) requires 5 bytes, while DECIMAL(18, 9) requires 8 bytes. For more details
about how this works, you can check the MySQL Reference Manual.
In contrast to the DECIMAL type, the DOUBLE and FLOAT types store
floating-point numbers. These data types provide for very large and very small
numbers, but with a limited number of significant digits. The FLOAT type can
be used to store a single-precision number, which provides for numbers with up
to 7 significant digits. And the DOUBLE type can be used to store a
double-precision number, which provides for numbers with up to 15 significant
digits.
To express the value of a floating-point number, you can use scientific
,iotation. To use this notation, you type the letter E followed by a power of 10.
For instance, 3.65E+9 is equal to 3.65 x 109 , or 3,650,000,000. Conversely,
3.65E-9 is equal to 3.65 x 10·9 , or 0.00000000365 . If you have a mathematical
background, of course, you 're already familiar with this notation.
Because the precision of the integer types and the DECIMAL type is exact,
these data types are considered exact numeric types. In contrast, the DOUBLE
and FLOAT types are considered approximate numeric types because they may
not represent a value exactly. That can happen, for example, when a number
is rounded to the appropriate number of significant digits. In this figure, for
instance, the last example shows that the FLOAT type rounds the original value
and only stores 7 significant digits. For business applications, you typically
use the exact numeric types, as there's seldom the need to work with the very
large and very small numbers that the floating-point data types are designed
for. However, for scientific applications, you n1ay sometimes 11eed to use the
DOUBLE and FLOAT types.
The DECIMAL, DOUBLE, and FLOAT types have numerous synonyms.
Sometimes these synonyms are helpful because they make it easier to work with
data from other databases. However, when working with a MySQL database,
most programmers use the DECIMAL, DOUBLE, and FLOAT types.
When you work with real numbers, you can use the UNSIGNED and
ZEROFILL attributes. These attributes work similarly to the way they do with
integer types.
Clzapter 8 How to work with data types 239

The fixed-point type


Type Bytes Description
DECIMAL(M, D) Vary Fixed-precision numbers where M specifies the maximum number
of total digits (the precision) and D specifies the nu1nber of digits
to the rigbl of the deci mal (the scale). M can range fro m l to 65. D
can range from Oto 30 but can ' t be larger than M. The default is 0.

The floating-point types


Type Bytes Description
DOUBLE 8 Double-precisio11 floating-point numbers from - l .7976xl0308 to l .7976xl 03°8 .
FLOAT 4 Single-precision floating-point numbers from -3.4028xl 0 38 to 3.4028xl038 .

How the fixed-point (exact) and floating-point (approximate) types work


Data type Original value Value stored Bytes used
DECIMAL(9,2 ) 1.2 1 . 20 5
DECIMAL(9,2) 1234567.89 1234567.89 5
DECIMAL(9,2) -1234567.89 -1234567.89 s
DECIMAL(18,9) 1234567.89 1234567.890000000 8
DOUBLE 1234567.89 1234567 . 89 8
FLOAT 1234567.89 1234570 4

Description
• Real numbers can include digits to the right of the decimal point. The precision of
a real n11mber indicates the total number of digits that can be stored, and the scale
indicates the number of digits that can be stored to the right of the decimal point.
• The DECIMAL type is considered an exact numeric type because its precision is
exact.
• The DOUBLE and FLOAT types store floating-point numbers, which have a
limited number of significant digits. These data types are considered approximate
numeric data types because they may not represent a val11e exactly.
• If the UNSIGNED attribute for a real number is set, it prevents storing negative
values in the column but does not affect the range of acceptable values.
• If the ZEROFILL attribute for a real number is set, the number is displayed with
zeros padded from the left, and the UNSIGNED attribute is automatically set.
• The DEC, NUMERIC, and FIXED types are synonyms for the DECIMAL type.
• The REAL and DOUBLE PRECISION types are synonyms for the DOUBLE type.

Figure 8-4 The fixed-point and floating-point types


240 Section 2 More SQL skills cts you need them

The date and time types


Part 1 of figure 8-5 presents the five date and time types supported by
MySQL. You can use the DATE type to store a date without a time. You can
use the TIME type to store a time without a date. And you can use either the
DATETIME or TIMESTAMP types to store both a date and a time.
You typically use the TIMESTAMP type to keep track of when a row was
inserted or last updated. For example, you might use this type to keep track
of the entries on a blog. MySQL makes that easy by automatically setting the
TIMESTAMP column to the current date and time whenever a row is inserted or
updated. If that's not what you want, you can use the DATETIME type instead.
The problem with the TIMESTAMP type is that it can only store dates up
to the year 2038. This is known as the yea,-2038 problem, the Y2K38 probleni,
and the Unix Millennium bug. As a result, if you want your database to be able
to store dates that go beyond 2038, you should use the DATETIME type instead
of the TIMESTAMP type. Otherwise, you can use the TIMESTAMP type since
it only reqtrires 4 bytes to store a TIMESTAMP value, compared to 8 bytes for a
DATETIME value.
If you need to store a year without any other temporal data, you can use the
YEAR type. With MySQL 5.7.5 and later, the YEAR type stores 4-digit years
from 1901 to 2155. Entries with one and two digits are still acceptable, though,
and are converted to 4-digit years as indicated in this figure. Note that, by
default, a numeric literal of O or 00 is converted to 0000. To store the value 2000
in a YEAR column, you must code it as a string.
Prior to MySQL 5.7 .5, the YEAR column could also store a 2-digit year.
To define a column like this, you coded the YEAR(2) type. Then, 2-digit entries
were stored as entered and 1-digit entries were converted to two digits.
Clzapter 8 How to work with data types 241

The date and time types


Type Bytes Description
DATE 3 Dates from January 1, 1000 through December 3 1, 9999. The
default format for display and e.ntry is "yyyy-m1n-dd" .
TIME 3 Times in the range -838:59:59 through 838:59:59. The default
format for display and entry is "hh:1nm:ss".
DATETIME 8 Combination date and time from midnight January l , 1970 to
December 31, 9999. The defaul t format for display and entry
is "yyyy-mm-dd hh:mm:ss".
TI MESTAMP 4 Combination date and time from midnight January 1, 1970 to
the year 2037. The default format is "yyyy-mm -dd hh:mm:ss".
YEAR[ ( 4 )] 1 Years in 4-digit format. Allowable values are from 1901 to
2155.

Description
• A column of TIMESTAMP type is auton1atically updated to the current date and
time when a row is inserted or updated. If a table bas multiple TIMESTAMP
columns, only the first one is updated automatically.
• The TIMESTAMP type can only store dates up to the year 2038. This is known
as the year 2038 problem, the Y2K38 problem, and the Unix Millenn.ium bug. To
fix this problem, use the DATETIME type instead of the TIMESTAMP type and
update the value manually as needed.
• MySQL 5.7 .5 and later support only 4-digit years, which can be defmed as YEAR
and YEAR(4). I-digit and 2-digit years can still be entered but are converted to
4-digit years. Values from Oto 69 are converted to 2000 to 2069, and values from
70 to 99 are converted to 1970 to 1999.
• For a value of O or 00 to be stored as 2000 in a YEAR column, you 1nust enter it as
a string. Otherwise, it's stored as 0000.

Figure 8-5 The date and time types (part 1 of 2)


242 Section 2 More SQL skills cts you need them

When you work with the date and time types, you need to know how to code
date and time literals. Part 2 of figure 8-5 shows how to do that. The default date
fo1mat for MySQL is ''yyyy-mm-dd'', which is why we've used this forn1at in
most of the examples in this book. By default, MySQL doesn 't support other
common date formats such as ''m.m/dd/yy''. If you attempt to use an unsupported
format, MySQL returns an error.
You also need to be aware of the two-digit year cutoff that's defined on your
system. When you code a two-digit year, the two-digit year cutoff determines
bow MySQL interprets the year. By default, MySQL interprets the years 00
through 69 as 2000 through 2069, and it interprets the years 70 through 99 as
1970 through 1999. Usually, that's what you want. However, the two-digit year
cutoff can be modified if necessary. In general, it's considered a good coding
practice to use four-digit years. That way, you can be sure that MySQL is
interpreting the year correctly.
MySQL interprets any punctuation character in a literal as a delimiter
between date parts or time parts. If you don't use any delimiters, you can code
the value as a numeric literal. In that case, you don't need to use single quotes.
When storing a date in a DATE column, the values are loosely checked for
valid data. For instance, months must be in the range 0-12 and days must be
in the range 0-31. For illegal dates, such as February 31, MySQL returns an
error. However, MySQL allows you to store unconventional date values, such as
''2018-12-00'', which represents a month and year without a specific day.
The default time format for MySQL is ''hh:mm: ss'', using a 24-hour clock.
Many of the same rules for coding date literals also apply to time literals. For
instance, you can use any punctuation character as a delimiter. Similarly, for
valid values, you can omit the delimiters. In that case, you can use a numeric
literal (no quotes) instead of a string literal (quotes). Finally, MySQL checks
times for validity. For illegal times, such as ''19:61:11'', MySQL returns an error.
The default date/time format for MySQL is a combination of the date and
time formats. Most of the rules for coding date/time literals ru·e a combination
of the rules for coding date and time literals. In addition, if you don't specify
a time when storing a TIMESTAMP or DATETIME value, the tim.e defaults to
00:00:00, which is midnight.
Clzapter 8 How to work with data types 243

How MySQL interprets literal date/time values


Literal value Value stored in DATE column
'2018-08-15' 2018-08-15
'2018-8-15' 2018-08-15
'18-8-15' 2018-08-15
'20180815' 2018-08-15
20180815 2018-08-15
'2018 . 08.15' 2018-08-15
'18/8/15' 2018-08-15
1
8/15/18 1 None
'2018-02-31' None
Literal value Value stored in TIME column
'7:32' 07:32:00
'19:32:11' 19:32:11
'193211' 19:32:11
193211 19:32:11
1
19:61:11 1 None
Literal value Value stored in DATETIME or TIMESTAMP column
'2018-08-15 19:32:11' 2018-08-15 19:32:11
'2018-08-15' 2018-08-15 00:00:00

Description
• You can specify date and time values by coding a literal value. In most cases, you
enclose the literal value in single quotes.
• For dates, MySQL uses the ''yyyy-mm-dd'' format. For times, MySQL uses the
''hh:mm:ss'' format, using a 24-hot1r clock.
• By default, MySQL does not support common date formats used by other systems
such as ''mm/dd/yy'' and ''mon/dd/yyyy''.
• By default, MySQL interprets 2-digit years from 00 to 69 as 2000 to 2069 and the
years from 70 to 99 as 1970 to 1999.
• MySQL interprets any punctuation character as a delimiter between date parts. If you
don't use any delimiters, you can code the value as a numeric literal without quotes.
• If you don' t specify a time when storiI1g a DATETIME or TIMESTAMP value,
MySQL stores a time value of 00:00:00 (12:00 midnight).
• If you don 't specify seconds when storing a TIME value, MySQL stores 00 for the
seconds.
• When storing date and time values, MySQL loosely checks the values to make sure they
are valid. For example, months must be in the range 0-12, days must be in the range
0-31, and so on. If MySQL determines that a date or time isn't valid, it returns an error.
• MySQL 5.5 and later are stricter than previous versions of MySQL for storing date
and time values. If MySQL can' t interpret a value, it returns an error or a warning.

Figure 8-5 The date and time types (part 2 of 2)


244 Section 2 More SQL skills cts you need them

The ENUM and SET types


The ENUM and SET types can be considered character data types since they
allow you to restrict the values for a column to a limited set of strings as shown
in figure 8-6. However, MySQL internally stores these values as integers, which
reduces the nun1ber of bytes needed to store each string.
The main difference between the ENUM and SET types is that an ENUM
column can store exactly one value, but a SET column can store zero, one, or
up to 64 different values. In other words, an ENUM column can consist of only
one member in a set of values, while the SET column may consist of any, or all,
members in a set.
You can use the ENUM type to store values that are mutually exclusive, such
as Yes, No, or Maybe. In other words, you can use the ENUM type to represent
a choice of one value, but not two. For example, delivery or pickup; cash, credit,
or debit; small, medium, or large; paper or plastic; soup or salad, although I
suppose you might want both soup and salad. For that, you could use a SET
column.
You can use a SET column when you want to choose more than one value.
For example, the toppings on a pizza, the software on a computer, or the features
of a car could be SET values.
The acceptable values for an ENUM or SET column are defined when the
table is created. An ENUM column can specify up to 65,535 acceptable values.
However, a SET column is limited to 64 values.
To store a value in an ENUM column, you code a single text string. If the
string is one of the acceptable values for the column, MySQL stores that value.
Otherwise, MySQL assigns an empty string to the col11mn.
When you add a row to a table that contains an ENUM column, MySQL
assigns a default value to that column if you don't explicitly specify a value. If
the column allows null values, MySQL assigns a null value to the col11mn. If
the column doesn ' t allow null values, MySQL assigns the first value in the set
of acceptable values. If you want MySQL to use a specific value as the default
value, then, you'll want to code that value as the first value in the set.
To store values in a SET coJumn, you code a single string with one or more
values separated by commas. Then, MySQL stores each acceptable value and
ignores any other values. Since commas are used to separate values, you can't
use commas within a value when you define the SET column.
When storing multiple values in a SET column, the order of the values
doesn' t matter. That's because MySQL stores the values in the same order as
in the column defmition. It also doesn't matter if you repeat a value because
MySQL doesn't store duplicate values.
Clzapter 8 How to work with data types 245

The ENUM and SET types


Type Bytes Description
ENUM 1-2 Stores one value selected from a list of acceptable val ues.
SET 1-8 Stores zero or more values selected from a list of accep table values.

How values are stored in ENUM columns


Stored in column
Value ENUM ('Yes', 'No', 'Maybe')
'Yes' 'Yes'
'No' 'No'
'Maybe' 'Maybe'
'Possibly' I I

How values are stored in SET columns


Stored in column
Value SET ( 'Pepperoni ', 'Mushrooms', 'Olives')
'Pepperoni• 'Pepperoni'
'Mushrooms' 'Mushrooms'
'Pepperoni, Bacon• 'Pepperoni'
'Olives, Pepperoni' 'Pepperoni, Olives'

Description
• The ENUM and SET types can be used to restrict the values that you store to a
li1nited set of values. Tl1e ENUM column can take on exactly one value, but a SET
colt1mn can take on zero, one, or up to 64 different values.
• You can defme the set of acceptable values for an ENUM or SET column when you
create a table. An ENUM column can have up to 65,535 acceptable values, but a
SET column is limited to 64 acceptable values.
• To specify a value for· an ENUM column, you code a single text string. If the string
contains an acceptable value, that value is stored in the column. Otherwise, the
column is assigned an empty string.
• If you don 't specify a value for an ENUM column when you insert a row, MySQL
assigns a default value that depends on whether the column allows null values. If
the column allows null values, MySQL assigns a null value to the column. If it
doesn't allow null values, MySQL assigns the first value in the set of acceptable
values to the column.
• To specify values for a SET column, you code a single string with the values
separated by commas. Each acceptable value is stored in the column, and any other
values are ignored.
• When you store values in a SET column, MySQL stores the values using the order
specified in the column definition, and it does not store duplicate values.

Figure 8-6 The ENUM and SET types


246 Section 2 More SQL skills cts you need them

The large object types


Figure 8-7 presents the large object (LOB) types. These data types are
designed to store large amounts of binary or character data.
The BLOB (binary large object) types store strings of binary data. This data
type is often used to store images, sounds, and video. However, the BLOB types
can be used to store any type of binary data, including the binary data that's
normally stored in application ftles such as PDF ftles or Word files.
The TEXT types work similarly to the BLOB types, but they store strings of
characters. As a result, in other database systems, they are sometimes referred
to as character large object (CLOE) types. These data types can be used to store
large amounts of character data including data that's normally stored in text,
XML, or JSON files.
To read and write data from a column defined with a BLOB or TEXT type,
you typically use another programming language such as Java or PHP. As a
result, we don't cover these types in this book. However, if you want to use these
types, you can learn more about how to do that by reading about them in the
MySQL Reference Manual.
Clzapter 8 How to work with data types 247

The large object types


Type Bytes Description
LONGBLOB L+4 Variable-length strings of binary data up to 4GB in len gth (L ).
MEDIUMBLOB L+3 Variable-length strings of binary data up to 16MB in length (L).
BLOB L+2 Variable-length strings of binary data up to 65KB in length (L).
TINYBLOB L+l Variable-length strings of binary data up to 255 bytes jn length (L ).

LONGTEXT L+4 Variable-length strings of characters up to 4GB in length (L).


MEDIUMTEXT L+3 Variable-length strings of characters up to 16MB in length (L).
TEXT L+2 Variable-length strings of characters up to 65KB in length (L).
TINYTEXT L+l Variable-length strings of characters up to 255 bytes in length (L).

Description
• The BLOB types store strings of binary data and are referred to as binary large
object (BLOB) types.
• The TEXT types store strings of character data and are sometimes referred to as
character large object (CLOE) types.

Figure 8-7 The large object types


248 Section 2 More SQL skills cts you need them

How to convert data


As you work with the various data types, you'll find that you frequently
need to convert data from one type to another. Although MySQL performs many
conversions automatically, it doesn't always perform the conversion the way you
want. Because of that, you need to be aware of how data conversion works, and
you need to know when and how to specify the type of conversion you want.

How implicit data conversion works


Before MySQL can operate on two values, it must convert those values to
the same data type. To understand how this works, consider the three expressions
shown in figu.r e 8-8.
In the first example, the second column joins a string literal of''$'' to the
invoice_total column, which is defined with the DECIMAL type. As a result,
MySQL converts the DECIMAL value to its corresponding characters, appends
those characters to the $ character, and stores them as a CHAR type.
In the second example, the second column divides the INT literal of 989319
by the VARCHAR type that's stored in the invoice_number column. As a result,
MySQL attempts to convert the invoice_number column to an INT type before
it perfor1ns the division operation. If the invoice_number column contains only
numbers, this works as you would expect. However, if the invoice_number
column contains letters or special characters, MySQL converts only the numeric
characters that precede the letters or special characters. For example, in the first
row in the result set, MySQL only converts the numbers before the dash in the
invoice- number column.
In the third example, the second column adds an INT literal of 1 to the
invoice_ date column, which is defined with the DATE type. As a result, MySQL
converts the DATE value in the invoice date column to an INT valt1e before it
performs the addition. In the result set, the first column uses the DATE type,
which includes dashes between the parts of the date. The second column, on the
other hand, uses the INT type, which doesn ' t include dashes between parts of the
date.
Notice in the third row of this result set that after 1 is added to the date,
the date is invalid. Because MySQL doesn't check if the resulting date is valid
when you perform an arithmetic operation like this, you're not likely to use the
arithmetic operators with dates. Instead, you'll use the functions for performing
calculations on dates that are presented in the next chapter.
When MySQL performs a conversion automatically, it's called an implicit
conversion. However, if you want to control how a conversion is performed,
you can code an explicit conversion. To do that, you can use the CAST and
CONVERT functions shown in the next figure.
Clzapter 8 How to work with data types 249

SELECT statements that implicitly convert data from one type to another
Number to string
SELECT invoice_ total, CONCAT{'$', invoice_ total)
FROM invoices
invoice_total CONCATCs', invoice_total)
- -
► 3813.33 53813.33
'10.20 s-10.20
I138.75 S138.75

String to number
SELECT invoice_r.n1mh,=ir, 989319 / invoice_ n11mher
FROM invoices
invoice_number 989 319/tnvoice _number
,..
► 989319-457 1
- L
263253241 0.0037580505988908225
1963253234 0.001027060138580 3393

Date to number
SELECT invoice_ date, invoice date+ 1
FROM invoices
.

-

invoice_date
2018-08-02
invoice_date
20180803
+1

2018-08-01 20180802
2018-07-31 20180732

Description
• When MySQL automatically converts one data type to another, it's known as an
implicit conversion.
• If you code an expression that involves values with different data types, MySQL
implicitly converts them when it evaluates the expression.
• If you use a string in a numeric expression, MySQL attempts to convert the string
to a nt1mber before evaluating the expression. If the string starts with a letter
or special character, MySQL returns a value of zero. If it starts with a number,
MySQL returns that number and each successive number until it encot1nters a letter
or special character.
• If you add or subtract an integer to or from a DATE value, MySQL implicitly
converts the DATE value to an integer value.

Figure 8-8 How implicit data conversion works


250 Section 2 More SQL skills cts you need them

How to convert data using the CAST


and CONVERT functions
Because MySQL's rules for implicit conversion are more flexible than those
for other SQL databases, you generally don't need to explicitly convert data
from one type to another. However, whenever necessary, you can use the CAST
and CONVERT functions to convert, or cast, an expression to the data type you
specify as shown in figure 8-9. Since CAST is an ANSI-standard function, it is
used more freqt1ently than CONVERT, but both functions work equally well for
most tasks.
The first SELECT statement shows how to use the CAST function. Here,
the fourth column in the result set casts the DATE values of the invoice date
colu1nn to CHAR values. Although the fourth column looks the same as the
second column, it stores a CHAR value, not a DATE value. In this case, MySQL
converted all of the characters in the DATE value to a CHAR value. If that's
not what you want, you can truncate the number of characters in the result by
specifying a value less than 10 after the CHAR keyword.
The fifth column in the 1·esult set casts the DECIMAL values in the
invoice_total column to signed INT values. Before the digits to the right of
the decimal point are dropped, the numbers are rounded to the nearest whole
number. For brevity, this statement only t1ses the SIGNED keyword. For clarity,
it could also include the optional INTEGER keyword immediately after the
SIGNED keyword.
The second SELECT statement in this figure shows how to use the
CONVERT function. If you compare this statement to the first SELECT state-
ment, you '11 see that it uses a slightly different syntax. However, both SELECT
statements accomplish the same task.
Clzapter 8 How to work with data types 251

The syntax of the CAST function


CAST(expression AS cast_ type)

The syntax of the CONVERT function


CONVERT(expression, cast_ type)

The cast types you can use in the CAST and CONVERT functions
Cast type Description
CHAR [ (N)] A string of characters where N is the maximu1n number of characters.
DATE A DATE value.
DATETIME A DATETIME value.
TIME A TIME value.
SIGNED [ INTEGER] A signed INT value. The INTEGER keyword is optional.
UNSIGNED [INTEGER] An unsigned INT value. The INTEGER keyword is optional.
DECIMAL [ (M [, D] ) l A DECIMAL value where M specifies the precision and D specifies
the scale.

A statement that uses the CAST function


SELECT invoice_ id, invoice_ date, invoice_ total,
CAST(invoice_ date AS CHAR(lO)) AS char_ date,
CAST(invoice_ total AS SIGNED) AS integer_ total
FROM invoices
invoice_id invoice_date invoice_total char_date integer_total
3813.33
► 1 2018-04-08 2018-04-08 3813
2018-04-10 410 .20 2018-04-10 410
I~ 2018-04-13 138. 75 2018-04-13 139

A statement that uses the CONVERT function


SELECT invoice_ id, invoice_ date, invoice_ total,
CONVERT(invoice- date, CHAR(lO)) AS char- date,
CONVERT(invoice_ total, SIGNED) AS integer_ total
FROM invoices
invoice_date n voice_total char_date integer_total
-
invoke id
-
► 1 2018-04-08 3813.33 2018-04-08 3813
2 2018-04-10 410.20 2018--04-10 410
13 2018-04-13 138. 75 2018--04-13 139
I

Description
• You can use the CAST or CONVERT function to perform an explicit conversion.
This allows you to convert, or cast, an expression from one data type to another.
• CAST is an ANSI-standard function and is used more frequently than CONVERT.

Figure 8-9 How to convert data using the CAST and CONVERT functions
252 Section 2 More SQL skills cts you need them

How to convert data using the FORMAT


and CHAR functions
In addition to the CAST and CONVERT functions, MySQL provides some
functions that perform other types of data conversion. In particular, it provides
the FORMAT and CHAR functions shown in figure 8-10.
You can use the FORMAT function to convert a number to a string of
characters. This function uses commas to group the thousands to the left of
the decimal point. This makes large numbers easier to read. In addition, the
FORMAT function rounds the number to the specified number of decimal
places. If you specify O decimal places, the function returns a string that doesn't
include a decimal point.
The CHAR function returns a binary string for each specified integer.
This function is typically used to output ASCII (American Standard Code
for Information Interchange) conu·ol characters that can't be typed on your
keyboard. The three most common control characters are presented in this figure.
These characters can be used to format output so it's easy to read. In this figure,
for example, the SELECT statement uses the CHAR(l3) and CHAR(l O) control
characters to start new lines after the vendor name and vendor address in the
output.
Clzapter 8 How to work with data types 253

The FORMAT and CHAR functions


Function Description
FORMAT(number,decimal) Converts the specified number to a character suing
w.ith grouped digits separated by co1nmas, rounded to
the specified number of decimal digits. If deciinal is
zero, then the decimal point is omitted.
CHAR{valuel[,value2] ... ) Converts one or 1nore numbers to a binary string. Each
number is interpreted as an integer between Oand 255.

The FORMAT function


Function Result
FORMAT(1234567.8901,2) 1,234,567.89
FORMAT{l234.56,4) 1,234.5600
FORMAT(1234.56,0) 1,235

The CHAR function for common control characters


Function Control character
CHAR(9) Tab
CHAR(lO) Line feed
CHAR(13) Caniage return

A statement that uses the CHAR function to format output


SELECT CONCAT(vendor_ name, CHAR(13,10), vendor_ addressl, CHAR(13,10),
vendor_ city, ', ', vendor_ state, ' ', vendor_ zip_ code)
FROM vendors
WHERE vendor id= 1

us Postal Service
Attn: Supt. Window Services
Madison, WI 53707

Description
• The CHAR function is typically used to insert control characters into a character
string.

Figure 8-10 How to convert data using the FORMAT and CHAR functions
254 Section 2 More SQL skills cts you need them

Perspective
In this chapter, you learned about the different MySQL data types. In
addition, you learned how to use some functions to convert data from one type
to another. In the next chapter, you'll learn some of the additional functions for
working with data.

Terms
data type latin I character set
character data types integer types
string fixed-point number
text scale
• •
numeric data types prec1s1on
integer floating-point number
real number significant digits
date and time data types single-precision number
date/time data types double-precision number
temporal data types scientific notation
large object (LOB) data types exact numeric types
spatial data types approximate numeric types
global positioning system (GPS) year 203 8 problem
geometry types Y2K38 problem
JSON data type Unix Millennium bug
JavaScript Object Notation (JSON) BLOB (Binary Large Object)
fixed-length string character large object (CLOB)
variable-length string implicit conversion
utf8mb4 character set explicit conversion
multiple-byte character set cast
Unicode standard ASCII (American Standard
utf8mb3 character set Code for Infor1nation
single-byte character set Interchange)
Clzapter 8 How to work with data types 255

Exercises
1. Write a SELECT statement that returns these columns from the Invoices
table:
The invoice- total column
A column that t1ses the FORMAT function to return the invoice total
column with 1 digit to the right of the decimal point
A column that uses the CONVERT function to return the invoice total
column as an integer
A column that uses the CAST function to return the invoice total column
as an integer
2. Write a SELECT statement that returns these columns from the Invoices
table:
The invoice- date column
A column that uses the CAST function to return the invoice_date column
with its full date and time
A column that uses the CAST function to return the invoice- date column
with just the year and the month

You might also like