Docsity

A Complete Guide to MySQL-tutorial, Slides of Computer Science

Partial preview of the text

Download A Complete Guide to MySQL-tutorial and more Slides Computer Science in PDF only on Docsity!

MySQL Tutorial

Mr Oddo

Table of Contents

  • 1 Tutorial Preface and Legal Notices v
  • 2 Connecting to and Disconnecting from the Server
  • 3 Entering Queries
  • 4 Creating and Using a Database
    • 4.1 Creating and Selecting a Database
    • 4.2 Creating a Table
    • 4.3 Loading Data into a Table
    • 4.4 Retrieving Information from a Table
      • 4.4.1 Selecting All Data
      • 4.4.2 Selecting Particular Rows
      • 4.4.3 Selecting Particular Columns
      • 4.4.4 Sorting Rows
      • 4.4.5 Date Calculations
      • 4.4.6 Working with NULL Values
      • 4.4.7 Pattern Matching
      • 4.4.8 Counting Rows
      • 4.4.9 Using More Than one Table
  • 5 Getting Information About Databases and Tables
  • 6 Using mysql in Batch Mode
  • 7 Examples of Common Queries
    • 7.1 The Maximum Value for a Column
    • 7.2 The Row Holding the Maximum of a Certain Column
    • 7.3 Maximum of Column per Group
    • 7.4 The Rows Holding the Group-wise Maximum of a Certain Column
    • 7.5 Using User-Defined Variables
    • 7.6 Using Foreign Keys
    • 7.7 Searching on Two Keys
    • 7.8 Calculating Visits Per Day
    • 7.9 Using AUTO_INCREMENT
  • 8 Using MySQL with Apache

Documentation Accessibility

The terms governing the U.S. Government's use of Oracle cloud services are defined by the applicable

contract for such services. No other rights are granted to the U.S. Government.

This software or hardware is developed for general use in a variety of information management

applications. It is not developed or intended for use in any inherently dangerous applications, including

applications that may create a risk of personal injury. If you use this software or hardware in dangerous

applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other

measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages

caused by use of this software or hardware in dangerous applications.

Oracle, Java, and MySQL are registered trademarks of Oracle and/or its affiliates. Other names may be

trademarks of their respective owners.

Intel and Intel Inside are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks

are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD,

Epyc, and the AMD logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a

registered trademark of The Open Group.

This software or hardware and documentation may provide access to or information about content,

products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and

expressly disclaim all warranties of any kind with respect to third-party content, products, and services

unless otherwise set forth in an applicable agreement between you and Oracle. Oracle Corporation and its

affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of

third-party content, products, or services, except as set forth in an applicable agreement between you and

Oracle.

This documentation is NOT distributed under a GPL license. Use of this documentation is subject to the

following terms:

You may create a printed copy of this documentation solely for your own personal use. Conversion to other

formats is allowed as long as the actual content is not altered or edited in any way. You shall not publish

or distribute this documentation in any form or on any media, except if you distribute the documentation in

a manner similar to how Oracle disseminates it (that is, electronically for download on a Web site with the

software) or on a CD-ROM or similar medium, provided however that the documentation is disseminated

together with the software on the same medium. Any other use, such as any dissemination of printed

copies or use of this documentation, in whole or in part, in another publication, requires the prior written

consent from an authorized representative of Oracle. Oracle and/or its affiliates reserve any and all rights

to this documentation not expressly granted above.

Documentation Accessibility

For information about Oracle's commitment to accessibility, visit the Oracle Accessibility Program website

at

https://www.oracle.com/corporate/accessibility/.

Access to Oracle Support for Accessibility

Oracle customers that have purchased support have access to electronic support through My Oracle

Support. For information, visit

https://www.oracle.com/corporate/accessibility/learning-support.html#support-tab.

vi

Chapter 1 Tutorial

This chapter provides a tutorial introduction to MySQL by showing how to use the mysql client program

