66
mySQL and Relational Databases By Jeff Smith

mySQL and Relational Databases

Embed Size (px)

Citation preview

Page 1: mySQL and Relational Databases

mySQL and Relational Databases

By Jeff Smith

Page 2: mySQL and Relational Databases

mySQL and Relational Databases

What is a Database?

DatabaseDatabase An organized collection of data grouped by An organized collection of data grouped by

common attributescommon attributes A collection of tablesA collection of tables

Page 3: mySQL and Relational Databases

What is a Table ?

TableTable Rows (records)Rows (records) Columns (fields)Columns (fields) Field valueField value

A field value is the intersection of a row and a A field value is the intersection of a row and a columncolumn

A USER table could store user information while a A USER table could store user information while a table called MODEL might store information about table called MODEL might store information about weather modelsweather models

Page 4: mySQL and Relational Databases

Table Concepts and Terms -1

A table is divided into rows, and each A table is divided into rows, and each rowrow is often is often referred to as a referred to as a RecordRecord. So if you look up your . So if you look up your information in a telephone book you are reviewing information in a telephone book you are reviewing your record. Each “row” contains several pieces of your record. Each “row” contains several pieces of information: your name, address, and phone information: your name, address, and phone number.number.

Each Each columncolumn in a table is a category of information in a table is a category of information referred to as a referred to as a FieldField. In a telephone book, one . In a telephone book, one column might be the names, another might be the column might be the names, another might be the phone numbers. phone numbers.

A single item of data, such as a single phone A single item of data, such as a single phone number, is called a number, is called a data valuedata value. .

Page 5: mySQL and Relational Databases

Table Concepts and Terms -2Table: PhoneBookColumns or Fields: Company, Address, City, State, Zip, Phone

Page 6: mySQL and Relational Databases

Keys of a Table -1 Primary keyPrimary key

Unique identifier which identifies a rowUnique identifier which identifies a row Foreign keyForeign key

A primary key in another table - used to lookup A primary key in another table - used to lookup information (provide referential integrity)information (provide referential integrity)

Example:Example: USERS and MODEL_GROUP tablesUSERS and MODEL_GROUP tables Each has primary key – USER_ID and Each has primary key – USER_ID and

MODEL_GROUP_IDMODEL_GROUP_ID USER_ID is also stored in the MODEL_GROUP table to USER_ID is also stored in the MODEL_GROUP table to

relate this model group to its user – USER_ID is a relate this model group to its user – USER_ID is a foreign key in the MODEL_GROUP tableforeign key in the MODEL_GROUP table

Page 7: mySQL and Relational Databases

Keys of a Table -2

USERUSER

--------------------------------------

USER_ID (PK)USER_ID (PK)

USER_NAMEUSER_NAME

PASSWORDPASSWORD

FIRST_NAMEFIRST_NAME

LAST_NAMELAST_NAME

MODEL_GROUP MODEL_GROUP

--------------------------------------------------------------------

MODEL_GROUP_ID (PK)MODEL_GROUP_ID (PK)

USER_ID (FK)USER_ID (FK)

MODEL_GROUP_NAMEMODEL_GROUP_NAME

Page 8: mySQL and Relational Databases

Indexes (Indicies)

Primary IndexPrimary Index Unique key for each recordUnique key for each record Used to enforce primary keysUsed to enforce primary keys The primary key can also be composite (comprised of The primary key can also be composite (comprised of

more than one table column)more than one table column) Secondary IndexesSecondary Indexes

Used to speed up ordering and searchingUsed to speed up ordering and searching For example, if you had thousands of users in the For example, if you had thousands of users in the

USER table and frequently searched for users by their USER table and frequently searched for users by their last name, you might add a secondary index to last last name, you might add a secondary index to last name in order to speed up these searches.name in order to speed up these searches.

Page 9: mySQL and Relational Databases

Referential and Domain Integrity Referential IntegrityReferential Integrity

Where a field or group of fields in one table must refer to the Where a field or group of fields in one table must refer to the key in another tablekey in another table

E.g. All models could be required to have a user. If you tried E.g. All models could be required to have a user. If you tried to enter a model record with a bogus USER_ID, the to enter a model record with a bogus USER_ID, the database would refuse to accept the record (and generate database would refuse to accept the record (and generate an error)an error)

Domain IntegrityDomain Integrity Ensuring field values are within a valid domainEnsuring field values are within a valid domain

E.g. start_year field in model table must be > 1950E.g. start_year field in model table must be > 1950

Some databases allow you to define integrity rules in Some databases allow you to define integrity rules in the database - engine then rejects invalid recordsthe database - engine then rejects invalid records

