42
1 Introduction to MySQL Introduction to MySQL & SQL & SQL

1 Introduction to MySQL & SQL. MySQL Relational Database Management System Relational Database Management System Competitors Competitors –Oracle –IBM

Embed Size (px)

Citation preview

11

Introduction to MySQL & Introduction to MySQL & SQLSQL

MySQLMySQL

• Relational Database Management Relational Database Management SystemSystem

• CompetitorsCompetitors– OracleOracle– IBM DB2IBM DB2– MS SQL-ServerMS SQL-Server

– These offer more facilities (better SQL-98 These offer more facilities (better SQL-98 compliance) but MySQL is generally fastestcompliance) but MySQL is generally fastest

Reasons to use MySQLReasons to use MySQL

• Price – Free or low costPrice – Free or low cost

• Stability and speedStability and speed

• Ease of useEase of use

• FeaturesFeatures

Choice of Database Engines (Table types - 1)Choice of Database Engines (Table types - 1)

• Default - MyIsam Default - MyIsam – Tables up to 4GB – also supports merge tablesTables up to 4GB – also supports merge tables– Max 64 keys per tableMax 64 keys per table– Full text searchingFull text searching– Very FastVery Fast– Not transaction safeNot transaction safe

• InnoDB – New in MySQL 4InnoDB – New in MySQL 4– No maximum size (tables can span multiple No maximum size (tables can span multiple

files)files)– Transaction SafeTransaction Safe– Row-level lockingRow-level locking– Foreign key integrity supportForeign key integrity support

Choice of Database Engines (Table types - 2)Choice of Database Engines (Table types - 2)

• Heap Heap – Loaded wholly into memoryLoaded wholly into memory– Extremely fastExtremely fast– Lost if there is a power failure!Lost if there is a power failure!

• OthersOthers– ISAM – deprecated – replaced by MyIsamISAM – deprecated – replaced by MyIsam– BDB – also transaction safeBDB – also transaction safe

66

Using MySQLUsing MySQL

SQLSQL

• Structured Query LanguageStructured Query Language

• Designed for non-expert usersDesigned for non-expert users

• Reads like English – 1Reads like English – 1stst version called version called Structured English Query Language Structured English Query Language = reason some people say “sequel”= reason some people say “sequel”

• Create, Drop, Show, Use, Describe, Create, Drop, Show, Use, Describe, Alter, Insert, Delete, Update, SelectAlter, Insert, Delete, Update, Select

Using MySQLUsing MySQL

• MySQL databases can be accessed MySQL databases can be accessed with a range of tools.with a range of tools.– MYSQL utility programsMYSQL utility programs– Web servers using technologies such as Web servers using technologies such as

PHP, ASP or JSPPHP, ASP or JSP– Programs (using SQL libraries)Programs (using SQL libraries)– Programs like MS-Access and Excel (Via Programs like MS-Access and Excel (Via

ODBC)ODBC)

MySQL ToolsMySQL Tools

• Mysql - best learning tool as code Mysql - best learning tool as code can be reused in PHP and elsewherecan be reused in PHP and elsewhere

• MySQLCC – Windows/Mac/Linux MySQLCC – Windows/Mac/Linux native clientnative client

• PHPmySQL – web based client – PHPmySQL – web based client – included with XAMPPincluded with XAMPP

• Many other 3Many other 3rdrd party tools party tools

MySQL monitorMySQL monitor

• MySQL MonitorMySQL Monitor

Mysql – h <server> -u <user> -p <password>Mysql – h <server> -u <user> -p <password>

-h Servername if not local device-h Servername if not local device

-u username – ‘root’ set up as default-u username – ‘root’ set up as default

-p password – default is no password-p password – default is no password

Mysql –u root –pMysql –u root –p

Each user can have different permissionsEach user can have different permissions

Database toolsDatabase tools

• Create <database>;Create <database>;

• Drop <database>;Drop <database>;

• Show databases;Show databases;

• Use <database>;Use <database>;

• Describe <database>;Describe <database>;

Creating Tables - 1Creating Tables - 1

