MYSQL-TOOLS

Comparison of graphical tools for MySQL

Home Creating Databases and Components

Creating Databases and Components

In this lesson of the MySQL tutorial, you will learn...
  1. To create, use and drop databases.
  2. To create, use and alter tables.
  3. To define columns and constraints for tables.
  4. To create and drop indexes.
  5. To show database, table and index information.

In this lesson of the MySQL tutorial, we explore management of core storage objects to hold data in MySQL.



Creating Databases

Print PDF
User Rating: / 1
PoorBest 

To store data in MySQL, we will set up a database and then place tables, relationships and other objects in that database, following a design that maps to our application requirements. We will use a command-line tool - mysql, running a script to generate our objects. Several other options are available to create components via User Interfaces such as phpMyAdmin, MySQL Query Browser and MySQL Workbench.

Tool/Web URL Features
phpMyAdmin

http://www.phpmyadmin.net/home_page/index.php

More on phpMyAdmin under User Intefaces.
MySQL Query Browser

http://www.mysql.com/products/tools/query-browser/

A product from MySQL that provides a good set of drag-and-drop tools to visually define, run, manage and optimize SQL queries for MySQL Databases. Covered in another lesson.
SQLyog MySQL

http://www.webyog.com/

SQLyog MySQL GUI is the most powerful MySQL manager and admin tool, combining the features of MySQL Query Browser, Administrator, phpMyAdmin and other MySQL Front Ends and MySQL GUI tools in a single intuitive interface.
Syntax
<database definition>::=
CREATE DATABASE [IF NOT EXISTS] <database name>
[[DEFAULT] CHARACTER SET <character set name>]
[[DEFAULT] COLLATE <collation name>]

Note: If the database named above already exists, the statement above will throw an error. By specifying the IF NOT EXISTS clause, MySQL returns just a note (warning).

The CHARACTER SET specifies the default character set to use and the COLLATE clause selects default collation for ordering. More on these later.

We will now set up our new database sakilakubili using mysql.

Code Sample:

CREATE DATABASE sakilakubili;
USE sakilakubili;

The 1 row affected response from mysql indicates that one row was changed in the internal MySQL table containing the list of all databases. On statement execution, a database named sakilakubili is added to MySQL server. The database uses the default character set and collation as we didn't specify any.

Note:On Windows, all object names, such as databases and tables, are converted to lowercase. In Linux and other Unix-like operating systems, the case is preserved. More on case- senstivity in other lessons.

Here, we actually specify the character set and collation to use:

Code Sample:

CREATE DATABASE sakilakubili
DEFAULT CHARACTER SET latin1
DEFAULT COLLATE latin1_bin;

Deleting Databases

A database is dropped via the DROP DATABASE statement.

Syntax
DROP DATABASE [IF EXISTS] <database name>

Code Sample:

DROP DATABASE sakilakubili;

Warning: When a database is dropped, the tables and their data stored in that database are also deleted. Exercise extreme caution executing the DROP DATABASE command.

Creating Tables

We will now create additional tables in the sakila database using CREATE TABLE.

First, we must specify the database we will be working with. The USE database sets the default database to which further commands will be applied. In other words, the USE command selects an active database among several databases under MySQL management.

Tables provide a structure for storing and securing the data. All data exists within the structure of the tables, and tables are grouped inside of the database. In addition to creating tables, you can also modify the table definitions or drop the tables from the database.

The CREATE TABLE statement includes appropriate column definitions and constraints to be used for the entity associated with the table. The fundamental CREATE TABLE statement is complex and contains various clauses and options to complete its definition. This lesson focuses on the essential clauses in a table definition.

The syntax block below shows the basic CREATE TABLE syntax. We will discuss theses clauses one by one in this lesson.

Syntax
<table definition>::=
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] <table name>(
<table element>
[{, <table element>}...]
)
{ENGINE = {MEMORY | INNODB | MERGE | MYISAM}}
| <additional table options>

