Tool/Web URL Features phpmyadmin. More on phpmyadmin under User Intefaces. MySQL Query Browser

Similar documents
To insert a record into a table, you must specify values for all fields that do not have default values and cannot be NULL.

TINYINT[(M)] [UNSIGNED] [ZEROFILL] A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

Data Definition Language with mysql. By Kautsar

Lab # 2 Hands-On. DDL Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

Data and Tables. Bok, Jong Soon

ALTER TABLE Improvements in MARIADB Server. Marko Mäkelä Lead Developer InnoDB MariaDB Corporation

Introducing Transactions

Careerarm.com. 1. What is MySQL? MySQL is an open source DBMS which is built, supported and distributed by MySQL AB (now acquired by Oracle)

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

Data Types in MySQL CSCU9Q5. MySQL. Data Types. Consequences of Data Types. Common Data Types. Storage size Character String Date and Time.

The Top 20 Design Tips

Chapter 8 How to work with data types

Chapter 8: Working With Databases & Tables

Overview of MySQL Structure and Syntax [2]

Basis Data Terapan. Yoannita

Lab # 4. Data Definition Language (DDL)

The M in LAMP: MySQL CSCI 470: Web Science Keith Vertanen Copyright 2014

Basic SQL. Basic SQL. Basic SQL

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Like all programming models, MySQL identifiers follow certain rules and conventions.

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

MySQL: an application

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Programming and Database Fundamentals for Data Scientists

Mastering phpmyadmiri 3.4 for

CIS 363 MySQL. Chapter 4 MySQL Connectors Chapter 5 Data Types Chapter 6 Identifiers

GridDB Advanced Edition SQL reference

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

SQL DDL II. CS121: Relational Databases Fall 2017 Lecture 8

More MySQL ELEVEN Walkthrough examples Walkthrough 1: Bulk loading SESSION

SQL: Data Definition Language

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus

Chapter 3 Introduction to relational databases and MySQL

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Exam Questions 1z0-882

*this is a guide that was created from lecture videos and is used to help you gain an understanding of what is mysql used for.

Lecture 07. Spring 2018 Borough of Manhattan Community College

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

Full file at

MySQL 5.0 Certification Study Guide

Writing High Performance SQL Statements. Tim Sharp July 14, 2014

T-SQL Training: T-SQL for SQL Server for Developers

MySQL 101. Designing effective schema for InnoDB. Yves Trudeau April 2015

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Oracle SQL Developer. Supplementary Information for MySQL Migrations Release 2.1 E

Today Learning outcomes LO2

High Performance MySQL Practical Tuesday, April 01, :45

Acknowledgments About the Authors

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

SQL. Often times, in order for us to build the most functional website we can, we depend on a database to store information.

Data Definition Language (DDL)

Data Storage and Query Answering. Data Storage and Disk Structure (4)

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Data types String data types Numeric data types Date, time, and timestamp data types XML data type Large object data types ROWID data type

Data File Header Structure for the dbase Version 7 Table File

SQL Interview Questions

Mysql Information Schema Update Time Null >>>CLICK HERE<<< doctrine:schema:update --dump-sql ALTER TABLE categorie

MTAT Introduction to Databases

Daffodil DB. Design Document (Beta) Version 4.0

MTAT Introduction to Databases

user specifies what is wanted, not how to find it

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

SQL Introduction. CS 377: Database Systems

DB Programming. Database Systems

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Simple Quesries in SQL & Table Creation and Data Manipulation

Tables From Existing Tables

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Model Question Paper. Credits: 4 Marks: 140

Creating databases using SQL Server Management Studio Express

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

Code Centric: T-SQL Programming with Stored Procedures and Triggers

opencrx Installation Guide for MySQL 5

Advanced SQL. Nov 21, CS445 Pacific University 1

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Course Outline. MySQL Database Administration & Design. Course Description: Pre-requisites: Course Content:

System Pages (Setup Admins Only)

Using DDL Statements to Create and Manage Tables. Copyright 2006, Oracle. All rights reserved.

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

Working with DB2 Data Using SQL and XQuery Answers

Oracle 1Z0-882 Exam. Volume: 100 Questions. Question No: 1 Consider the table structure shown by this output: Mysql> desc city:

SQL Server 2008 Tutorial 3: Database Creation

THE UNIVERSITY OF AUCKLAND


Selections. Lecture 4 Sections Robb T. Koether. Hampden-Sydney College. Wed, Jan 22, 2014

Creating and Managing Tables Schedule: Timing Topic

System Characteristics

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

SQL DATA DEFINITION LANGUAGE

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

Introduction to SQL Server 2005/2008 and Transact SQL

DB Creation with SQL DDL

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

Transcription:

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 SQLyog MySQL http://www.webyog.com/ SQLyog MySQL GUI is the most powerful MySQL manager and admin tool, Syntax <database definition>::= CREATE DATABASE [IF NOT EXISTS] <database name> [[DEFAULT] CHARACTER SET <character set name>] [[DEFAULT] COLLATE <collation name>] combining the featur 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. 1 / 25

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: 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> 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. 2 / 25

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: 3 / 25

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. 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 ( 4 / 25

... 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 in InnoDB A transaction-safe table that is managed by the InnoDB handler. As a result MERGE A virtual table that is made up of identical MyISAM tables. Data is not stored MEMORY A table whose contents are stored in memory, available only as long as the We will create a table called film_info of type ISAM. 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 P RIMARY 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>}...])} 5 / 25

{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. ALTER TABLE film_review ADD COLUMN review_date DATETIME; Renaming Tables An existing table can be renamed with another name, as shown CREATE TEMPORARY TABLE temp_table( column1 SMALLINT ); ALTER TABLE temp_table RENAME temp2_table; DROP TABLE temp_table; -- Should give an error! 6 / 25

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>] 7 / 25

<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 167772153 bytes INT/INTEGER Signed: -2147483648 to 2147483647 Unsigned: 0 to 4294967295 4 bytes BIGINT Signed: -9223372036854775808 Unsigned: to 9223372036854775807 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 4 bytes 0 1.175494351E-38 to 3.4028 DOUBLE [PRECISION]/REAL 1.7976931348623157E+308 8 bytes to -2.2250738585072014E-308 0 2.22507385 DEC/DECIMAL/NUMERIC/FIXED Range and Storage requirements Depends depend on the <length> and <decimals> v String Data Types 8 / 25

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 VARCH AR 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. 9 / 25

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) 10 / 25

For example, the film information table may include a BLOB column named title_photo. 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 11 / 25

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. 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 12 / 25

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 13 / 25

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 ALTER TABLE film_review ADD review_date DATETIME NOT NULL; The reserve_date column is a date and time combination. TIMESTAMP: A Special Type 14 / 25

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 TIMESTAM P column. 15 / 25

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 v 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 UNSIGNED Integers are stored without a sign. Warning: calculations are then also made CHARACTER SET name[collate sort] For strings, specifies the character set and optionally 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 16 / 25

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. 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 N ULL. 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 17 / 25

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. 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. 18 / 25

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. 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) 19 / 25

... <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; 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 I NSERT statement, ensure that the table is not changed by any of these INSERT statements. All changes made by these statements will be rolled back. 20 / 25

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. 21 / 25

- 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. 22 / 25

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. DROP TABLE IF EXISTS film_review; 23 / 25

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. 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. 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. 24 / 25

In this demo, we are dropping the UNIQUE constraint. 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. 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. 25 / 25