Download presentation
Presentation is loading. Please wait.
Published byAvis Smith Modified over 9 years ago
1
1 Introduction to MySQL & SQL
2
MySQL Relational Database Management System Relational Database Management System Competitors Competitors –Oracle –IBM DB2 –MS SQL-Server –These offer more facilities (better SQL-98 compliance) but MySQL is generally fastest
3
Reasons to use MySQL Price – Free or low cost Price – Free or low cost Stability and speed Stability and speed Ease of use Ease of use Features Features
4
Choice of Database Engines (Table types - 1) Default - MyIsam Default - MyIsam –Tables up to 4GB – also supports merge tables –Max 64 keys per table –Full text searching –Very Fast –Not transaction safe InnoDB – New in MySQL 4 InnoDB – New in MySQL 4 –No maximum size (tables can span multiple files) –Transaction Safe –Row-level locking –Foreign key integrity support
5
Choice of Database Engines (Table types - 2) Heap Heap –Loaded wholly into memory –Extremely fast –Lost if there is a power failure! Others Others –ISAM – deprecated – replaced by MyIsam –BDB – also transaction safe
6
6 Using MySQL
7
SQL Structured Query Language Structured Query Language Designed for non-expert users Designed for non-expert users Reads like English – 1 st version called Structured English Query Language = reason some people say “sequel” Reads like English – 1 st version called Structured English Query Language = reason some people say “sequel” Create, Drop, Show, Use, Describe, Alter, Insert, Delete, Update, Select Create, Drop, Show, Use, Describe, Alter, Insert, Delete, Update, Select
8
Using MySQL MySQL databases can be accessed with a range of tools. MySQL databases can be accessed with a range of tools. –MYSQL utility programs –Web servers using technologies such as PHP, ASP or JSP –Programs (using SQL libraries) –Programs like MS-Access and Excel (Via ODBC)
9
MySQL Tools Mysql - best learning tool as code can be reused in PHP and elsewhere Mysql - best learning tool as code can be reused in PHP and elsewhere MySQLCC – Windows/Mac/Linux native client MySQLCC – Windows/Mac/Linux native client PHPmySQL – web based client – included with XAMPP PHPmySQL – web based client – included with XAMPP Many other 3 rd party tools Many other 3 rd party tools
10
MySQL monitor MySQL Monitor MySQL Monitor Mysql – h -u -p Mysql – h -u -p -h Servername if not local device -u username – ‘root’ set up as default -p password – default is no password Mysql –u root –p Each user can have different permissions
11
Database tools Create ; Create ; Drop ; Drop ; Show databases; Show databases; Use ; Use ; Describe ; Describe ;
12
Creating Tables - 1 Create table (table definition) [Primary Key ( ) Index index_name ( )[type = table_type]; Create table (table definition) [Primary Key ( ) Index index_name ( )[type = table_type]; Create table book ( title varchar(80), author varchar(40) );
13
Common MySQL String Data types –CHAR(length) – fixed-length character data, n characters long - Maximum length = 255 bytes –VARCHAR(maxlength) – variable length character data, maximum 255 bytes –LONGTEXT up to 4Gb. –Others are available –Tables made without the use of VARCHAR are faster but use more disk space
14
Common MySQL Numeric types –DECIMAL – general purpose numeric data type –INTEGER types – INT +/ 4 Billion /TINYINT – 1 byte, SMALLINT – 2 bytes… –FLOAT/DOUBLE – floating point –All numeric types may be SIGNED or UNSIGNED
15
Others ENUM – Enumerated type ENUM – Enumerated type Fruit enum (‘Apple’, ’Orange’, ’Banana’) DATE – fixed-length date/time in YYYY- MM-DD form DATE – fixed-length date/time in YYYY- MM-DD form DATETIME DATETIME TIME TIME
16
Column Attributes Auto_increment Auto_increment Default Value Default Value Not Null Not Null Primary Key Primary Key Unsigned Unsigned Zerofill Zerofill
17
More Create Table Create table users ( Userid int not null auto_increment primary key, FirstName varchar(30) not null, JobTitle varchar 20, Sex enum(‘Male’, ‘Female’), Age tinyint unsigned ) Type = InnoDB ;
18
Changing and Removing Tables ALTER TABLE statement allows you to change column specifications: ALTER TABLE statement allows you to change column specifications: –ALTER TABLE BOOK ADD COLUMN (ISBN VARCHAR(15)) [Before/After /First/Last]; –Also rename column CHANGE –Also rename column CHANGE –Drop columns - DROP COLUMN, –Rename table - RENAME ; DROP TABLE statement allows you to delete tables and all their data: DROP TABLE statement allows you to delete tables and all their data: –DROP TABLE CUSTOMERS;
19
Info commands Show tables; Show tables; Describe ; Describe ; Show index from ; Show index from ; Show table status; Show table status; Show Create table; Show Create table;
20
Insert Statement Adds data to a table Adds data to a table Inserting into a table Inserting into a table –INSERT INTO CUSTOMER VALUES (001, ‘RACC’, ‘Parkshot.’, ‘Richmond’, ‘UK’, ‘TW9 4AA’); Inserting a record that has some null attributes requires identifying the fields that get data Inserting a record that has some null attributes requires identifying the fields that get data –INSERT INTO PRODUCT (PRODUCT_ID, PRODUCTDESC, PRODUCTCOLOUR, PRICE, NO_IN_STOCK) VALUES (1002, ‘Table’, ‘Brown’, 175, 8);
21
Delete Statement Removes rows from a table Removes rows from a table Delete certain rows Delete certain rows –DELETE FROM CUSTOMER WHERE COUNTRY = ‘France’; Delete all rows Delete all rows –DELETE FROM CUSTOMER;
22
Update Statement Modifies data in existing rows Modifies data in existing rows UPDATE PRODUCT SET PRICE = 775 WHERE PRODUCT_ID = 7;
23
SELECT Statement Used for queries on single or multiple tables Used for queries on single or multiple tables Clauses of the SELECT statement: Clauses of the SELECT statement: –SELECT List the columns (and expressions) that should be returned from the query List the columns (and expressions) that should be returned from the query –FROM Indicate the table(s) or view(s) from which data will be obtained Indicate the table(s) or view(s) from which data will be obtained –WHERE Indicate the conditions under which a row will be included in the result Indicate the conditions under which a row will be included in the result –GROUP BY Indicate categorization of results Indicate categorization of results –HAVING Indicate the conditions under which a category (group) will be included Indicate the conditions under which a category (group) will be included –ORDER BY Sorts the result according to specified criteria Sorts the result according to specified criteria
24
SELECT Examples Select all fields from all records Select all fields from all records Select * from Customer; Select * from Customer; Find products with a price of less than £275 Find products with a price of less than £275 SELECT PRODUCT_NAME, PRICE FROM PRODUCT WHERE PRICE < 275;
25
SELECT Example Using a Function Using the COUNT function to find totals Using the COUNT function to find totals SELECT COUNT(*) FROM ORDER_LINE WHERE ORDER_ID = 1004;
26
SELECT Example – Boolean Operators AND, OR, and NOT Operators for customizing conditions in WHERE clause AND, OR, and NOT Operators for customizing conditions in WHERE clause SELECT PRODUCT_DESCRIPTION, PRODUCT_COLOUR, PRICE FROM PRODUCT WHERE (PRODUCT_DESCRIPTION LIKE ‘%Desk’ OR PRODUCT_DESCRIPTION LIKE ‘%Table’) AND 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
27
SELECT Example – Sorting Results with the ORDER BY Clause Sort the results first by COUNTRY, and within a country by CUSTOMER_NAME Sort the results first by COUNTRY, and within a country by CUSTOMER_NAME SELECT CUSTOMER_NAME, CITY, COUNTRY FROM CUSTOMER WHERE Country IN (‘UK’, ‘FR’, ‘DE’, ‘NL’) ORDER BY COUNTRY, CUSTOMER_NAME;
28
SELECT Example – Categorizing Results Using the GROUP BY Clause SELECT COUNTRY, COUNT(COUNTRY) FROM CUSTOMER GROUP BY COUNTRY;
29
29 Advanced SQL
30
Objectives Definition of terms Definition of terms Write multiple table SQL queries Write multiple table SQL queries Define and use two types of joins Define and use two types of joins Establish referential integrity in SQL Establish referential integrity in SQL
31
Processing Multiple Tables – Basic Joins Join – An operation that causes two or more tables with a common field to be combined into a single table or view Join – An operation that causes two or more tables with a common field to be combined into a single table or view Computer science makes this very complicated Computer science makes this very complicated If fact it’s quite easy If fact it’s quite easy Select employee.name, department.name from employee, department Where employee.departmentID = department.departmentID; This is called an Equijoin or Inner join – the joining condition is based on equality between values in the common columns and can also be written as: This is called an Equijoin or Inner join – the joining condition is based on equality between values in the common columns and can also be written as: Select employee.name, department.name from employee join/or Inner Join/ or Cross join department Where employee.departmentID = department.departmentID;
32
Left and Right joins What if we want to join two tables and the matching data is missing from one? What if we want to join two tables and the matching data is missing from one? Select employee.name From employee, assignment On employee.employeeID = Assignment.EmployeeID; Will only show records where there is a match Select employee.name From employee left join assignment On employee.employeeID = Assignment.EmployeeID; 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! These are also called left and right Outer joins
33
The following slides create tables for this enterprise data model
34
These tables are used in queries that follow
35
For each customer who placed an order, what is the customer’s name and order number? For each customer who placed an order, what is the customer’s name and order number? SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID FROM CUSTOMER, ORDER WHERE CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID; Join involves multiple tables in FROM clause Inner Join Example WHERE clause performs the equality check for common columns of the two tables
36
Results
37
List the customer name, ID number, and order number for all customers. Include customer information even for customers that have not placed an order List the customer name, ID number, and order number for all customers. Include customer information even for customers that have not placed an order SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID FROM CUSTOMER, LEFT JOIN ORDER ON CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID; 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
38
Assemble all information necessary to create an invoice for order number 1006 Assemble all information necessary to create an invoice for order number 1006 SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, STATE, POSTAL_CODE, ORDER.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_NAME, UNIT_PRICE, (QUANTITY * UNIT_PRICE) FROM CUSTOMER, ORDER, ORDER_LINE, PRODUCT WHERE CUSTOMER.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID AND ORDER.ORDER_ID = ORDER_LINE.ORDER_ID AND ORDER_LINE.PRODUCT_ID = PRODUCT_PRODUCT_ID AND ORDER.ORDER_ID = 1006; Four tables involved in this join Multiple Table Join Example Each pair of tables requires an equality-check condition in the WHERE clause, matching primary keys against foreign keys
39
Figure 8-2 – Results from a four-table join From CUSTOMER_T table From ORDER_T table From PRODUCT_T table
40
Transaction Integrity Transaction = A discrete unit of work that must be completely processed or not processed at all Transaction = A discrete unit of work that must be completely processed or not processed at all –May involve multiple updates –If any update fails, then all other updates must be cancelled SQL commands for transactions SQL commands for transactions –BEGIN TRANSACTION/END TRANSACTION Marks boundaries of a transaction Marks boundaries of a transaction –COMMIT Makes all updates permanent Makes all updates permanent –ROLLBACK Cancels updates since the last COMMIT Cancels updates since the last COMMIT
41
Figure 8-5: An SQL Transaction sequence (in pseudocode)
42
Embedded and Dynamic SQL Embedded SQL Embedded SQL –Including hard-coded SQL statements in a program written in another language such as C or Java Dynamic SQL Dynamic SQL –Ability for an application program to generate SQL code on the fly, as the application is running
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.