Here is an example:

Code Sample:

DROP TABLE IF EXISTS film_review;
CREATE TABLE film_review (
review_id INTEGER,
film_id SMALLINT NOT NULL,
review_text VARCHAR(255) NOT NULL
) ENGINE=InnoDB;

Tip:The CREATE TABLE command can span multiple lines, and each line is terminated with a Carriage Return.

Dropping Tables

To drop or delete a table, use the DROP TABLE statement.

Syntax
DROP [TEMPORARY] TABLE [IF EXISTS] <table name> [{, <table name>}...]

Some Tips:

  • The optional TEMPORARY keyword prevents the inadvertent loss of a permanent table.
  • When the IF EXISTS clause is used with a non-existent table, a warning is thrown instead of an error. Warnings do not stop the execution of a multi-statement script in its tracks.
  • We can use the DROP statement to drop several tables.

Code Sample:

DROP TABLE IF EXISTS reservation;

Warning: A master table referenced in a foreign key cannot be dropped without first removing the reference.

Defining Table Types

One especially important MySQL table options allows us to define the type of table that you create in your table definition.

Syntax
CREATE TABLE table-name (
... columns ... )
ENGINE = {MYISAM | INNODB | MEMORY | MERGE}

Each ENGINE or table type in MySQL is designed for specific purpose and is processed by associated storage engine. Engines are discussed in more detail in other lessons.

Table type Description
MyISAM This is default table type in MySQL. MyISAM tables support extensive indexing and are optimized for compression and speed. Unlike other table types, BLOB and TEXT columns can be indexed and null values are allowed in indexed columns. MyISAM tables are not transaction safe, and they do not support full foreign key functionality.
InnoDB A transaction-safe table that is managed by the InnoDB handler. As a result, data is not stored in a .MYD file, but instead is managed in the InnoDB tablespace. InnoDB tables also support full foreign key functionality in MySQL, unlike other tables. In addition, the InnoDB handler supports automatic recovery and row-level locking. InnoDB tables do not perform as well as MyISAM tables.
MERGE A virtual table that is made up of identical MyISAM tables. Data is not stored in the MERGE table, but in the underlying MyISAM tables. Changes made to the MERGE table definition do not affect the underlying MyISAM tables. MERGE tables can also be referred to as MRG_MyISAM tables.
MEMORY A table whose contents are stored in memory, available only as long as the MySQL server is available. If the server crashes or is shut down, the data disappears. Because these types of tables are stored in memory, they are very fast and are good candidates for temporary tables. The keywords MEMORY and HEAP are synonymous.

We will create a table called film_info of type ISAM.

Code Sample:

DROP TABLE IF EXISTS film_info;
CREATE TABLE film_info (
film_id SMALLINT NOT NULL,
info_text VARCHAR(10000) NOT NULL
) ENGINE=MyISAM;

Altering Existing Table Structures

Using ALTER TABLE, MySQL allows you to change an existing table in several ways, such as adding or dropping columns, change existing column definitions, adding PRIMARY KEY and FOREIGN KEY constraints, or remove constraints.

Altering table requires a good understanding of columns and constraints which are discussed in subsequent lessons.

Syntax
ALTER TABLE <table name>
<alter option> [{, <alter option>}...]

