Вы находитесь на странице: 1из 45

CREATING DATABASES,

TABLES, AND INDEXES


Creating Databases, Tables, and
2
Indexes
 In this chapter you'll learn how to create all the
basic MySQL structures: databases, tables, and
indexes. We'll cover the following:
 Creating a database
 Selecting a database
 Creating tables
 Column and data types in MySQL
 Creating indexes
 Deleting tables, indexes, and databases
 Altering existing table structures
Case Sensitivity
3

 SQL keywords are not case sensitive.


 This is standard across database systems.
 Case sensitivity for identifiers depends on the database
system you are using. In MySQL, whether database and
table names are case sensitive depends on your operating
system. The reason for this is that generally each
database will have an underlying directory in your
operating system, and each table will have an underlying
file. These directory names and filenames follow different
rules depending on the operating system.
Identifiers in MySQL
4

 An identifier is simply the name of an alias, a


database, a table, a column, or an index. It is how
you uniquely identify that object.
 Before you can begin creating your own databases
and tables, we should discuss what identifiers are
valid in MySQL.
Identifiers in MySQL
5

 Generally speaking, identifiers can contain any


characters, with these exceptions:
 Database names can contain any characters that are
allowed in a directory name, but not the characters that
have special meaning in a directory name (/, \, and .)
for obvious reasons.
 Table names can contain any characters that are
allowed in filenames, except for . and /.
 All identifiers except aliases can be up to 64
characters long. Alias names can be up to 255
characters long.
Creating a Database
6

 After design, the first step in creating a database is,


logically enough, to tell MySQL that we want to create
a new database. We do this with the CREATE
DATABASE SQL statement, as follows:
create database employee;
 You can check to see that this statement worked by
executing the command
show databases;
 You should now see the employee database listed
among the databases in the system.
 We now have an empty database, waiting for some
tables to be created.
Selecting a Database
7

 Before we can create any tables or do anything


else with the employee database, we need to tell
MySQL that we want to work with our new
database.
 We do this with the use statement, as follows:
use employee;
 The employee database is now selected, and all
actions we take from now on will be applied to this
database by default.
Creating Tables
8

 To create the tables in the employee database, we use


the CREATE TABLE SQL statement. The usual form of this
statement is

create table tablename ( table definition )


[type=table_type];
 That is, we begin with the words create table, followed
by the name we would like the table to have, followed
by a set of column definitions.
 At the end of the statement, we can optionally specify
the storage engine type we would like to use.
Example:
9

 create table department ( departmentID int not null


auto_increment primary key, name varchar(30) )
type=InnoDB;
Column and Data Types in MySQL
10

 There are three basic column types in MySQL:


 numerical types,
 string or text types,
 date and time types.
Numerical Types
11

 Numerical types are used for storing numbers. In our


example, we used the types int (integer) and float
(floating-point number).
 These represent the two subtypes of numerical
types:
 the exact numerical types and
 the approximate numerical types.
NUMERIC or DECIMAL
12

 These types are the same, and DECIMAL may also


be abbreviated to DEC.
 These types are used to store exact floating-point
values and are typically used to store monetary
values.
 They have the same range as double-precision
floating-point numbers.
INTEGER and Variations
13

 This type can be abbreviated as INT. This is a


standard integer, stored in 4 bytes, giving a range of
232 possible values. There are also several variations
on INT:
A TINYINT is 1 byte (28 possible values). The keywords
BIT and BOOL are synonyms for TINYINT.
 A SMALLINT is 2 bytes (216 possible values).

 A MEDIUMINT is 3 bytes (224 possible values).

 A BIGINT is 8 bytes (264 possible values).


FLOAT
14

 This is a single-precision floating-point number. It


can represent a positive number between 1.18x10-
38 to 3.40x1038 and a similar range of negative

numbers.
DOUBLE
15

 This is a double-precision floating-point number.


Synonyms for DOUBLE are REAL and DOUBLE
PRECISION.
 They can represent a positive number between