• Create table <tablename> (table Create table <tablename> (table definition) [Primary Key (<col>) Index definition) [Primary Key (<col>) Index index_name (<col>)[type = index_name (<col>)[type = table_type];table_type];

Create table book (Create table book (title varchar(80),title varchar(80),author varchar(40)author varchar(40)););

Common MySQL Common MySQL String String Data Data types types

– CHAR(length) – fixed-length character data, n CHAR(length) – fixed-length character data, n characters long - Maximum length = 255 characters long - Maximum length = 255 bytesbytes

– VARCHAR(maxlength) – variable length VARCHAR(maxlength) – variable length character data, maximum 255 bytescharacter data, maximum 255 bytes

– LONGTEXT up to 4Gb. LONGTEXT up to 4Gb.

– Others are availableOthers are available– Tables made without the use of VARCHAR are Tables made without the use of VARCHAR are

faster but use more disk spacefaster but use more disk space

Common MySQL Numeric Common MySQL Numeric typestypes

– DECIMAL – general purpose numeric DECIMAL – general purpose numeric data typedata type

– INTEGER types – INT +/ 4 Billion INTEGER types – INT +/ 4 Billion /TINYINT – 1 byte, SMALLINT – 2 bytes…/TINYINT – 1 byte, SMALLINT – 2 bytes…

– FLOAT/DOUBLE – floating pointFLOAT/DOUBLE – floating point

– All numeric types may be SIGNED or All numeric types may be SIGNED or UNSIGNEDUNSIGNED

OthersOthers

• ENUM – Enumerated typeENUM – Enumerated typeFruit enum (‘Apple’ , ’Orange’ , ’Banana’)Fruit enum (‘Apple’ , ’Orange’ , ’Banana’)

• DATE – fixed-length date/time in DATE – fixed-length date/time in YYYY-MM-DD formYYYY-MM-DD form

• DATETIMEDATETIME

• TIMETIME

Column AttributesColumn Attributes

• Auto_incrementAuto_increment

• Default Default ValueValue

• Not NullNot Null

• Primary KeyPrimary Key

• UnsignedUnsigned

• ZerofillZerofill

More Create TableMore Create Table

Create table users (Create table users (

Userid int Userid int not null auto_increment primary key,not null auto_increment primary key,

FirstName varchar(30) FirstName varchar(30) not nullnot null,,

JobTitle varchar 20,JobTitle varchar 20,

Sex enum(‘Male’, ‘Female’),Sex enum(‘Male’, ‘Female’),

Age tinyint Age tinyint unsignedunsigned

))

Type = InnoDBType = InnoDB

;;

Changing and Removing Changing and Removing TablesTables• ALTER TABLE statement allows you to ALTER TABLE statement allows you to

change column specifications:change column specifications:– ALTER TABLE BOOK ALTER TABLE BOOK ADDADD COLUMNCOLUMN (ISBN (ISBN

VARCHAR(15)) [Before/After<col>/First/Last];VARCHAR(15)) [Before/After<col>/First/Last];– Also rename column Also rename column CHANGE CHANGE

<oldcol><newcol><oldcol><newcol>– Drop columns - Drop columns - DROP COLUMN DROP COLUMN <col>,<col>,– Rename table - Rename table - RENAME RENAME <new Name>;<new Name>;

• DROP TABLE statement allows you to delete DROP TABLE statement allows you to delete tables and all their data:tables and all their data:– DROP TABLE CUSTOMERS;DROP TABLE CUSTOMERS;

Info commandsInfo commands

• Show tables;Show tables;

• Describe <tablename>;Describe <tablename>;

• Show index from <tablename>;Show index from <tablename>;

• Show table status;Show table status;

• Show Create table;Show Create table;

Insert StatementInsert Statement

• Adds data to a tableAdds data to a table

• Inserting into a tableInserting into a table– INSERT INTO CUSTOMER VALUES (001, ‘RACC’, INSERT INTO CUSTOMER VALUES (001, ‘RACC’,

‘Parkshot.’, ‘Richmond’, ‘UK’, ‘TW9 4AA’);‘Parkshot.’, ‘Richmond’, ‘UK’, ‘TW9 4AA’);

• Inserting a record that has some null Inserting a record that has some null attributes requires identifying the fields attributes requires identifying the fields that get datathat get data– INSERT INTO PRODUCT (PRODUCT_ID, PRODUCTDESC, INSERT INTO PRODUCT (PRODUCT_ID, PRODUCTDESC,

PRODUCTCOLOUR, PRICE, NO_IN_STOCK) VALUES PRODUCTCOLOUR, PRICE, NO_IN_STOCK) VALUES (1002, ‘Table’, ‘Brown’, 175, 8);(1002, ‘Table’, ‘Brown’, 175, 8);

Delete StatementDelete Statement

• Removes rows from a tableRemoves rows from a table

• Delete certain rowsDelete certain rows– DELETE FROM CUSTOMER WHERE DELETE FROM CUSTOMER WHERE

COUNTRY = ‘France’;COUNTRY = ‘France’;

• Delete all rowsDelete all rows– DELETE FROM CUSTOMER;DELETE FROM CUSTOMER;

Update StatementUpdate Statement

• Modifies data in existing rowsModifies data in existing rows

UPDATE PRODUCT UPDATE PRODUCT SETSET PRICE = 775 WHERE PRICE = 775 WHERE PRODUCT_ID = 7;PRODUCT_ID = 7;

SELECT StatementSELECT Statement• Used for queries on single or multiple tablesUsed for queries on single or multiple tables• Clauses of the SELECT statement:Clauses of the SELECT statement:

– SELECTSELECT• List the columns (and expressions) that should be returned from the queryList the columns (and expressions) that should be returned from the query

– FROMFROM• Indicate the table(s) or view(s) from which data will be obtainedIndicate the table(s) or view(s) from which data will be obtained

– WHEREWHERE• Indicate the conditions under which a row will be included in the resultIndicate the conditions under which a row will be included in the result

– GROUP BYGROUP BY• Indicate categorization of results Indicate categorization of results

– HAVINGHAVING• Indicate the conditions under which a category (group) will be includedIndicate the conditions under which a category (group) will be included

– ORDER BYORDER BY• Sorts the result according to specified criteriaSorts the result according to specified criteria

SELECT ExamplesSELECT Examples

• Select all fields from all recordsSelect all fields from all records

Select * from Customer;Select * from Customer;

• Find products with a price of less than Find products with a price of less than £275£275

SELECT PRODUCT_NAME, PRICE SELECT PRODUCT_NAME, PRICE FROM PRODUCT FROM PRODUCT WHERE PRICE < 275;WHERE PRICE < 275;

SELECT Example SELECT Example Using a FunctionUsing a Function

• Using the COUNT Using the COUNT functionfunction to find totals to find totals

SELECT SELECT COUNT(*)COUNT(*) FROM ORDER_LINE FROM ORDER_LINEWHERE ORDER_ID = 1004;WHERE ORDER_ID = 1004;

SELECT Example – Boolean SELECT Example – Boolean OperatorsOperators

• ANDAND, , OROR, and , and NOTNOT Operators for customizing Operators for customizing conditions in WHERE clauseconditions in WHERE clause

SELECT PRODUCT_DESCRIPTION, PRODUCT_COLOUR, SELECT PRODUCT_DESCRIPTION, PRODUCT_COLOUR, PRICEPRICE

FROM PRODUCTFROM PRODUCT

WHERE (PRODUCT_DESCRIPTION WHERE (PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Desk’Desk’

OROR PRODUCT_DESCRIPTION PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Table’) Table’)

ANDAND PRICE > 300; PRICE > 300;Note: the LIKE operator allows you to compare strings using wildcards. For example, the % wildcard in ‘%Desk’ indicates that all strings that have any number of characters preceding the word “Desk” will be allowed

SELECT Example – SELECT Example – Sorting Results with the ORDER BY Sorting Results with the ORDER BY ClauseClause• Sort the results first by COUNTRY, and Sort the results first by COUNTRY, and

within a country by CUSTOMER_NAMEwithin a country by CUSTOMER_NAME

SELECT CUSTOMER_NAME, CITY, COUNTRYSELECT CUSTOMER_NAME, CITY, COUNTRY

FROM CUSTOMERFROM CUSTOMER

WHERE Country WHERE Country ININ (‘UK’, ‘FR’, ‘DE’, ‘NL’) (‘UK’, ‘FR’, ‘DE’, ‘NL’)

ORDER BY COUNTRY, CUSTOMER_NAME;ORDER BY COUNTRY, CUSTOMER_NAME;

SELECT Example – SELECT Example – Categorizing Results Using the GROUP BY Categorizing Results Using the GROUP BY ClauseClause

SELECT COUNTRY, COUNT(COUNTRY) SELECT COUNTRY, COUNT(COUNTRY)

FROM CUSTOMERFROM CUSTOMER

GROUP BYGROUP BY COUNTRY; COUNTRY;

2929

Advanced SQLAdvanced SQL

ObjectivesObjectives

• Definition of termsDefinition of terms

• Write multiple table SQL queriesWrite multiple table SQL queries

• Define and use two types of joinsDefine and use two types of joins

• Establish referential integrity in SQLEstablish referential integrity in SQL

Processing Multiple Tables – Basic JoinsProcessing Multiple Tables – Basic Joins

• Join – An operation that causes two or more tables with a common Join – An operation that causes two or more tables with a common field to be combined into a single table or view field to be combined into a single table or view

• Computer science makes this very complicatedComputer science makes this very complicated

• If fact it’s quite easyIf fact it’s quite easy

Select employee.name, department.name Select employee.name, department.name from employee, departmentfrom employee, departmentWhere employee.departmentID = department.departmentID;Where employee.departmentID = department.departmentID;

• This is called an Equijoin or Inner join – the joining condition is This is called an Equijoin or Inner join – the joining condition is based on equality between values in the common columns and can based on equality between values in the common columns and can also be written as: also be written as:

Select employee.name, department.name Select employee.name, department.name from employee join/or Inner Join/ or Cross join departmentfrom employee join/or Inner Join/ or Cross join departmentWhere employee.departmentID = department.departmentID;Where employee.departmentID = department.departmentID;

Left and Right joinsLeft and Right joins

• What if we want to join two tables and the matching data is What if we want to join two tables and the matching data is missing from one?missing from one?

Select employee.nameSelect employee.nameFrom employee, assignmentFrom employee, assignmentOn employee.employeeID = Assignment.EmployeeID;On employee.employeeID = Assignment.EmployeeID;

Will only show records where there is a matchWill only show records where there is a match

Select employee.nameSelect employee.nameFrom employee left join assignmentFrom employee left join assignmentOn employee.employeeID = Assignment.EmployeeID;On employee.employeeID = Assignment.EmployeeID;

Will show all records in ‘Left’ Table and their matches (if any)Will show all records in ‘Left’ Table and their matches (if any)

Right joins are simply left joins with the tables listed in the other order!Right joins are simply left joins with the tables listed in the other order!These are also called left and right Outer joinsThese are also called left and right Outer joins

The following slides create tables The following slides create tables for this enterprise data modelfor this enterprise data model

These tables are used in queries that follow

• For each customer who placed an order, what is For each customer who placed an order, what is the customer’s name and order number?the customer’s name and order number?

SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDFROM CUSTOMER, ORDERFROM CUSTOMER, ORDER

WHERE CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID;WHERE CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID;

Join involves multiple tables in FROM clause

Inner Join ExampleInner Join Example

WHERE clause performs the equality check for common columns of the two tables

Results

• List the customer name, ID number, and order List the customer name, ID number, and order number for all customers. Include customer number for all customers. Include customer information even for customers that have not information even for customers that have not placed an orderplaced an order

SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDFROM CUSTOMER, LEFT JOIN ORDERFROM CUSTOMER, LEFT JOIN ORDERON CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID;ON CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID;

Outer Join Example Outer Join Example

LEFT OUTER JOIN syntax with ON keyword instead of WHERE causes customer data to appear even if there is no corresponding order data

• Assemble all information necessary to create an invoice for order Assemble all information necessary to create an invoice for order number 1006number 1006

SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, STATE, SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, STATE, POSTAL_CODE, ORDER.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_NAME, UNIT_PRICE, POSTAL_CODE, ORDER.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_NAME, UNIT_PRICE, (QUANTITY * UNIT_PRICE)(QUANTITY * UNIT_PRICE)

FROM CUSTOMER, ORDER, ORDER_LINE, PRODUCTFROM CUSTOMER, ORDER, ORDER_LINE, PRODUCT

WHERE CUSTOMER.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID WHERE CUSTOMER.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID AND ORDER.ORDER_ID = AND ORDER.ORDER_ID = ORDER_LINE.ORDER_ID ORDER_LINE.ORDER_ID

AND ORDER_LINE.PRODUCT_ID = PRODUCT_PRODUCT_IDAND ORDER_LINE.PRODUCT_ID = PRODUCT_PRODUCT_IDAND ORDER.ORDER_ID = 1006;AND ORDER.ORDER_ID = 1006;

Four tables involved in this join

Multiple Table Join Multiple Table Join ExampleExample

Each pair of tables requires an equality-check condition in the WHERE clause, matching primary keys against foreign keys

Figure 8-2 – Results from a four-table join

From CUSTOMER_T table

From ORDER_T table From PRODUCT_T table

Transaction IntegrityTransaction Integrity• Transaction = A discrete unit of work Transaction = A discrete unit of work

that must be completely processed or that must be completely processed or not processed at allnot processed at all– May involve multiple updatesMay involve multiple updates– If any update fails, then all other updates If any update fails, then all other updates

must be cancelledmust be cancelled

• SQL commands for transactionsSQL commands for transactions– BEGIN TRANSACTION/END TRANSACTIONBEGIN TRANSACTION/END TRANSACTION

• Marks boundaries of a transactionMarks boundaries of a transaction

– COMMITCOMMIT• Makes all updates permanentMakes all updates permanent

– ROLLBACKROLLBACK• Cancels updates since the last COMMITCancels updates since the last COMMIT

Figure 8-5: An SQL Transaction sequence (in pseudocode)

Embedded and Dynamic Embedded and Dynamic SQLSQL

• Embedded SQLEmbedded SQL– Including hard-coded SQL statements in Including hard-coded SQL statements in

a program written in another language a program written in another language such as C or Javasuch as C or Java

• Dynamic SQLDynamic SQL– Ability for an application program to Ability for an application program to

generate SQL code on the fly, as the generate SQL code on the fly, as the application is runningapplication is running