<alter option>::=
{ADD [COLUMN] <column definition> [FIRST | AFTER <column name>]}
| {ADD [COLUMN] (<table element> [{, <table element>}...])}
| {ADD [CONSTRAINT <constraint name>] PRIMARY KEY
(<column name> [{, <column name>}...])}
| {ADD [CONSTRAINT <constraint name>] FOREIGN KEY [<index name>]
(<column name> [{, <column name>}...]) <reference definition>}
| {ADD [CONSTRAINT <constraint name>] UNIQUE [<index name>]
(<column name> [{, <column name>}...])}
| {ADD INDEX [<index name>] (<column name> [{, <column name>}...])}
| {ADD FULLTEXT [<index name>] (<column name> [{, <column name>}...])}
| {ALTER [COLUMN] <column name> {SET DEFAULT <value> | DROP DEFAULT}}
| {MODIFY [COLUMN] <column definition> [FIRST | AFTER <column name>]}
| {CHANGE [COLUMN] <column name> <column definition> [FIRST | AFTER <column name>]}
| {DROP [COLUMN] <column name>}
| {DROP PRIMARY KEY}
| {DROP INDEX <index name>}
| {DROP FOREIGN KEY <constraint name>}
| {RENAME [TO] <new table name>}
| {ORDER BY <column name> [{, <column name>}...]}
| CONVERT TO CHARACTER SET charset_name [COLLATE collation_name]
| [DEFAULT] CHARACTER SET charset_name [COLLATE collation_name]
| {<table option> [<table option>...]}

Each of the alter options relates to a table definition option, and is preceded with an action keyword - ADD, ALTER, or DROP.

Add a column

A basic use of altering table is to add columns. In this demo, we are adding a column we forgot to add.

Code Sample:

ALTER TABLE film_review
ADD COLUMN review_date DATETIME;

Renaming Tables

An existing table can be renamed with another name, as shown

Code Sample:

CREATE TEMPORARY TABLE temp_table( column1 SMALLINT );
ALTER TABLE temp_table RENAME temp2_table;
DROP TABLE temp_table; -- Should give an error !
DROP TABLE temp2_table; -- That works !!

Temporary Tables

A TEMPORARY option make the table local or available only during the current session to the current user.

We created a temporary table in the previous demo. Once we end that session, the table will be automatically deleted in case you forget to do so.

Exercise: Confirm a Table is temporary

Duration: 5 to 10 minutes.

In this exercise, we will ensure the temp table above is not available.

  1. Start another mysql session, while the previous session is still active.
  2. Ensure that temp2_table above does not exist.
  3. The table should not be available whether the previous session is still running or not.

Creating Column Definitions

We will create column definitions for each column that needs to be part of the table. Two core elements required in a column definition are the column name (any acceptable MySQL identifier) and a supported data type, but several other elements can be specified with a column as shown in the syntax for table elements below.

Syntax
<table element>::=
<column definition>
| {[CONSTRAINT <constraint name>] PRIMARY KEY
(<column name> [{, <column name>}...])}
| {[CONSTRAINT <constraint name>] FOREIGN KEY [<index name>]
(<column name> [{, <column name>}...]) <reference definition>}
| {[CONSTRAINT <constraint name>] UNIQUE [INDEX] [<index name>]
(<column name> [{, <column name>}...])}
| {{INDEX | KEY} [<index name>] (<column name> [{, <column name>}...])}
| {FULLTEXT [INDEX] [<index name>] (<column name> [{, <column name>}...])}

<column definition>::=
<column name> <type> [NOT NULL | NULL] [DEFAULT <value>] [AUTO_INCREMENT]
[PRIMARY KEY] [COMMENT '<string>'] [<reference definition>]

<type>::=
<numeric data type>
| <string data type>
| <data/time data type>

<reference definition>::=
REFERENCES <table name> [(<column name> [{, <column name>}...])]
[ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }]
[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }]
[MATCH FULL | MATCH PARTIAL]

Data Types in MySQL

Every table is composed of a number of columns. For each column, an intended data type must be specified. This section provides an overview of the data types available in MySQL. A data type is essentially a constraint on a column which defines and limits the type of values that can be stored in that column.

Numeric Data Types

Numeric data types fall under two key categories: integer or fractional. UNSIGNED option disallows negative values in the column. There are several integer types in MySQL to store various range of values as shown:

