01.Murachs MySQL 2019 Chapter 08
01.Murachs MySQL 2019 Chapter 08
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.
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 .
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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
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