mySQL 5 supports this capabilitymySQL 5 supports this capability

Page 10: mySQL and Relational Databases

About mySQL Open source! Here’s some mySQL hype:Open source! Here’s some mySQL hype:

The MySQL database server is the world's most The MySQL database server is the world's most popular open source database. popular open source database.

Over ten million installations of MySQLOver ten million installations of MySQL Used by The Associated Press, Google, NASA, etc.Used by The Associated Press, Google, NASA, etc. Runs on over 20 platforms (including Linux, Windows) Runs on over 20 platforms (including Linux, Windows) Download it for free from the web:Download it for free from the web:

http://www.mysql.com/http://www.mysql.com/

Can either manage mySQL from a command line Can either manage mySQL from a command line interface or from nice and free GUI tools (mySQL interface or from nice and free GUI tools (mySQL Query Browser and mySQL Administrator)Query Browser and mySQL Administrator)

Page 11: mySQL and Relational Databases

Setting up a mySQL Database - 1

Remember, database is a collection of tablesRemember, database is a collection of tables You must first create database before you You must first create database before you

can add tables to itcan add tables to it The latest version of mySQL is version 5The latest version of mySQL is version 5 With mySQL, you can either create a With mySQL, you can either create a

database from the command line or by using database from the command line or by using a GUI tool like MySQL Administratora GUI tool like MySQL Administrator

Page 12: mySQL and Relational Databases

MySQL Table Engines InnoDBInnoDB

Most popular transactional storage engine for MySQLMost popular transactional storage engine for MySQL Fullly supports standard SQL isolation levels for ACID-Fullly supports standard SQL isolation levels for ACID-

compliant transaction processing (ie. commit, rollback)compliant transaction processing (ie. commit, rollback) Provides row level lockingProvides row level locking

MyISAM MyISAM Default storage engineDefault storage engine No transaction support (no commit, rollback)No transaction support (no commit, rollback) Faster reads, good choice for table where you select Faster reads, good choice for table where you select

from it a lot, but don’t need to update itfrom it a lot, but don’t need to update it Doesn’t support row level locking (so slower if you Doesn’t support row level locking (so slower if you

modify the data a lot)modify the data a lot) Also supports 8 other storage enginesAlso supports 8 other storage engines Can mix these engines within a single databaseCan mix these engines within a single database

Page 13: mySQL and Relational Databases

MySQL Data Types Common data typesCommon data types

intint doubledouble decimaldecimal varchar(n)varchar(n) char(n)char(n) enumenum datedate datetimedatetime timestamptimestamp

Page 14: mySQL and Relational Databases

Setting Up Database With A ScriptDROP DATABASE IF EXISTS jeff_db;DROP DATABASE IF EXISTS jeff_db;CREATE DATABASE IF NOT EXISTS jeff_db;CREATE DATABASE IF NOT EXISTS jeff_db;

CREATE TABLE USER CREATE TABLE USER (( USER_ID USER_ID int NOT NULL auto_increment PRIMARY KEY,int NOT NULL auto_increment PRIMARY KEY, USERNAME USERNAME varchar(20) NOT NULL,varchar(20) NOT NULL, PASSWORD PASSWORD varchar(20) NOT NULL,varchar(20) NOT NULL, EMAILEMAIL varchar(100),varchar(100), LAST_ACCESS datetime, LAST_ACCESS datetime, UNIQUE KEY LOGIN (USERNAME, PASSWORD)UNIQUE KEY LOGIN (USERNAME, PASSWORD)) ) ENGINE=InnoDB;ENGINE=InnoDB;

# Table structure for table MODEL_GROUP# Table structure for table MODEL_GROUPCREATE TABLE MODEL_GROUPCREATE TABLE MODEL_GROUP(( MODEL_GROUP_ID MODEL_GROUP_ID int NOT NULL auto_increment, int NOT NULL auto_increment, MODEL_GROUP_NAME varchar(20) NOT NULL,MODEL_GROUP_NAME varchar(20) NOT NULL, USER_ID USER_ID int, int, TYPETYPE enum(‘A’, ‘B’) default ‘A’, enum(‘A’, ‘B’) default ‘A’, FOREIGN KEY (USER_ID) REFERENCES USER(USER_ID)FOREIGN KEY (USER_ID) REFERENCES USER(USER_ID)

Page 15: mySQL and Relational Databases
Page 16: mySQL and Relational Databases

Setting up a Database - 3 You can run this script from a command line or a GUIYou can run this script from a command line or a GUI

Page 17: mySQL and Relational Databases

Basic SQL SQL stands for Structured Query Language. It SQL stands for Structured Query Language. It