Data type Acceptable values Storage
TINYINT Signed: -128 to 127 Unsigned: 0 to 255 1 byte
SMALLINT Signed: -32768 to 32767 Unsigned: 0 to 65535 2 bytes
MEDIUMINT Signed: -8388608 to 8388607 Unsigned: 0 to 16777215 3 bytes
INT/INTEGER Signed: -2147483648 to 2147483647 Unsigned: 0 to 4294967295 4 bytes
BIGINT Signed: -9223372036854775808 to 9223372036854775807 Unsigned: 0 to 18446744073709551615 8 bytes

The fractional data types support the use of data in post decimals places.

Data type Range of Values Storage
FLOAT -3.402823466E+38 to -1.175494351E-38 0 1.175494351E-38 to 3.402823466E+38 4 bytes
DOUBLE [PRECISION]/REAL 1.7976931348623157E+308 to -2.2250738585072014E-308 0 2.2250738585072014E-308 to 1.7976931348623157E+308 8 bytes
DEC/DECIMAL/NUMERIC/FIXED Range and Storage requirements depend on the <length> and <decimals> values specified in the column definition Depends

String Data Types

The string data types can hold wide range of data from individual bits to large files. MySQL supports four varieties of string data types.

<character data type>
CHAR (<length>) [BINARY | ASCII | UNICODE]
VARCHAR (<length>) [BINARY]

<binary data type>
TINYBLOB | BLOB | MEDIUMBLOB | LONGBLOB

<text data type>
TINYTEXT | TEXT | MEDIUMTEXT | LONGTEXT

<list data type>
{ENUM | SET} (<value> [{, <value>}...])

The CHAR data type is a fixed in length and can store up to 255 characters. The actual value can have fewer characters than the amount specified, still the amount of storage is fixed at the specified amount. If character count in the column is variable, we can use a VARCHAR type, where storage is based roughly on the number of characters in the value.

The following options can be used with CHAR type.

  • BINARY: Makes sorting and comparisons case sensitive.
  • ASCII: Assigns the latin1 character set to the column.
  • UNICODE: Assigns the ucs2 character set to the column.

Binary data types are designed to store large amounts of data, such as pictures and varying messages.

The main difference between Text data and Binary data types is that text data types are associated with a specific character set. Binary columns are treated as strings, and sorting is case sensitive. Text columns are treated according to their character sets, and sorting is based on the collation for that character set. The advantage here is that we can use a character set / collation for the column that differs from the table, database or server.

Data type

Maximum size

TINYBLOB/TINYTEXT

255 characters (355 bytes)

BLOB/TEXT

65,535 characters (64 KB)

MEDIUMBLOB/MEDIUMTEXT

16,777,215 characters (16 MB)

LONGBLOB/LONGTEXT

4,294,967,295 characters (4 GB)

For example, the film information table may include a BLOB column named title_photo.

Code Sample:

ALTER TABLE film_info
ADD COLUMN film_photo BLOB;

Character Set Fundamentals

For TEXT columns, we can use the additional attributes CHARACTER SET character-set-name COLLATE sortorder. Character sets specify the code-set is used to represent the various characters. In general, character sets incorporate the 128 English ASCII characters. Representation of international characters is a challenge however.

  • Latin Character Sets: In earlier years of computing, the linguistic regions evolved various one-byte character sets. Latin character sets have achieved the most widespread use: Latin1, alias ISO-8859-1, contains all characters usual in Western Europe (??????? etc.). Latin2, alias ISO-8859-2, contains characters from CEE (Central and East European) languages. Latin0, alias Latin9, alias ISO-8859- 15, is the same as Latin 1, but with the euro symbol included.

    None of these character sets contains all the characters of all the European languages, so there is no single Latin character set for all of Europe.

  • Unicode Variants: To handle this issue, a 2-byte Unicode character set was developed. With 65,535 characters allowed, the set covers all of Europe and most of the Asian languages.

    However, Unicode determines only which code is associated with which character, not how the codes are internally stored, and we discuss two common storage variants:

    • UCS-2/UTF-16 (Universal Character Set): Each character is stored in 2 bytes or 16 bits.

      However, this format has downsides: The storage requirement for characters is simply doubled, even in the routine and very common situations where only European/ASCII characters are used, as these never go beyond 1 byte.

      Also, the byte code 0 is common in Unicode character strings. For 1-byte English ASCII characters, every second byte is zero. Many older, non-Unicode programs cannot handle zero bytes in strings and some even use a zero byte as the end of a string.

    • UTF-8 (Unicode transfer format): This is a popular alternative to UTF-16 where the 7-bit ASCII characters are stored as a single byte. The other Unicode characters are stored as 2 to 4 bytes.

      There is no obvious relationship between the number of bytes and characters. But this format is compatible with existing programs, a big advantage. UTF-8 is therefore a standard under Unix/Linux and most other components important for Web development.