to create and use a simple database. mysql (sometimes referred to as the “terminal monitor” or just

“monitor”) is an interactive program that enables you to connect to a MySQL server, run queries, and view

the results. mysql may also be used in batch mode: you place your queries in a file beforehand, then tell

mysql to execute the contents of the file. Both ways of using mysql are covered here.

To see a list of options provided by mysql, invoke it with the --help option:

$> mysql --help

This chapter assumes that mysql is installed on your machine and that a MySQL server is available to

which you can connect. If this is not true, contact your MySQL administrator. (If you are the administrator,

you need to consult the relevant portions of this manual, such as MySQL Server Administration.)

This chapter describes the entire process of setting up and using a database. If you are interested only

in accessing an existing database, you may want to skip the sections that describe how to create the

database and the tables it contains.

Because this chapter is tutorial in nature, many details are necessarily omitted. Consult the relevant

sections of the manual for more information on the topics covered here.

Chapter 3 Entering Queries

Make sure that you are connected to the server, as discussed in the previous section. Doing so does not in

itself select any database to work with, but that is okay. At this point, it is more important to find out a little

about how to issue queries than to jump right in creating tables, loading data into them, and retrieving data

from them. This section describes the basic principles of entering queries, using several queries you can

try out to familiarize yourself with how mysql works.

Here is a simple query that asks the server to tell you its version number and the current date. Type it in as

shown here following the mysql> prompt and press Enter:

mysql> SELECT VERSION(), CURRENT_DATE; +--------------+--------------+ | VERSION() | CURRENT_DATE | +--------------+--------------+ | 5.7.1-m4-log | 2012-12-25 | +--------------+--------------+ 1 row in set (0.01 sec) mysql>