is a fairly standard way to communicate with is a fairly standard way to communicate with relational databases such as mySQL, relational databases such as mySQL, Postgres, Oracle, MS SQL Server, etc.Postgres, Oracle, MS SQL Server, etc.

There are four common SQL commands:There are four common SQL commands: SELECT -retrieves the specified recordsSELECT -retrieves the specified records INSERT -adds a new row (or record)INSERT -adds a new row (or record) UPDATE -changes values in the specified row(s)UPDATE -changes values in the specified row(s) DELETE -removes the specified rowsDELETE -removes the specified rows

Page 18: mySQL and Relational Databases

Basic SQL, SELECT statement -1 Select statements generally retrieve data from Select statements generally retrieve data from

one or more database tables.one or more database tables.

SELECT SELECT column_namescolumn_names

FROM FROM table_namestable_names

[ WHERE [ WHERE search_conditionsearch_condition ] ]

[ GROUP BY [ GROUP BY group_expressiongroup_expression ] [HAVING ] [HAVING conditioncondition]]

[ ORDER BY [ ORDER BY order_conditionorder_condition [ ASC | DESC ] ] [ ASC | DESC ] ]

Note: The statements in square brackets are optional.Note: The statements in square brackets are optional.

Page 19: mySQL and Relational Databases

Basic SQL, SELECT statement -2 For example, to select the first name and last name of For example, to select the first name and last name of

user number 122:user number 122:

SELECT FirstName, LastNameSELECT FirstName, LastName

FROM UsersFROM Users

WHERE UserID = 122WHERE UserID = 122

Result:Result:

FIRSTNAME LASTNAMEFIRSTNAME LASTNAME

Jeff SmithJeff Smith

Page 20: mySQL and Relational Databases

Basic SQL, SELECT statement -3 For example, to select all the fields for a particular user:For example, to select all the fields for a particular user:

SELECT SELECT **

FROM FROM UsersUsers

WHERE UserName = ‘jssmith’WHERE UserName = ‘jssmith’

Result:Result:

USERID USERNAME PASSWORD FIRSTNAME LASTNAMEUSERID USERNAME PASSWORD FIRSTNAME LASTNAME

122 jssmith password Jeff Smith122 jssmith password Jeff Smith

Page 21: mySQL and Relational Databases

Basic SQL, SELECT statement -4 You can order the results of your SELECT statement with You can order the results of your SELECT statement with

the ORDER BY clausethe ORDER BY clause

SELECT * SELECT * FROM userFROM userWHERE userid > 120 AND userid < 135WHERE userid > 120 AND userid < 135ORDER BY lastname DESCORDER BY lastname DESC

Result:Result:

USERID USERNAME PASSWORD FIRSTNAME USERID USERNAME PASSWORD FIRSTNAME LASTNAMELASTNAME121 kzeller tree13 Kathy 121 kzeller tree13 Kathy ZellerZeller122 jssmith password Jeff 122 jssmith password Jeff SmithSmith134 tarroyo apple01 Thomas 134 tarroyo apple01 Thomas ArroyoArroyo

Page 22: mySQL and Relational Databases

Basic SQL, SELECT statement -5 You can also You can also joinjoin tables with your search criteria. For tables with your search criteria. For

example, to find all the model groups for user jssmith:example, to find all the model groups for user jssmith:

SELECT model_group.*SELECT model_group.*

FROM model_group, userFROM model_group, user

WHERE user.username = ‘jssmith’WHERE user.username = ‘jssmith’

AND user.user_id = model_group.user_idAND user.user_id = model_group.user_id

Result:Result:

MODEL_GROUP_ID USER_ID MODEL_GROUP_NAMEMODEL_GROUP_ID USER_ID MODEL_GROUP_NAME

11 122 Jeff’s Ensemble11 122 Jeff’s Ensemble

Page 23: mySQL and Relational Databases

Basic SQL, SELECT statement -6 Sometimes SQL statements can get verbose. As a Sometimes SQL statements can get verbose. As a

shorthand, you can specify aliases for the table names.shorthand, you can specify aliases for the table names.

SELECT MG.*SELECT MG.*

FROM model_group FROM model_group MGMG, user , user UU

WHERE U.username = ‘jssmith’WHERE U.username = ‘jssmith’

AND U.user_id = MG.user_idAND U.user_id = MG.user_id

Result:Result:

MODEL_GROUP_ID USER_ID MODEL_GROUP_NAMEMODEL_GROUP_ID USER_ID MODEL_GROUP_NAME

11 122 Jeff’s Ensemble11 122 Jeff’s Ensemble

Page 24: mySQL and Relational Databases