Set Types

The ENUM type restricts a column to a given list of values. A SET type is similar to an ENUM type, but SET type allows multiple values to be stored in the column from the list.

In the example below, the trust status of information on a film is a single value from a limited set whereas the entities the info can be shown for of film, actor and / or studio. Similarly, we also record who was the information submitted by from a select set of values.

Code Sample:

ALTER TABLE film_info
ADD status ENUM('ACTIVE', 'NOTVERIFIED'),
ADD show_in SET('FILM', 'ACTOR', 'STUDIO'),
ADD submitted_by ENUM('PROF','VIEWER','STAFF','STUDIO');

Date/Time Data Types

The date/time data types store temporal values such as dates and times.

DATE | TIME | DATETIME | YEAR | TIMESTAMP

Data type

Format

Range

DATE

YYYY-MM-DD

1000-01-01 through 9999

TIME

HH:MM:SS

-838:59:59 to 838:59:59

DATETIME

YYYY-MM-DD HH:MM:SS

1000-01-01 00:00:00 through 9999

YEAR

YYYY

1901 to 2155 (and 0000)

TIMESTAMP

YYYY-MM-DD HH:MM:SS

1970-01-01 00:00:00 to partway through 2037

Code Sample:

ALTER TABLE film_review
ADD review_date DATETIME NOT NULL;

The reserve_date column is a date and time combination.

TIMESTAMP: A Special Type

Columns of TIMESTAMP play a special role as they are automatically updated whenever the record is inserted or updated with the time of last change. This is more of a tracking field rather than for storing actual data. For a TIMESTAMP to be automated well, the column must not have any explicit value assigned or be a NULL where MySQL will set the current time.

We can manage variations TIMESTAMP columns through two attributes shown below.

TIMESTAMP [DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP]

(Default) The column is automatically updated both when a new record is created and for each change in a record. The specification in square brackets [] is optional.

TIMESTAMP DEFAULT CURRENT_TIMESTAMP

Time is set on the column when a new record is added, but column is left unchanged thereafter.

TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

The column is set to zero on creation but updated with current time on subsequent changes.

TIMESTAMP DEFAULT 'yyyy-mm-dd hh:mm:ss' ON UPDATE CURRENT_TIMESTAMP

When created, column is set to given time; but current time is stored on subsequent updates.

Tip: To manage a date-time column yourself, use DATETIME data type and NOT a TIMESTAMP column.

Options and Attributes

A variety of options and additional attributes can be specified when a column is created. Table below lists the most important options. Note that many attributes are suitable only for particular data types.

Important Column Attributes and Options
MySQL Keyword Meaning
NULL The column may contain NULL values. (default)
NOT NULL The value NULL is not permitted.
DEFAULT xxx The value xxx will be used as a default if value is not specified on add.
PRIMARY KEY Defines the column as a primary key.
AUTO_INCREMENT

A incrementing sequential number is automatically input for integer values. The column should

also be a NOT NULL and a PRIMARY KEY or a UNIQUE.

UNSIGNED Integers are stored without a sign. Warning: calculations are then also made without a sign.
CHARACTER SET name [COLLATE sort] For strings, specifies the character set and optionally the desired sort order.