This query illustrates several things about mysql:

  • A query normally consists of an SQL statement followed by a semicolon. (There are some exceptions

where a semicolon may be omitted. QUIT, mentioned earlier, is one of them. We'll get to others later.)

  • When you issue a query, mysql sends it to the server for execution and displays the results, then prints

another mysql> prompt to indicate that it is ready for another query.

  • mysql displays query output in tabular form (rows and columns). The first row contains labels for

the columns. The rows following are the query results. Normally, column labels are the names of the

columns you fetch from database tables. If you're retrieving the value of an expression rather than a

table column (as in the example just shown), mysql labels the column using the expression itself.

  • mysql shows how many rows were returned and how long the query took to execute, which gives you

a rough idea of server performance. These values are imprecise because they represent wall clock time

(not CPU or machine time), and because they are affected by factors such as server load and network

latency. (For brevity, the “rows in set” line is sometimes not shown in the remaining examples in this

chapter.)

Keywords may be entered in any lettercase. The following queries are equivalent:

mysql> SELECT VERSION(), CURRENT_DATE; mysql> select version(), current_date; mysql> SeLeCt vErSiOn(), current_DATE;

Here is another query. It demonstrates that you can use mysql as a simple calculator:

mysql> SELECT SIN(PI()/4), (4+1)5;* +------------------+---------+ | SIN(PI()/4) | (4+1)*5 | +------------------+---------+ | 0.70710678118655 | 25 | +------------------+---------+ 1 row in set (0.02 sec)

The queries shown thus far have been relatively short, single-line statements. You can even enter multiple

statements on a single line. Just end each one with a semicolon:

mysql> SELECT VERSION(); SELECT NOW(); +------------------+ | VERSION() |

| 5.7.10-ndb-7.5.1 | +------------------+ 1 row in set (0.00 sec) +---------------------+ | NOW() | +---------------------+ | 2016-01-29 18:02:55 | +---------------------+ 1 row in set (0.00 sec)

A query need not be given all on a single line, so lengthy queries that require several lines are not a

problem. mysql determines where your statement ends by looking for the terminating semicolon, not by

looking for the end of the input line. (In other words, mysql accepts free-format input: it collects input lines

but does not execute them until it sees the semicolon.)

Here is a simple multiple-line statement:

mysql> SELECT -> USER() -> , -> CURRENT_DATE; +---------------+--------------+ | USER() | CURRENT_DATE | +---------------+--------------+ | jon@localhost | 2010-08-06 | +---------------+--------------+

In this example, notice how the prompt changes from mysql> to -> after you enter the first line of a

multiple-line query. This is how mysql indicates that it has not yet seen a complete statement and is

waiting for the rest. The prompt is your friend, because it provides valuable feedback. If you use that

feedback, you can always be aware of what mysql is waiting for.

If you decide you do not want to execute a query that you are in the process of entering, cancel it by typing

\c:

mysql> SELECT -> USER() -> \c mysql>

Here, too, notice the prompt. It switches back to mysql> after you type \c, providing feedback to indicate

that mysql is ready for a new query.

The following table shows each of the prompts you may see and summarizes what they mean about the

state that mysql is in.

Prompt Meaning

mysql> Ready for new query

-> Waiting for next line of multiple-line query

'> Waiting for next line, waiting for completion of a

string that began with a single quote (')

"> Waiting for next line, waiting for completion of a

string that began with a double quote (")

`> Waiting for next line, waiting for completion of an

identifier that began with a backtick (`)

/*> Waiting for next line, waiting for completion of a

comment that began with /*

Chapter 4 Creating and Using a Database

Table of Contents

4.1 Creating and Selecting a Database ............................................................................................. 10

4.2 Creating a Table ........................................................................................................................ 11

4.3 Loading Data into a Table .......................................................................................................... 12

4.4 Retrieving Information from a Table ............................................................................................. 13

4.4.1 Selecting All Data ............................................................................................................ 13

4.4.2 Selecting Particular Rows ................................................................................................. 14

4.4.3 Selecting Particular Columns ............................................................................................ 15

4.4.4 Sorting Rows ................................................................................................................... 16

4.4.5 Date Calculations ............................................................................................................. 17

4.4.6 Working with NULL Values ............................................................................................... 20

4.4.7 Pattern Matching .............................................................................................................. 21

4.4.8 Counting Rows ................................................................................................................ 23

4.4.9 Using More Than one Table ............................................................................................. 25

Once you know how to enter SQL statements, you are ready to access a database.

Suppose that you have several pets in your home (your menagerie) and you would like to keep track of

various types of information about them. You can do so by creating tables to hold your data and loading

them with the desired information. Then you can answer different sorts of questions about your animals by

retrieving data from the tables. This section shows you how to perform the following operations:

  • Create a database
  • Create a table
  • Load data into the table
  • Retrieve data from the table in various ways
  • Use multiple tables

The menagerie database is simple (deliberately), but it is not difficult to think of real-world situations

in which a similar type of database might be used. For example, a database like this could be used by

a farmer to keep track of livestock, or by a veterinarian to keep track of patient records. A menagerie

distribution containing some of the queries and sample data used in the following sections can be

obtained from the MySQL website. It is available in both compressed tar file and Zip formats at https://

dev.mysql.com/doc/.

Use the SHOW statement to find out what databases currently exist on the server:

mysql> SHOW DATABASES; +----------+ | Database | +----------+ | mysql | | test | | tmp | +----------+

The mysql database describes user access privileges. The test database often is available as a

workspace for users to try things out.

Creating and Selecting a Database

The list of databases displayed by the statement may be different on your machine; SHOW DATABASES

does not show databases that you have no privileges for if you do not have the SHOW DATABASES

privilege. See SHOW DATABASES Statement.

If the test database exists, try to access it:

mysql> USE test Database changed

USE, like QUIT, does not require a semicolon. (You can terminate such statements with a semicolon if you

like; it does no harm.) The USE statement is special in another way, too: it must be given on a single line.

You can use the test database (if you have access to it) for the examples that follow, but anything you

create in that database can be removed by anyone else with access to it. For this reason, you should

probably ask your MySQL administrator for permission to use a database of your own. Suppose that you

want to call yours menagerie. The administrator needs to execute a statement like this:

mysql> GRANT ALL ON menagerie. TO 'your_mysql_name'@'your_client_host';*

where your_mysql_name is the MySQL user name assigned to you and your_client_host is the host

from which you connect to the server.

4.1 Creating and Selecting a Database

If the administrator creates your database for you when setting up your permissions, you can begin using

it. Otherwise, you need to create it yourself:

mysql> CREATE DATABASE menagerie;

Under Unix, database names are case-sensitive (unlike SQL keywords), so you must always refer to

your database as menagerie, not as Menagerie, MENAGERIE, or some other variant. This is also true

for table names. (Under Windows, this restriction does not apply, although you must refer to databases

and tables using the same lettercase throughout a given query. However, for a variety of reasons, the

recommended best practice is always to use the same lettercase that was used when the database was

created.)

Note

If you get an error such as ERROR 1044 (42000): Access denied for user

'micah'@'localhost' to database 'menagerie' when attempting to

create a database, this means that your user account does not have the necessary

privileges to do so. Discuss this with the administrator or see Access Control and

Account Management.

Creating a database does not select it for use; you must do that explicitly. To make menagerie the current

database, use this statement:

mysql> USE menagerie Database changed

Your database needs to be created only once, but you must select it for use each time you begin a mysql

session. You can do this by issuing a USE statement as shown in the example. Alternatively, you can select

the database on the command line when you invoke mysql. Just specify its name after any connection

parameters that you might need to provide. For example:

$> mysql -h host -u user -p menagerie Enter password: ************

Loading Data into a Table

The use of the DATE data type for the birth and death columns is a fairly obvious choice.

Once you have created a table, SHOW TABLES should produce some output:

mysql> SHOW TABLES; +---------------------+ | Tables in menagerie | +---------------------+ | pet | +---------------------+

To verify that your table was created the way you expected, use a DESCRIBE statement:

mysql> DESCRIBE pet; +---------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+---------+-------+ | name | varchar(20) | YES | | NULL | | | owner | varchar(20) | YES | | NULL | | | species | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | birth | date | YES | | NULL | | | death | date | YES | | NULL | | +---------+-------------+------+-----+---------+-------+

You can use DESCRIBE any time, for example, if you forget the names of the columns in your table or what

types they have.

For more information about MySQL data types, see Data Types.

4.3 Loading Data into a Table

After creating your table, you need to populate it. The LOAD DATA and INSERT statements are useful for

this.

Suppose that your pet records can be described as shown here. (Observe that MySQL expects dates in

' YYYY-MM-DD ' format; this may differ from what you are used to.)

name owner species sex birth death

Fluffy Harold cat f 1993-02-

Claws Gwen cat m 1994-03-

Buffy Harold dog f 1989-05-

Fang Benny dog m 1990-08-

Bowser Diane dog m 1979-08-31 1995-07-

Chirpy Gwen bird f 1998-09-

Whistler Gwen bird 1997-12-

Slim Benny snake m 1996-04-

Because you are beginning with an empty table, an easy way to populate it is to create a text file

containing a row for each of your animals, then load the contents of the file into the table with a single

statement.

You could create a text file pet.txt containing one record per line, with values separated by tabs, and

given in the order in which the columns were listed in the CREATE TABLE statement. For missing values

(such as unknown sexes or death dates for animals that are still living), you can use NULL values. To

Retrieving Information from a Table

represent these in your text file, use \N (backslash, capital-N). For example, the record for Whistler the bird

would look like this (where the whitespace between values is a single tab character):

Whistler Gwen bird \N 1997-12-09 \N

To load the text file pet.txt into the pet table, use this statement:

mysql> LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;

If you created the file on Windows with an editor that uses \r\n as a line terminator, you should use this

statement instead:

mysql> LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet LINES TERMINATED BY '\r\n';

(On an Apple machine running macOS, you would likely want to use LINES TERMINATED BY '\r'.)

You can specify the column value separator and end of line marker explicitly in the LOAD DATA statement

if you wish, but the defaults are tab and linefeed. These are sufficient for the statement to read the file

pet.txt properly.

If the statement fails, it is likely that your MySQL installation does not have local file capability enabled by

default. See Security Considerations for LOAD DATA LOCAL, for information on how to change this.

When you want to add new records one at a time, the INSERT statement is useful. In its simplest form,

you supply values for each column, in the order in which the columns were listed in the CREATE TABLE

statement. Suppose that Diane gets a new hamster named “Puffball.” You could add a new record using

an INSERT statement like this:

mysql> INSERT INTO pet VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);

String and date values are specified as quoted strings here. Also, with INSERT, you can insert NULL

directly to represent a missing value. You do not use \N like you do with LOAD DATA.

From this example, you should be able to see that there would be a lot more typing involved to load your

records initially using several INSERT statements rather than a single LOAD DATA statement.

4.4 Retrieving Information from a Table

The SELECT statement is used to pull information from a table. The general form of the statement is:

SELECT what_to_select FROM which_table WHERE conditions_to_satisfy ;

what_to_select indicates what you want to see. This can be a list of columns, or * to indicate “all

columns.” which_table indicates the table from which you want to retrieve data. The WHERE clause

is optional. If it is present, conditions_to_satisfy specifies one or more conditions that rows must

satisfy to qualify for retrieval.

4.4.1 Selecting All Data

The simplest form of SELECT retrieves everything from a table:

mysql> SELECT * FROM pet; +----------+--------+---------+------+------------+------------+ | name | owner | species | sex | birth | death |

Selecting Particular Columns

| name | owner | species | sex | birth | death | +----------+-------+---------+------+------------+-------+ | Chirpy | Gwen | bird | f | 1998-09-11 | NULL | | Puffball | Diane | hamster | f | 1999-03-30 | NULL | +----------+-------+---------+------+------------+-------+

You can combine conditions, for example, to locate female dogs:

mysql> SELECT * FROM pet WHERE species = 'dog' AND sex = 'f'; +-------+--------+---------+------+------------+-------+ | name | owner | species | sex | birth | death | +-------+--------+---------+------+------------+-------+ | Buffy | Harold | dog | f | 1989-05-13 | NULL | +-------+--------+---------+------+------------+-------+

The preceding query uses the AND logical operator. There is also an OR operator:

mysql> SELECT * FROM pet WHERE species = 'snake' OR species = 'bird'; +----------+-------+---------+------+------------+-------+ | name | owner | species | sex | birth | death | +----------+-------+---------+------+------------+-------+ | Chirpy | Gwen | bird | f | 1998-09-11 | NULL | | Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | | Slim | Benny | snake | m | 1996-04-29 | NULL | +----------+-------+---------+------+------------+-------+

AND and OR may be intermixed, although AND has higher precedence than OR. If you use both operators, it

is a good idea to use parentheses to indicate explicitly how conditions should be grouped:

mysql> SELECT * FROM pet WHERE (species = 'cat' AND sex = 'm') OR (species = 'dog' AND sex = 'f'); +-------+--------+---------+------+------------+-------+ | name | owner | species | sex | birth | death | +-------+--------+---------+------+------------+-------+ | Claws | Gwen | cat | m | 1994-03-17 | NULL | | Buffy | Harold | dog | f | 1989-05-13 | NULL | +-------+--------+---------+------+------------+-------+

4.4.3 Selecting Particular Columns

If you do not want to see entire rows from your table, just name the columns in which you are interested,

separated by commas. For example, if you want to know when your animals were born, select the name

and birth columns:

mysql> SELECT name, birth FROM pet; +----------+------------+ | name | birth | +----------+------------+ | Fluffy | 1993-02-04 | | Claws | 1994-03-17 | | Buffy | 1989-05-13 | | Fang | 1990-08-27 | | Bowser | 1989-08-31 | | Chirpy | 1998-09-11 | | Whistler | 1997-12-09 | | Slim | 1996-04-29 | | Puffball | 1999-03-30 | +----------+------------+

To find out who owns pets, use this query:

mysql> SELECT owner FROM pet; +--------+ | owner |

Sorting Rows

| Harold | | Gwen | | Harold | | Benny | | Diane | | Gwen | | Gwen | | Benny | | Diane | +--------+

Notice that the query simply retrieves the owner column from each record, and some of them appear more

than once. To minimize the output, retrieve each unique output record just once by adding the keyword

DISTINCT:

mysql> SELECT DISTINCT owner FROM pet; +--------+ | owner | +--------+ | Benny | | Diane | | Gwen | | Harold | +--------+

You can use a WHERE clause to combine row selection with column selection. For example, to get birth

dates for dogs and cats only, use this query:

mysql> SELECT name, species, birth FROM pet WHERE species = 'dog' OR species = 'cat'; +--------+---------+------------+ | name | species | birth | +--------+---------+------------+ | Fluffy | cat | 1993-02-04 | | Claws | cat | 1994-03-17 | | Buffy | dog | 1989-05-13 | | Fang | dog | 1990-08-27 | | Bowser | dog | 1989-08-31 | +--------+---------+------------+

4.4.4 Sorting Rows

You may have noticed in the preceding examples that the result rows are displayed in no particular order. It

is often easier to examine query output when the rows are sorted in some meaningful way. To sort a result,

use an ORDER BY clause.

Here are animal birthdays, sorted by date:

mysql> SELECT name, birth FROM pet ORDER BY birth; +----------+------------+ | name | birth | +----------+------------+ | Buffy | 1989-05-13 | | Bowser | 1989-08-31 | | Fang | 1990-08-27 | | Fluffy | 1993-02-04 | | Claws | 1994-03-17 | | Slim | 1996-04-29 | | Whistler | 1997-12-09 | | Chirpy | 1998-09-11 | | Puffball | 1999-03-30 | +----------+------------+

Date Calculations

| Claws | 1994-03-17 | 2003-08-19 | 9 | | Buffy | 1989-05-13 | 2003-08-19 | 14 | | Fang | 1990-08-27 | 2003-08-19 | 12 | | Bowser | 1989-08-31 | 2003-08-19 | 13 | | Chirpy | 1998-09-11 | 2003-08-19 | 4 | | Whistler | 1997-12-09 | 2003-08-19 | 5 | | Slim | 1996-04-29 | 2003-08-19 | 7 | | Puffball | 1999-03-30 | 2003-08-19 | 4 | +----------+------------+------------+------+

The query works, but the result could be scanned more easily if the rows were presented in some order.

This can be done by adding an ORDER BY name clause to sort the output by name:

mysql> SELECT name, birth, CURDATE(), TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age FROM pet ORDER BY name; +----------+------------+------------+------+ | name | birth | CURDATE() | age | +----------+------------+------------+------+ | Bowser | 1989-08-31 | 2003-08-19 | 13 | | Buffy | 1989-05-13 | 2003-08-19 | 14 | | Chirpy | 1998-09-11 | 2003-08-19 | 4 | | Claws | 1994-03-17 | 2003-08-19 | 9 | | Fang | 1990-08-27 | 2003-08-19 | 12 | | Fluffy | 1993-02-04 | 2003-08-19 | 10 | | Puffball | 1999-03-30 | 2003-08-19 | 4 | | Slim | 1996-04-29 | 2003-08-19 | 7 | | Whistler | 1997-12-09 | 2003-08-19 | 5 | +----------+------------+------------+------+

To sort the output by age rather than name, just use a different ORDER BY clause:

mysql> SELECT name, birth, CURDATE(), TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age FROM pet ORDER BY age; +----------+------------+------------+------+ | name | birth | CURDATE() | age | +----------+------------+------------+------+ | Chirpy | 1998-09-11 | 2003-08-19 | 4 | | Puffball | 1999-03-30 | 2003-08-19 | 4 | | Whistler | 1997-12-09 | 2003-08-19 | 5 | | Slim | 1996-04-29 | 2003-08-19 | 7 | | Claws | 1994-03-17 | 2003-08-19 | 9 | | Fluffy | 1993-02-04 | 2003-08-19 | 10 | | Fang | 1990-08-27 | 2003-08-19 | 12 | | Bowser | 1989-08-31 | 2003-08-19 | 13 | | Buffy | 1989-05-13 | 2003-08-19 | 14 | +----------+------------+------------+------+

A similar query can be used to determine age at death for animals that have died. You determine which

animals these are by checking whether the death value is NULL. Then, for those with non-NULL values,

compute the difference between the death and birth values:

mysql> SELECT name, birth, death, TIMESTAMPDIFF(YEAR,birth,death) AS age FROM pet WHERE death IS NOT NULL ORDER BY age; +--------+------------+------------+------+ | name | birth | death | age | +--------+------------+------------+------+ | Bowser | 1989-08-31 | 1995-07-29 | 5 | +--------+------------+------------+------+

The query uses death IS NOT NULL rather than death <> NULL because NULL is a special value

that cannot be compared using the usual comparison operators. This is discussed later. See Section 4.4.6,

“Working with NULL Values”.

Date Calculations

What if you want to know which animals have birthdays next month? For this type of calculation, year

and day are irrelevant; you simply want to extract the month part of the birth column. MySQL provides

several functions for extracting parts of dates, such as YEAR(), MONTH(), and DAYOFMONTH(). MONTH()

is the appropriate function here. To see how it works, run a simple query that displays the value of both

birth and MONTH(birth):

mysql> SELECT name, birth, MONTH(birth) FROM pet; +----------+------------+--------------+ | name | birth | MONTH(birth) | +----------+------------+--------------+ | Fluffy | 1993-02-04 | 2 | | Claws | 1994-03-17 | 3 | | Buffy | 1989-05-13 | 5 | | Fang | 1990-08-27 | 8 | | Bowser | 1989-08-31 | 8 | | Chirpy | 1998-09-11 | 9 | | Whistler | 1997-12-09 | 12 | | Slim | 1996-04-29 | 4 | | Puffball | 1999-03-30 | 3 | +----------+------------+--------------+

Finding animals with birthdays in the upcoming month is also simple. Suppose that the current month is

April. Then the month value is 4 and you can look for animals born in May (month 5 ) like this:

mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = 5; +-------+------------+ | name | birth | +-------+------------+ | Buffy | 1989-05-13 | +-------+------------+

There is a small complication if the current month is December. You cannot merely add one to the month

number ( 12 ) and look for animals born in month 13 , because there is no such month. Instead, you look for

animals born in January (month 1 ).

You can write the query so that it works no matter what the current month is, so that you do not have to

use the number for a particular month. DATE_ADD() enables you to add a time interval to a given date.

If you add a month to the value of CURDATE(), then extract the month part with MONTH(), the result

produces the month in which to look for birthdays:

mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = MONTH(DATE_ADD(CURDATE(),INTERVAL 1 MONTH));

A different way to accomplish the same task is to add 1 to get the next month after the current one after

using the modulo function (MOD) to wrap the month value to 0 if it is currently 12 :

mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = MOD(MONTH(CURDATE()), 12) + 1;

MONTH() returns a number between 1 and 12. And MOD(something,12) returns a number between 0

and 11. So the addition has to be after the MOD(), otherwise we would go from November ( 11 ) to January

If a calculation uses invalid dates, the calculation fails and produces warnings:

mysql> SELECT '2018-10-31' + INTERVAL 1 DAY; +-------------------------------+ | '2018-10-31' + INTERVAL 1 DAY | +-------------------------------+ | 2018-11-01 | +-------------------------------+ mysql> SELECT '2018-10-32' + INTERVAL 1 DAY; +-------------------------------+