Basic SQL, INSERT statement -1 Insert statements insert data into a tableInsert statements insert data into a table

INSERT INTO INSERT INTO table_nametable_name((column_namescolumn_names) ) VALUES(VALUES(value_listvalue_list) )

For example:For example:

INSERT INTO USER(username, password)INSERT INTO USER(username, password)

VALUES (‘jssmith’, ‘password’)VALUES (‘jssmith’, ‘password’)

Page 25: mySQL and Relational Databases

Basic SQL, INSERT statement -2 You can also combine an INSERT with a You can also combine an INSERT with a

SELECTSELECT

For example:For example:

INSERT INTO USER(username, password)INSERT INTO USER(username, password)

SELECT OU.username, OU.password SELECT OU.username, OU.password

FROM OTHER_USER OU FROM OTHER_USER OU

WHERE OU.USER_ID = 1WHERE OU.USER_ID = 1

Page 26: mySQL and Relational Databases

Basic SQL, UPDATE statement An update statement updates (changes) an existing An update statement updates (changes) an existing

record (row) in a tablerecord (row) in a table

UPDATE UPDATE table_nametable_name SET SET column_name1=value1, ... , column_name1=value1, ... , column_nameN=valueNcolumn_nameN=valueN [ WHERE [ WHERE search_conditionsearch_condition ] ]

For example:For example:

UPDATE model_groupUPDATE model_groupSET model_group_name = ‘my ensemble’SET model_group_name = ‘my ensemble’WHERE model_group_id = 134WHERE model_group_id = 134

Page 27: mySQL and Relational Databases

Basic SQL, DELETE statement Delete statement remove data from a tableDelete statement remove data from a table

DELETE FROM table_nameDELETE FROM table_name

[ WHERE [ WHERE search_conditionsearch_condition ] ]

For example:For example:

DELETE FROM model_groupDELETE FROM model_group

WHERE model_group_id = 134WHERE model_group_id = 134

Page 28: mySQL and Relational Databases

Common MySQL Commands -1 use dbName (e.g. use my_database)use dbName (e.g. use my_database)

Subsequent commands apply to this databaseSubsequent commands apply to this database show databases (lists databases)show databases (lists databases) show tables (lists tables)show tables (lists tables)

Generates listing of all tablesGenerates listing of all tables describe tableName (e.g. describe USER)describe tableName (e.g. describe USER)

Describes the table, listing column names, data types, Describes the table, listing column names, data types, etc.etc.

drop database dbName (deletes entire database)drop database dbName (deletes entire database) drop table tableName (e.g. drop table USER)drop table tableName (e.g. drop table USER)

Page 29: mySQL and Relational Databases

Common MySQL Commands -2 create tablecreate table [mysql dir]/bin/mysql -h hostname -u root –p[mysql dir]/bin/mysql -h hostname -u root –p

Logs you into a database from command lineLogs you into a database from command line

mysql –h 12.123.1.12 –u root –pmysql –h 12.123.1.12 –u root –p(logs you into mysql running at that IP address,(logs you into mysql running at that IP address,as user “root”, will prompt you for the password)as user “root”, will prompt you for the password)

mysql –u john –pmysql –u john –p(logs you into local mysql as user “john”)(logs you into local mysql as user “john”)

Page 30: mySQL and Relational Databases

Common MySQL Commands -3

Delete a column.alter table [table name] drop column [column name];

Add a new column to db.alter table [table name] add column [new column name] varchar (20);

Change column name.alter table [table name] change [old column name] [new column name] varchar (50);

Make a unique column so you get no dupes.

alter table [table name] add unique ([column name]);

Make a column bigger.alter table [table name] modify [column name] VARCHAR(3);

Delete unique from table.alter table [table name] drop index [colmn name];

Page 31: mySQL and Relational Databases

Summary SQL is a simple, reliable, and standard way to SQL is a simple, reliable, and standard way to

save and retrieve informationsave and retrieve information mySQL is open source (basically free for non-mySQL is open source (basically free for non-

commercial uses)commercial uses) mySQL supports Windows, UNIX, Linux, etc. mySQL supports Windows, UNIX, Linux, etc.

and so has widespread supportand so has widespread support mySQL is mature and stablemySQL is mature and stable There are some fairly slick tools to use with There are some fairly slick tools to use with

mySQL (notably MySQL Administrator, Query mySQL (notably MySQL Administrator, Query Browser, and Squirrel SQL Client)Browser, and Squirrel SQL Client)

Page 32: mySQL and Relational Databases

Squirrel SQL Client Java GUI that can be installed without admin Java GUI that can be installed without admin