Unfortunately, MySQL does not allow a function to be given as default value. It is also impossible, for example, to specify DEFAULT RAND() if you wish to have a random number automatically stored in a column. It is also impossible to define validation rules for columns (so that, for example, only values between 0 and 100 can be stored).

Constraints

MySQL also supports many types of constraints to support data integrity. A constraint can be part of a column definition or be given a specific name so that it can be referenced later. Constraint violations are generally checked after execution of each statement.

NOT NULL Constraint: Defining a Column's Nullability

For some columns, it is acceptable to set null or unknown values. A null value is not the same as zero or blank, instead it indicates absence of value. By default, NULL is assumed, and null values are permitted in the column.

Warning: You must provide values for NOT NULL columns during Inserts and Updates. There are two exceptions to this rule when a column is of data type TIMESTAMP or tagged with AUTO_INCREMENT option.

For example, after executing the following, review_date below can never be set to null.

Code Sample:

ALTER TABLE film_review
MODIFY review_date DATETIME NOT NULL;

UNIQUE Constraint

The UNIQUE constraint specifies that the combined value of given columns must either be unique across the table or have NULL values. If using just one column, UNIQUE constraint can be specified as part of the column definition.

Syntax
CONSTRAINT constraintName UNIQUE(column1,column2,...)
... or for single column ...
<column-def> UNIQUE

PRIMARY KEY Constraint: Defining a Master Key

PRIMARY KEY constraint is similar to UNIQUE constraint as well as a PK column cannot be NULL. A primary key is one or more columns in a table used uniquely identify each row in that table. For nearly any table you create, you should define a primary key for that table. A table can have only one PRIMARY KEY constraint.

CONSTRAINT constraintName PRIMARY KEY(column1,column2....)
... or for single column ...
<column-def> PRIMARY KEY

Use PRIMARY KEY option in the column definition.

film_id INT NOT NULL PRIMARY KEY,
... or define a separate constraint ...
sPRIMARY KEY (film_id)

Defining Auto-Increment Columns

review_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
);

In this demo, we are making review_id a TRUE key and set it as an AUTO_INCREMENT column.

Code Sample:

USE sakilakubili;
ALTER TABLE film_review
MODIFY review_id MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY;

Now, when we add a new row to the film_review table, a new number is automatically assigned to the review_id, incremented by 1, based on the highest value existing in that column.

Note: AUTO_INCREMENT can only be used on an integer type column as NOT NULL. The table must be set up as a primary key or with a unique index, and only one AUTO_INCREMENT column per table is allowed. No DEFAULTS are allowed for AUTO_INCREMENT column.

Referential Integrity Constraints: Defining Foreign Keys

Referential integrity or FK constraints ensure data in the referencing table has related and needed data in the foreign or referenced table. Specifically, each element of the column specified as a foreign key must match an element of a key column (or a set of columns comprising the key) of the specified foreign (referenced) table. Several example of FK constraints are part of schemas included with this courseware.

In order to implement relationships in MySQL, we define foreign keys on the referencing tables. You define the foreign key on the column or columns in the originating child table that references the column or columns in the referenced parent table. A foreign key leads to consistency between the child table the parent table.

Syntax
REFERENCES referenced-table(column)
... or as a separate constraint ...
FOREIGN KEY(referencing-table-columns)
REFERENCES referenced-table(columns)

There are two key Foreign Key rules generally applied:

  • Insert & Update Rule (Referencing Table): Inserting a non-null foreign key or updating a foreign key in the referencing table is permitted when the new or modified foreign key matches a key in the specified referenced table.
  • Update & Delete Rule (Referenced Table): A key in the referenced table cannot be altered or removed if being used as a foreign key in any referencing table.

In this demo, we are adding a FOREIGN KEY constraint.

Code Sample:

ALTER TABLE film_review
ADD INDEX(film_id);
ALTER TABLE film_review
ADD CONSTRAINT fk_film_review_film FOREIGN KEY (film_id) REFERENCES film(film_id)
ON DELETE CASCADE ON UPDATE CASCADE;