2.23x10-308 to 1.80x10308 and a similar range of
negative numbers.
String and Text Types
16

 MySQL supports various string and text types.


 The basic types are CHAR, VARCHAR, TEXT, ENUM,
and SET.
CHAR
17

 CHAR is used to store fixed-length strings.


 As in the employee database, CHAR is usually
followed by a string length, for example CHAR(20).
If you do not specify a length, you will get a
CHAR(1).
 The maximum length of a CHAR is 255 characters.
VARCHAR
18

 VARCHAR stores variable-length strings.


 You specify the width in parentheses after the type,
for example, VARCHAR(10). The range is 0 to 255.
TEXT
19

 The TEXT types are used for storing longer pieces of


text than you can fit in a CHAR or VARCHAR.
ENUM
20

 This type allows you to list a set of possible values.


Each row can contain one value from the
enumerated set. You declare an ENUM as follows:
gender enum('m', 'f')
 Enumerated types can also be NULL, so the possible
values of gender are m, f, NULL, or error.
SET
21

 The SET type is similar to ENUM except that rows


may contain a set of values from the enumerated
set.
Date and Time Types
22

 DATE
 TIME
 DATETIME
 TIMESTAMP
 YEAR
DATE
23

 The date type stores a date.


 MySQL expects the date in ISO year-month-day
order, avoiding trans-Atlantic arguments.
 Dates are displayed as YYYY-MM-DD.
TIME
24

 This type stores a time, displayed as HH:MM:SS.


DATETIME
25

 This is a combination of DATE and TIME.


 The format is YYYY-MM-DD HH:MM:SS.
TIMESTAMP
26

 This is a useful column type. If you do not set this


column in a particular row, or set it to NULL, it will
store the time that row was inserted or last changed.
 When you retrieve a timestamp, it will be displayed
in the DATETIME format.
YEAR
27

 This type stores a year.


 When you declare a column of this type, you can
declare it as YEAR(2) or YEAR(4) to specify the
number of digits. YEAR(4) is the default.
 YEAR(2) represents the range 1970 to 2069.
Creating Indexes
28

 Usually, you create all the indexes you need when you are creating
tables. Any column declared as PRIMARY KEY, KEY, UNIQUE, or INDEX
will be indexed.
 Sometimes you will find that you are running many queries based on an
unindexed column, and in this situation, you can add an index using the
CREATE INDEX statement.
 Interestingly enough, the CREATE INDEX statement is mapped to an
ALTER TABLE statement before being executed. The ALTER TABLE
statement can be used for this and many other purposes. We will look
at its use in the last section of this chapter.
 We can, for example, add an index to the employee table as follows:
 create index name on employee(name);
 This creates an index called name based on the name field in the
employee table.
Deleting Databases, Tables, and
29
Indexes

 Now that we know how to create databases, tables,


and indexes, it is also useful to know how to delete
these things. The keyword we need for this purpose
is DROP.

drop database employee;


Deleting a Table
30

 You can delete a single table with the DROP TABLE


statement, for example,
drop table assignment;

 The general form of the DROP TABLE statement is as


follows:

DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [,


tbl_name,...] You can specify the TEMPORARY keyword
for dropping temporary tables. You can also drop
multiple tables at once by listing a set of comma-
separated names. The optional IF EXISTS clause works
the same way as it does for DROP DATABASE.
Deleting an Index
31

 You can delete an index with the DROP INDEX


statement, for example,
 drop index part_name on employee;
 As you can see, you need to specify which table the
index is on to delete the index.
Altering Existing Table Structures
32

 As well as creating and deleting tables, we often need


to be able to change the structure of an existing table.
 We can do this with the ALTER TABLE statement. ALTER
TABLE has many, many variations we can use to alter
table structure.
 For example, we could have created the name index on
employee as follows:

alter table employee