privilegesprivileges Cross platform compatible (Java, of course)Cross platform compatible (Java, of course) It is open source (free) It is open source (free) Can download it from SourceForge.netCan download it from SourceForge.net

Download from here:Download from here:

http://squirrel-sql.sourceforge.net/http://squirrel-sql.sourceforge.net/

Page 33: mySQL and Relational Databases

Squirrel SQL Client Installation Downloading the JAR file (note that IE might Downloading the JAR file (note that IE might

rename the file .zip—if it does, just rename rename the file .zip—if it does, just rename it .jar) it .jar)

Run the JAR file:Run the JAR file:

java –jar squirrel-sql-2.4-install.jarjava –jar squirrel-sql-2.4-install.jar

(After a few seconds, the installation(After a few seconds, the installation

program will start running)program will start running)

Page 34: mySQL and Relational Databases

Squirrel SQL Client Installation -1 You may not have permission to install the You may not have permission to install the

program under C:\Program Filesprogram under C:\Program Files

Page 35: mySQL and Relational Databases

Squirrel SQL Client Installation -2 Select the optional MySQL plugin optionSelect the optional MySQL plugin option

Page 36: mySQL and Relational Databases

Squirrel SQL Client Installation -3 Add shortcuts to the desktopAdd shortcuts to the desktop

Page 37: mySQL and Relational Databases

Squirrel SQL Client Installation -4 Double click on the desktop iconDouble click on the desktop icon If you get a “main class not found” type error, If you get a “main class not found” type error,

go to the “Squirrel SQL Client” directory and go to the “Squirrel SQL Client” directory and run the following commandrun the following command

java -jar -Xmx256m squirrel-sql.jarjava -jar -Xmx256m squirrel-sql.jar

Page 38: mySQL and Relational Databases

Squirrel SQL Client Installation -5 When the program is up and running, select When the program is up and running, select

the MySQL option in the left boxthe MySQL option in the left box

Page 39: mySQL and Relational Databases

Squirrel SQL Client Installation -6 Click on the Extra Class Path tab and then Click on the Extra Class Path tab and then

click on the Add button. Select the mysql jarclick on the Add button. Select the mysql jar

Page 40: mySQL and Relational Databases

Squirrel SQL Client Installation -7 Click on the + to add a new alias to your Click on the + to add a new alias to your

mySQL databasemySQL database

Page 41: mySQL and Relational Databases

Squirrel SQL Client Installation -8 Add your alias. An alias basically stores connection Add your alias. An alias basically stores connection

information to connect to a database. An IP address information to connect to a database. An IP address other than localhost connects you to remote mySQLother than localhost connects you to remote mySQL Instructor IP address is 140.172.8.164Instructor IP address is 140.172.8.164

Page 42: mySQL and Relational Databases

Squirrel SQL Client Installation -9 If you get an error message like this, it If you get an error message like this, it

probably means mySQL isn’t runningprobably means mySQL isn’t running

Page 43: mySQL and Relational Databases

Squirrel SQL Client Installation -10 If you connect, you’ll see a screen like thisIf you connect, you’ll see a screen like this

Page 44: mySQL and Relational Databases

Squirrel SQL Client Installation -11 Click on the SQL tab to type in your SQLClick on the SQL tab to type in your SQL

Page 45: mySQL and Relational Databases

WHERE Clause Can be quite complex with AND and OR Can be quite complex with AND and OR

statementsstatements Can include LIKE clause to do wildcard Can include LIKE clause to do wildcard

matches (LIKE ‘Sm%’ or LIKE ‘%M’)matches (LIKE ‘Sm%’ or LIKE ‘%M’)

SELECT * SELECT * FROM employeeFROM employeeWHERE NAME LIKE ‘S%’WHERE NAME LIKE ‘S%’AND (SALARY < 20000 OR SALARY >= 100000)AND (SALARY < 20000 OR SALARY >= 100000)

Select employees whose names start with S and whoseSelect employees whose names start with S and whosesalary is less than 20k or greater than or equal to 100ksalary is less than 20k or greater than or equal to 100k

Page 46: mySQL and Relational Databases

Selecting the COUNT Sometimes you want to select the count of Sometimes you want to select the count of

rows that match the given constraintsrows that match the given constraintsSELECT COUNT(*) SELECT COUNT(*)

FROM employeeFROM employee

WHERE NAME LIKE ‘%TH’WHERE NAME LIKE ‘%TH’

Select the number of employees whose names end withSelect the number of employees whose names end with

the letters ‘TH’the letters ‘TH’

Page 47: mySQL and Relational Databases

Selecting the MIN or MAX Sometimes you want to select the max or min Sometimes you want to select the max or min