ON DELETE clause and an ON UPDATE clause set with CASCADE option are out of scope for this lesson.

CHECK Constraint

The CHECK constraint specifies a condition that must not be violated, and is used commonly for limiting values that can be stored in a column.

Syntax
CONSTRAINT constraintName CHECK(condition)
.... <column-def> CHECK(condition)

Here are two sample CHECK constraints. budget must be greater than 50,000 and release_year must be 20th century or newer.

budget FLOAT CHECK(budget > 50000.0),
release_year CHECK(release_year >= 2000),

Constraint Checking on a Transaction

By default, MySQL does not abort the transaction violating a constraint. If the statements are executed as part of a transaction.

START TRANSACTION;
.... constraint error
ROLLBACK;

Code Sample:

ALTER TABLE category DROP INDEX uniq_cat_name;
ALTER TABLE category ADD UNIQUE uniq_cat_name(name);
START TRANSACTION;
INSERT INTO category(name) VALUES('Bizarre');
INSERT INTO category(name) VALUES('Bizarre');
INSERT INTO category(name) VALUES('Outlandish');
COMMIT;

SELECT * FROM category WHERE name in ('Bizarre','Outlandish');

DELETE FROM category WHERE name in ('Bizarre','Outlandish');
Code Explanation
  • Alter the category table to add a UNIQUE constraint on name.
  • Start a transaction
  • Insert three rows, with two being same names, defying the unique constraint.
  • Eventhough only two rows are inserted, the UNIQUE failure on the second insert did not stop the transaction from proceeding.

if you would like to abort the transaction explicitly on error, instead of committing after the last INSERT statement, ensure that the table is not changed by any of these INSERT statements. All changes made by these statements will be rolled back.

MySQL is flexible in its handling of constraint violations. For example, instead of flagging an error and simply not executing the statement violating a constraint, MySQL can be instructed to abort the transaction containing the offending statement. This is done by setting the MySQL variable sql_mode to the value STRICT_TRANS_TABLES when starting the MySQL server or from the MySQL client.

Deferred Checking

With some databases, the timing to execute Constraint checks can be specified as:

  • IMMEDIATE: After execution of each statement using the IMMEDIATE clause (default) or
  • DEFERRED: At end of a transaction using the DEFERRED clause.

One issue with immediate constraint checking after each statement is slowing down of transaction processing. However, this may be a good thing as an error can be detected immediately, resulting to a transaction abort (or error indication), statement that violated the constraint. MySQL does not support Deferred constraint checks.

Defining Default Values

DEFAULT values can also be used for undefined values.

... ReviewBy VARCHAR(50) NOT NULL DEFAULT '**' ...

It is likely that the review writer may not be known and is set to '**" via DEFAULT option followed by the default value to use.

If a column accepts null values, the default is NULL. If a column does not accept null values, MySQL has a way of handling defaults as shown:

  • TIMESTAMP: the default value for the first TIMESTAMP column is the current date and time. The default values for any other TIMESTAMP columns in the table are zero values in place of the date and time.
  • For columns configured with a date/time data type other than TIMESTAMP, the default values are zero values in place of the date and time.
  • For numeric columns configured with the AUTO_INCREMENT option, the default value is the next number in the incremented sequence of numbers. (The AUTO_INCREMENT option is discussed later in the lessons.)
  • For numeric columns that are not configured with the AUTO_INCREMENT option, the default value is 0.
  • For columns configured with the ENUM data type, the default value is the first value specified in the column definition.
  • For columns configured with a string data type other than the ENUM type, the default value is an empty string.

Warning: RDBMSs differ considerably on handling defaults and many do not automatically assign default values to all columns. MySQL is however more forgiving and this laxity may actually cause issues.

Managing Indexes

Indexes on data tables speed up searches which cut down the time it takes to execute complex queries. Scanning a sorted index is quicker and more efficient access than reading a whole table. MySQL supports several index types that can be created on a table.