add index name (name);
Syntax
33

 ALTER [IGNORE] TABLE tbl_name alter_spec [,


alter_spec ...] alter_spec:
 ADD [COLUMN] create_definition [FIRST | AFTER
col_name ] or ADD [COLUMN] (create_definition,
create_definition,...) or
 ADD INDEX [index_name] (index_col_name,...) or
 ADD PRIMARY KEY (index_col_name,...) or
 ADD UNIQUE [index_name] (index_col_name,...) or
 ADD FULLTEXT [index_name] (index_col_name,...) or
Syntax
34

 ADD [CONSTRAINT symbol] FOREIGN KEY


[index_name] (index_col_name,...)
[reference_definition] or
 ALTER [COLUMN] col_name {SET DEFAULT literal |
DROP DEFAULT} or
 CHANGE [COLUMN] old_col_name create_definition
[FIRST | AFTER column_name] or
 MODIFY [COLUMN] create_definition [FIRST | AFTER
col_name] or
 DROP [COLUMN] col_name or
 DROP PRIMARY KEY or
Syntax
35

 DROP INDEX index_name or


 DISABLE KEYS or
 ENABLE KEYS or
 RENAME [TO] new_tbl_name or
 ORDER BY col_name or
 table_options
The Syntax Explained:
36

 The CHANGE and MODIFY clauses are the same:


They allow you to change the definition of a column
or its position in the table.
 DROP COLUMN deletes a column from the table,
whereas DROP PRIMARY KEY and DROP INDEX
delete just the associated index for that column.
 The DISABLE KEYS clause tells MySQL to stop
updating indexes for a MyISAM table only. ENABLE
KEYS turns index updating back on.
The Syntax Explained:
37

 The RENAME clause lets you change the name of a


table.
 The ORDER BY clause will put the rows in the newly
altered table in a particular order, like the ORDER
BY clause in a SELECT statement.
 The table_options option lets you specify the same
table options as at the end of the CREATE TABLE
statement—see earlier in this chapter for details.
Summary
38

 In this chapter, we learned how to create and


delete databases, tables, and indexes and how to
change the structure of an existing table.
Case Sensitivity and Identifiers
39

 Database names have the same case sensitivity as


directories in your operating system. Table names follow
the same rules as filenames. Everything else is case
insensitive.
 All identifiers except aliases can be up to 64 characters
long. Aliases can be up to 255 characters long.
 Identifiers can contain most characters, but database
names may not contain /, \, or . and table names
cannot contain . or /.
 You can use reserved words for identifiers as long as
you put them in quotes.
Creating a Database
40

 create database dbname; creates a database.


 use database dbname; selects a database for use.
Creating Tables
41

 Use the create table statement, which has this general form:
Column Types
42

 Exact numeric types are TINYINT, SMALLINT, INT,


MEDIUMINT, BIGINT, NUMERIC, and DECIMAL.
 Approximate numeric types are FLOAT and
DOUBLE.
 String types are CHAR, VARCHAR, TEXT, and BLOB.
 Date and time types are DATE, TIME, DATETIME,
TIMESTAMP, and YEAR.
 There are also various aliases to these type names.
Dropping Databases, Tables, and
43
Indexes
 Drop a database with
 drop database dbname;
 Drop a table with
 drop table tablename;
 Drop an index with
 drop index indexname on tablename;
Altering Existing Table Structures
44

 Change table structure with ALTER TABLE. This is the general structure of the
ALTER TABLE command:
Exercises
45

1: Write SQL statements to create a database with the following schema:


customer(customerID, customerName, customerAddress)
order(orderID, orderDate, customerID)
orderItem(orderID, itemID , itemQuantity)
item(itemID, itemName)
You may make any assumptions you like about data types.
Test your statements in MySQL and view the resulting tables using SHOW and
DESCRIBE.
2: We would now like to add a notes field, which you may assume is of type
TEXT, to each order in the orders table. Use an ALTER TABLE statement to
achieve this, and check your result with a DESCRIBE statement.
3: Drop the order database.

Вам также может понравиться