value for a field in a given tablevalue for a field in a given table

SELECT MAX(salary) SELECT MAX(salary)

FROM employeeFROM employee

WHERE dept_no = 22WHERE dept_no = 22

Select the highest salary or all employees in dept. 22Select the highest salary or all employees in dept. 22

Page 48: mySQL and Relational Databases

Selecting the SUM Sometimes you want to select the sum of field Sometimes you want to select the sum of field

for a field in a given tablefor a field in a given table

SELECT SUM(salary) SELECT SUM(salary)

FROM employeeFROM employee

WHERE dept_no = 22WHERE dept_no = 22

Select the sum of all salaries for employees in dept. 22Select the sum of all salaries for employees in dept. 22

Page 49: mySQL and Relational Databases

Joining Tables Sometimes the information you want is Sometimes the information you want is

scattered in more than one tablescattered in more than one table You can join tables in a SELECT statementYou can join tables in a SELECT statement

SELECT E.name, E.salary, D.dept_name SELECT E.name, E.salary, D.dept_name FROM employee E, department DFROM employee E, department DWHERE WHERE E.dept_no = D.dept_noE.dept_no = D.dept_no

Select the employee name, salary and department nameSelect the employee name, salary and department namefor all employeesfor all employees

The join condition here is E.dept_no = D.dept_noThe join condition here is E.dept_no = D.dept_no

Page 50: mySQL and Relational Databases

Sub Queries -1 You can imbed sub queries into your WHERE You can imbed sub queries into your WHERE

clause to create sophisticated constraintsclause to create sophisticated constraints Sub queries can be correlated or non-Sub queries can be correlated or non-

correlatedcorrelated A correlated sub query refers to a column from a A correlated sub query refers to a column from a

table in the parent query table in the parent query A non-correlated sub query does notA non-correlated sub query does not

Page 51: mySQL and Relational Databases

Sub Queries -1 Non-correlated sub query exampleNon-correlated sub query example

SELECT name FROM employee ESELECT name FROM employee E

WHERE E.dept_no = (SELECT dept_no FROM employeeWHERE E.dept_no = (SELECT dept_no FROM employee

WHERE name = 'Zirsky')WHERE name = 'Zirsky')

This selects the names of all the people who work in the sameThis selects the names of all the people who work in the same

department as ‘Zirsky’department as ‘Zirsky’

This sub query must return a single row (or no rows) since theThis sub query must return a single row (or no rows) since the

Comparator is an ‘=‘ (equals sign). If there are two ‘Zirsky’s,Comparator is an ‘=‘ (equals sign). If there are two ‘Zirsky’s,

you’ll get a SQL erroryou’ll get a SQL error

Page 52: mySQL and Relational Databases

Sub Queries -2 A sub query can also return a set of rows A sub query can also return a set of rows

(instead of a single row)(instead of a single row) To do this, use ‘IN’ or ‘NOT IN’To do this, use ‘IN’ or ‘NOT IN’

SELECT name FROM employee ESELECT name FROM employee E

WHERE E.dept_no IN (SELECT dept_no FROM employeeWHERE E.dept_no IN (SELECT dept_no FROM employee

WHERE name = 'Zirsky‘WHERE name = 'Zirsky‘

OR name = ‘Thompson’)OR name = ‘Thompson’)

This selects the names of all the people who work in the sameThis selects the names of all the people who work in the same

department as ‘Zirsky’ or ‘Thompson’department as ‘Zirsky’ or ‘Thompson’

Page 53: mySQL and Relational Databases

Correlated Sub Queries -2 NOT IN sub query exampleNOT IN sub query example

SELECT name FROM employee ESELECT name FROM employee E

WHERE E.employee_id NOT IN WHERE E.employee_id NOT IN

(SELECT employee_id FROM benefits)(SELECT employee_id FROM benefits)

This selects the names of all the people who are not in theThis selects the names of all the people who are not in the

benefits table (they have no benefits)benefits table (they have no benefits)

Page 54: mySQL and Relational Databases

Aggregate Selects (GROUP BY) -1 You can aggregate information (e.g. sub total it) in your select You can aggregate information (e.g. sub total it) in your select

statements by using GROUP BY in conjunction with COUNT, statements by using GROUP BY in conjunction with COUNT, MAX, MIN or SUMMAX, MIN or SUM

Since aggregate functions (like MAX) return the aggregate of all Since aggregate functions (like MAX) return the aggregate of all column values every time they are called, the GROUP BY clause column values every time they are called, the GROUP BY clause enables you to find the aggregate for individual groups (i.e. enables you to find the aggregate for individual groups (i.e. subtotal)subtotal)