Unique Indexes require that a value or a set of values be unique across the table in the columns on which the index is defined. But unlike primary key indexes, null values are allowed. We can also create Regular (non-unique) indexes that permits duplicate values and null values on the indexed columns.

MySQL will automatically create an index on column(s) used as a Primary key.

When using a foreign key on columns in a child InnoDB table, the child's foreign key columns and the referenced columns in the parent table must both be indexed.

Full-text indexes support full-text searches of the values in the columns on which the index is defined. A full-text index can be used only with tables of MyISAM type and only on CHAR, VARCHAR, and TEXT columns.

To add indexes on a table, we can use indexing options in column definition, either at Creation time or via an ALTER TABLE statement; or create indexes later by using the CREATE INDEX statement explicitly.

Tip: Adding or dropping keys via ALTER TABLE statement can also be used to add or drop indexes once tables have been already created.

Defining Indexes when Creating Tables

When we define keys in CREATE TABLE statement, MySQL automatically creates appropriate indexes on the columns participating in a particular key.

In Database parlance, the keywords KEY and INDEX are used interchangeably.

We can create unique indexes using a UNIQUE constraint on a set of columns, and we can define a regular index by specifying the INDEX or KEY keyword and the name of the indexed column, and optionally provide a name for your index.

The next demo shows a more-or-less complete film_review table as a summary of concepts just learnt.

Code Sample:

DROP TABLE IF EXISTS film_review;
CREATE TABLE film_review (
review_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
film_id SMALLINT UNSIGNED NOT NULL,
review_text VARCHAR(255) NOT NULL,
review_by VARCHAR(50) NOT NULL DEFAULT '-',
review_category ENUM('PROF','VIEWER','PUBLIC','STAFF') NOT NULL DEFAULT 'PUBLIC',
review_date DATETIME NOT NULL,
PRIMARY KEY (review_id),
UNIQUE idx_uq_film_review(review_by,film_id),
KEY idx_fk_review_film (film_id),
CONSTRAINT fk_review_film FOREIGN KEY (film_id) REFERENCES film (film_id) ON DELETE
 RESTRICT ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE INDEX Statement

A CREATE INDEX statement can be used to explicitly create indexes on various tables. Using CREATE INDEX, you can add unique, regular, and full-text indexes to a table, but not primary key or foreign key indexes.

Code Sample:

CREATE INDEX idx_film_review_date ON film_review(review_date);

Full-Text Indexes

Adding a full-text index is similar to a regular index using keyword FULLTEXT. This example create a special full-text index on the info_text column of VARCHAR data type in film_info table.

Code Sample:

DROP INDEX idx_text_film_info ON film_info;
CREATE FULLTEXT INDEX idx_text_film_info ON film_info (info_text);

Deleting Indexes

Indexes can be dropped either via ALTERing the TABLE or by explicit DROP INDEX statement.

In this demo, we are dropping the UNIQUE constraint.

Code Sample:

ALTER TABLE film_review DROP INDEX idx_uq_film_review;
-- This works as well
-- DROP INDEX idx_uq_film_review ON film_review;
Code Explanation

Drop the unique index from film review table.

In this demo, we create a table called film_studio with several indexes.

Code Sample:

DROP TABLE IF EXISTS studio;
CREATE TABLE studio (
studio_id MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
studio_name VARCHAR(100) NOT NULL,
UNIQUE( studio_name )
)ENGINE=MyISAM AUTO_INCREMENT=101 DEFAULT CHARSET=utf8;

Creating Databases and Components Conclusion

This lesson covered the mechanisms to create a database and some components.

To continue to learn MySQL go to the top of this page and click on the next lesson in this MySQL Tutorial's Table of Contents.
 


mysql tools

How create data source in Visual Studio with data from My SQL tables with FK. more...

'mysql.proc' doesn't exist fixed problem

_

Table 'mysql.proc' doesn't exist. Fix error 1146 Table doesn't exist here...