SELECT count(*), E.nameSELECT count(*), E.name

FROM employee E, doctor_visits DVFROM employee E, doctor_visits DV

WHERE E.emp_id = DV.emp_idWHERE E.emp_id = DV.emp_id

GROUP BY E.nameGROUP BY E.name

This selects the employee names and number of doctor visitsThis selects the employee names and number of doctor visits

they’ve had. For examplethey’ve had. For example

4 John Doe4 John Doe

2 Maggie Smith2 Maggie Smith

Page 55: mySQL and Relational Databases

Aggregate Selects (GROUP BY) -2 You can aggregate by COUNT, SUM, MIN, or You can aggregate by COUNT, SUM, MIN, or

MAXMAX

SELECT count(*), E.nameSELECT count(*), E.name

FROM employee E, doctor_visits DVFROM employee E, doctor_visits DV

WHERE E.emp_id = DV.emp_idWHERE E.emp_id = DV.emp_id

GROUP BY E.nameGROUP BY E.name

This selects the employee names and number of doctor visitsThis selects the employee names and number of doctor visits

they’ve had. For examplethey’ve had. For example

4 John Doe4 John Doe

2 Maggie Smith2 Maggie Smith

3 Tom Jones3 Tom Jones

Page 56: mySQL and Relational Databases

Aggregate Selects (GROUP BY) -3 You can add a HAVING clause to add a You can add a HAVING clause to add a

further constraint to the grouping conditionfurther constraint to the grouping condition

SELECT count(E.name), E.nameSELECT count(E.name), E.name

FROM employee E, doctor_visits DVFROM employee E, doctor_visits DV

WHERE E.emp_id = DV.emp_idWHERE E.emp_id = DV.emp_id

GROUP BY E.nameGROUP BY E.name

HAVING (COUNT(E.name) > 2)HAVING (COUNT(E.name) > 2)

This selects the employee names and number of doctor visitsThis selects the employee names and number of doctor visits

they’ve had IF they’ve had more than 2 visits. For examplethey’ve had IF they’ve had more than 2 visits. For example

4 John Doe4 John Doe

3 Tom Jones3 Tom Jones

Page 57: mySQL and Relational Databases

Outer Joins -1 Sometimes you want to select fields from multiple tables Sometimes you want to select fields from multiple tables

with a join condition, and even if the joined field is null in with a join condition, and even if the joined field is null in one of the tables, you want to return the data—this is an one of the tables, you want to return the data—this is an OUTER JOINOUTER JOIN

A LEFT OUTER JOIN returns all the rows that an inner A LEFT OUTER JOIN returns all the rows that an inner join returns plus one row for each of the other rows in join returns plus one row for each of the other rows in the first table that did not have a match in the second the first table that did not have a match in the second tabletable

A RIGHT OUTER JOIN returns all the rows that an inner A RIGHT OUTER JOIN returns all the rows that an inner join returns plus one row for each of the other rows in join returns plus one row for each of the other rows in the second table that did not have a match in the first the second table that did not have a match in the first table. table.

A FULL OUTER JOIN acts like the combination of a A FULL OUTER JOIN acts like the combination of a LEFT and RIGHT outer join LEFT and RIGHT outer join

Page 58: mySQL and Relational Databases

Outer Joins -2 The LEFT OUTER JOIN is the most commonThe LEFT OUTER JOIN is the most common

SELECT E.nameSELECT E.name

FROM employee E FROM employee E LEFT OUTER JOINLEFT OUTER JOIN DOCTOR_VISITS DV DOCTOR_VISITS DV

ON E.emp_id = DV.emp_idON E.emp_id = DV.emp_id

Selects employee names and doctor visits, one row per doctorSelects employee names and doctor visits, one row per doctor

visit. If the employee has no doctor visits, his name still appearsvisit. If the employee has no doctor visits, his name still appears

in the results, but with NULL values for doctor visits. In thisin the results, but with NULL values for doctor visits. In this

example, John Doe had a doctor visit while Tom Jones did not.example, John Doe had a doctor visit while Tom Jones did not.

E.Name DV.Date DV.ReasonE.Name DV.Date DV.Reason

--------------------------------------------------------------------------------------------------------

John Doe 02/10/2005 Sore throat John Doe 02/10/2005 Sore throat

Tom Jones NULL NULLTom Jones NULL NULL

Page 59: mySQL and Relational Databases

Outer Joins -2 The LEFT OUTER JOIN is the most commonThe LEFT OUTER JOIN is the most common

SELECT E.nameSELECT E.name

FROM employee E FROM employee E LEFT OUTER JOINLEFT OUTER JOIN DOCTOR_VISITS DV DOCTOR_VISITS DV

ON E.emp_id = DV.emp_idON E.emp_id = DV.emp_id

WHERE DV.emp_id IS NULLWHERE DV.emp_id IS NULL

Selects employee names who have no doctor visitsSelects employee names who have no doctor visits

E.Name DV.Date DV.ReasonE.Name DV.Date DV.Reason

--------------------------------------------------------------------------------------------------------

Tom Jones NULL NULLTom Jones NULL NULL

Page 60: mySQL and Relational Databases

What We Didn’t Cover ALTER TABLEALTER TABLE SQL Optimization and TuningSQL Optimization and Tuning Stored proceduresStored procedures TriggersTriggers CursorsCursors Database transactionsDatabase transactions

Page 61: mySQL and Relational Databases

MySQL Exercise -1 Create a database named MYNAME_DB (e.g. Create a database named MYNAME_DB (e.g.

JEFF_DB)JEFF_DB) CREATE DATABASE IF NOT EXISTS jeff_db;CREATE DATABASE IF NOT EXISTS jeff_db;

Create the following three tablesCreate the following three tables

STUDENTSTUDENT

--------------------------------------

STUDENT_ID (PK)STUDENT_ID (PK)

FIRST_NAMEFIRST_NAME

LAST_NAMELAST_NAME

GENDER (CHAR ‘M’ or ‘F’)GENDER (CHAR ‘M’ or ‘F’)

First name/Last name comboFirst name/Last name combo

Must Be uniqueMust Be unique

COURSECOURSE

--------------------------------------------------------------------

COURSE_ID (PK)COURSE_ID (PK)

COURSE_NAMECOURSE_NAME

COURSE_NUMBER (INT)COURSE_NUMBER (INT)

Course Name/NumberCourse Name/Number

combo should be uniquecombo should be unique

Page 62: mySQL and Relational Databases

MySQL Exercise -2REGISTRATIONREGISTRATION

--------------------------------------------

REGISTRATION_ID (PK)REGISTRATION_ID (PK)

STUDENT_IDSTUDENT_ID

COURSE_IDCOURSE_ID

STUDENT_ID and COURSE_ID should be foreign keysSTUDENT_ID and COURSE_ID should be foreign keys

Page 63: mySQL and Relational Databases

MySQL Exercise -3 Add the following records to your databaseAdd the following records to your database

STUDENTSSTUDENTS

--------------------------------

John DoeJohn Doe

Tom JonesTom Jones

Sally SmithSally Smith

Jennifer SmithJennifer Smith

COURSESCOURSES

------------------------------

Physics 101Physics 101

French 101French 101

French 201French 201

REGISTRATIONSREGISTRATIONS

------------------------------------------------

John Doe, Sally Smith, Tom Jones in Physics 101John Doe, Sally Smith, Tom Jones in Physics 101

Tom Jones in French 101Tom Jones in French 101

Sally Smith in French 201Sally Smith in French 201

Page 64: mySQL and Relational Databases

MySQL Exercise -4 Now that the database has been built and Now that the database has been built and

populated with data, we can run some queriespopulated with data, we can run some queries Easier queriesEasier queries

Select all the female students in descending Select all the female students in descending ALPHAALPHA

Select all the courses sorted first by course Select all the courses sorted first by course name, second by course numbername, second by course number

Select all the students with last name that starts Select all the students with last name that starts with the letter S, order by last name then first with the letter S, order by last name then first namename

Select the count of male studentsSelect the count of male students

Page 65: mySQL and Relational Databases

MySQL Exercise -5 More difficult queriesMore difficult queries

Select the number of students registered for Select the number of students registered for Physics 101Physics 101

Select the names of the students registered for Select the names of the students registered for the Physics 101 classthe Physics 101 class

Select all the students who are not registered for Select all the students who are not registered for any classes any classes

Select the count of students who are not Select the count of students who are not registered for any classesregistered for any classes

Select the names of students registered for Select the names of students registered for classes, and how many classes each is classes, and how many classes each is registered forregistered for

Page 66: mySQL and Relational Databases

MySQL Exercise -6 ExtraExtra

Try to delete a student from the student table who Try to delete a student from the student table who has been registered for a class. What happens?has been registered for a class. What happens?

Update a student who has already been registered Update a student who has already been registered for a class (e.g. change the first name). Do you get for a class (e.g. change the first name). Do you get an error?an error?

Create a single script that creates your database, Create a single script that creates your database, creates the tables, and inserts the records. Run it creates the tables, and inserts the records. Run it from Squirrel.from Squirrel.

Experiment with other SQL statementsExperiment with other SQL statements