mySQL and Relational Databases

2,465 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,465
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
128
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

mySQL and Relational Databases

  1. 1. mySQL and Relational Databases By Jeff Smith
  2. 2. mySQL and Relational Databases What is a Database? <ul><li>Database </li></ul><ul><ul><li>An organized collection of data grouped by common attributes </li></ul></ul><ul><ul><li>A collection of tables </li></ul></ul>
  3. 3. What is a Table ? <ul><li>Table </li></ul><ul><ul><li>Rows (records) </li></ul></ul><ul><ul><li>Columns (fields) </li></ul></ul><ul><ul><li>Field value </li></ul></ul><ul><ul><ul><li>A field value is the intersection of a row and a column </li></ul></ul></ul><ul><ul><li>A USER table could store user information while a table called MODEL might store information about weather models </li></ul></ul>
  4. 4. Table Concepts and Terms -1 <ul><li>A table is divided into rows, and each row is often referred to as a Record . So if you look up your information in a telephone book you are reviewing your record. Each “row” contains several pieces of information: your name, address, and phone number. </li></ul><ul><li>Each column in a table is a category of information referred to as a Field . In a telephone book, one column might be the names, another might be the phone numbers. </li></ul><ul><li>A single item of data, such as a single phone number, is called a data value . </li></ul>
  5. 5. Table Concepts and Terms -2 Table: PhoneBook Columns or Fields: Company, Address, City, State, Zip, Phone
  6. 6. Keys of a Table -1 <ul><li>Primary key </li></ul><ul><ul><li>Unique identifier which identifies a row </li></ul></ul><ul><li>Foreign key </li></ul><ul><ul><li>A primary key in another table - used to lookup information (provide referential integrity) </li></ul></ul><ul><li>Example: </li></ul><ul><ul><li>USERS and MODEL_GROUP tables </li></ul></ul><ul><ul><li>Each has primary key – USER_ID and MODEL_GROUP_ID </li></ul></ul><ul><ul><li>USER_ID is also stored in the MODEL_GROUP table to relate this model group to its user – USER_ID is a foreign key in the MODEL_GROUP table </li></ul></ul>
  7. 7. Keys of a Table -2 <ul><li>USER </li></ul><ul><li>------------------- </li></ul><ul><li>USER_ID (PK) </li></ul><ul><li>USER_NAME </li></ul><ul><li>PASSWORD </li></ul><ul><li>FIRST_NAME </li></ul><ul><li>LAST_NAME </li></ul>MODEL_GROUP ---------------------------------- MODEL_GROUP_ID (PK) USER_ID (FK) MODEL_GROUP_NAME
  8. 8. Indexes (Indicies) <ul><li>Primary Index </li></ul><ul><ul><li>Unique key for each record </li></ul></ul><ul><ul><li>Used to enforce primary keys </li></ul></ul><ul><ul><li>The primary key can also be composite (comprised of more than one table column) </li></ul></ul><ul><li>Secondary Indexes </li></ul><ul><ul><li>Used to speed up ordering and searching </li></ul></ul><ul><ul><li>For example, if you had thousands of users in the USER table and frequently searched for users by their last name, you might add a secondary index to last name in order to speed up these searches. </li></ul></ul>
  9. 9. Referential and Domain Integrity <ul><li>Referential Integrity </li></ul><ul><ul><li>Where a field or group of fields in one table must refer to the key in another table </li></ul></ul><ul><ul><li>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 database would refuse to accept the record (and generate an error) </li></ul></ul><ul><li>Domain Integrity </li></ul><ul><ul><li>Ensuring field values are within a valid domain </li></ul></ul><ul><ul><ul><li>E.g. start_year field in model table must be > 1950 </li></ul></ul></ul><ul><li>Some databases allow you to define integrity rules in the database - engine then rejects invalid records </li></ul><ul><li>mySQL 5 supports this capability </li></ul>
  10. 10. About mySQL <ul><li>Open source! Here’s some mySQL hype: </li></ul><ul><ul><li>The MySQL database server is the world's most popular open source database. </li></ul></ul><ul><ul><li>Over ten million installations of MySQL </li></ul></ul><ul><ul><li>Used by The Associated Press, Google, NASA, etc. </li></ul></ul><ul><ul><li>Runs on over 20 platforms (including Linux, Windows) </li></ul></ul><ul><ul><li>Download it for free from the web: http://www.mysql.com/ </li></ul></ul><ul><li>Can either manage mySQL from a command line interface or from nice and free GUI tools (mySQL Query Browser and mySQL Administrator) </li></ul>
  11. 11. Setting up a mySQL Database - 1 <ul><li>Remember, database is a collection of tables </li></ul><ul><li>You must first create database before you can add tables to it </li></ul><ul><li>The latest version of mySQL is version 5 </li></ul><ul><li>With mySQL, you can either create a database from the command line or by using a GUI tool like MySQL Administrator </li></ul>
  12. 12. MySQL Table Engines <ul><li>InnoDB </li></ul><ul><ul><li>Most popular transactional storage engine for MySQL </li></ul></ul><ul><ul><li>Fullly supports standard SQL isolation levels for ACID-compliant transaction processing (ie. commit, rollback) </li></ul></ul><ul><ul><li>Provides row level locking </li></ul></ul><ul><li>MyISAM </li></ul><ul><ul><li>Default storage engine </li></ul></ul><ul><ul><li>No transaction support (no commit, rollback) </li></ul></ul><ul><ul><li>Faster reads, good choice for table where you select from it a lot, but don’t need to update it </li></ul></ul><ul><ul><li>Doesn’t support row level locking (so slower if you modify the data a lot) </li></ul></ul><ul><li>Also supports 8 other storage engines </li></ul><ul><li>Can mix these engines within a single database </li></ul>
  13. 13. MySQL Data Types <ul><li>Common data types </li></ul><ul><ul><li>int </li></ul></ul><ul><ul><li>double </li></ul></ul><ul><ul><li>decimal </li></ul></ul><ul><ul><li>varchar(n) </li></ul></ul><ul><ul><li>char(n) </li></ul></ul><ul><ul><li>enum </li></ul></ul><ul><ul><li>date </li></ul></ul><ul><ul><li>datetime </li></ul></ul><ul><ul><li>timestamp </li></ul></ul>
  14. 14. Setting Up Database With A Script <ul><li>DROP DATABASE IF EXISTS jeff_db; </li></ul><ul><li>CREATE DATABASE IF NOT EXISTS jeff_db; </li></ul><ul><li>CREATE TABLE USER </li></ul><ul><li>( </li></ul><ul><li>USER_ID int NOT NULL auto_increment PRIMARY KEY, </li></ul><ul><li>USERNAME varchar(20) NOT NULL, </li></ul><ul><li>PASSWORD varchar(20) NOT NULL, </li></ul><ul><li>EMAIL varchar(100), </li></ul><ul><li>LAST_ACCESS datetime, </li></ul><ul><li>UNIQUE KEY LOGIN (USERNAME, PASSWORD) </li></ul><ul><li>) ENGINE=InnoDB; </li></ul><ul><li># Table structure for table MODEL_GROUP </li></ul><ul><li>CREATE TABLE MODEL_GROUP </li></ul><ul><li>( </li></ul><ul><li>MODEL_GROUP_ID int NOT NULL auto_increment, </li></ul><ul><li>MODEL_GROUP_NAME varchar(20) NOT NULL, </li></ul><ul><li>USER_ID int, </li></ul><ul><li>TYPE enum(‘A’, ‘B’) default ‘A’, </li></ul><ul><li>FOREIGN KEY (USER_ID) REFERENCES USER(USER_ID) </li></ul>
  15. 16. Setting up a Database - 3 <ul><li>You can run this script from a command line or a GUI </li></ul>
  16. 17. Basic SQL <ul><li>SQL stands for Structured Query Language. It is a fairly standard way to communicate with relational databases such as mySQL, Postgres, Oracle, MS SQL Server, etc. </li></ul><ul><li>There are four common SQL commands: </li></ul><ul><ul><li>SELECT -retrieves the specified records </li></ul></ul><ul><ul><li>INSERT -adds a new row (or record) </li></ul></ul><ul><ul><li>UPDATE -changes values in the specified row(s) </li></ul></ul><ul><ul><li>DELETE -removes the specified rows </li></ul></ul>
  17. 18. Basic SQL, SELECT statement -1 <ul><li>Select statements generally retrieve data from one or more database tables. </li></ul><ul><li>SELECT column_names </li></ul><ul><li>FROM table_names </li></ul><ul><li>[ WHERE search_condition ] </li></ul><ul><li>[ GROUP BY group_expression ] [HAVING condition ] </li></ul><ul><li>[ ORDER BY order_condition [ ASC | DESC ] ] </li></ul><ul><li>Note: The statements in square brackets are optional. </li></ul>
  18. 19. Basic SQL, SELECT statement -2 <ul><li>For example, to select the first name and last name of user number 122: </li></ul><ul><li>SELECT FirstName, LastName </li></ul><ul><li>FROM Users </li></ul><ul><li>WHERE UserID = 122 </li></ul><ul><li>Result: </li></ul><ul><li>FIRSTNAME LASTNAME </li></ul><ul><li>Jeff Smith </li></ul>
  19. 20. Basic SQL, SELECT statement -3 <ul><li>For example, to select all the fields for a particular user: </li></ul><ul><li>SELECT * </li></ul><ul><li>FROM Users </li></ul><ul><li>WHERE UserName = ‘jssmith’ </li></ul><ul><li>Result: </li></ul><ul><li>USERID USERNAME PASSWORD FIRSTNAME LASTNAME </li></ul><ul><li>122 jssmith password Jeff Smith </li></ul>
  20. 21. Basic SQL, SELECT statement -4 <ul><li>You can order the results of your SELECT statement with the ORDER BY clause </li></ul><ul><li>SELECT * </li></ul><ul><li>FROM user </li></ul><ul><li>WHERE userid > 120 AND userid < 135 </li></ul><ul><li>ORDER BY lastname DESC </li></ul><ul><li>Result: </li></ul><ul><li>USERID USERNAME PASSWORD FIRSTNAME LASTNAME </li></ul><ul><li>121 kzeller tree13 Kathy Zeller </li></ul><ul><li>122 jssmith password Jeff Smith </li></ul><ul><li>134 tarroyo apple01 Thomas Arroyo </li></ul>
  21. 22. Basic SQL, SELECT statement -5 <ul><li>You can also join tables with your search criteria. For example, to find all the model groups for user jssmith: </li></ul><ul><li>SELECT model_group.* </li></ul><ul><li>FROM model_group, user </li></ul><ul><li>WHERE user.username = ‘jssmith’ </li></ul><ul><li>AND user.user_id = model_group.user_id </li></ul><ul><li>Result: </li></ul><ul><li>MODEL_GROUP_ID USER_ID MODEL_GROUP_NAME </li></ul><ul><li>11 122 Jeff’s Ensemble </li></ul>
  22. 23. Basic SQL, SELECT statement -6 <ul><li>Sometimes SQL statements can get verbose. As a shorthand, you can specify aliases for the table names. </li></ul><ul><li>SELECT MG.* </li></ul><ul><li>FROM model_group MG , user U </li></ul><ul><li>WHERE U.username = ‘jssmith’ </li></ul><ul><li>AND U.user_id = MG.user_id </li></ul><ul><li>Result: </li></ul><ul><li>MODEL_GROUP_ID USER_ID MODEL_GROUP_NAME </li></ul><ul><li>11 122 Jeff’s Ensemble </li></ul>
  23. 24. Basic SQL, INSERT statement -1 <ul><li>Insert statements insert data into a table </li></ul><ul><li>INSERT INTO table_name ( column_names ) VALUES( value_list ) </li></ul><ul><li>For example: </li></ul><ul><li>INSERT INTO USER(username, password) </li></ul><ul><li>VALUES (‘jssmith’, ‘password’) </li></ul>
  24. 25. Basic SQL, INSERT statement -2 <ul><li>You can also combine an INSERT with a SELECT </li></ul><ul><li>For example: </li></ul><ul><li>INSERT INTO USER(username, password) </li></ul><ul><li>SELECT OU.username, OU.password </li></ul><ul><li>FROM OTHER_USER OU </li></ul><ul><li>WHERE OU.USER_ID = 1 </li></ul>
  25. 26. Basic SQL, UPDATE statement <ul><li>An update statement updates (changes) an existing record (row) in a table </li></ul><ul><li>UPDATE table_name SET column_name1=value1, ... , column_nameN=valueN [ WHERE search_condition ] </li></ul><ul><li>For example: </li></ul><ul><li>UPDATE model_group </li></ul><ul><li>SET model_group_name = ‘my ensemble’ </li></ul><ul><li>WHERE model_group_id = 134 </li></ul>
  26. 27. Basic SQL, DELETE statement <ul><li>Delete statement remove data from a table </li></ul><ul><li>DELETE FROM table_name </li></ul><ul><li>[ WHERE search_condition ] </li></ul><ul><li>For example: </li></ul><ul><li>DELETE FROM model_group </li></ul><ul><li>WHERE model_group_id = 134 </li></ul>
  27. 28. Common MySQL Commands -1 <ul><li>use dbName (e.g. use my_database) </li></ul><ul><ul><li>Subsequent commands apply to this database </li></ul></ul><ul><li>show databases (lists databases) </li></ul><ul><li>show tables (lists tables) </li></ul><ul><ul><li>Generates listing of all tables </li></ul></ul><ul><li>describe tableName (e.g. describe USER) </li></ul><ul><ul><li>Describes the table, listing column names, data types, etc. </li></ul></ul><ul><li>drop database dbName (deletes entire database) </li></ul><ul><li>drop table tableName (e.g. drop table USER) </li></ul>
  28. 29. Common MySQL Commands -2 <ul><li>create table </li></ul><ul><li>[mysql dir]/bin/mysql -h hostname -u root –p </li></ul><ul><ul><li>Logs you into a database from command line </li></ul></ul><ul><li>mysql –h 12.123.1.12 –u root –p </li></ul><ul><li>(logs you into mysql running at that IP address, </li></ul><ul><li>as user “root”, will prompt you for the password) </li></ul><ul><li>mysql –u john –p </li></ul><ul><li>(logs you into local mysql as user “john”) </li></ul>
  29. 30. Common MySQL Commands -3 alter table [table name] drop index [colmn name]; Delete unique from table. alter table [table name] modify [column name] VARCHAR(3); Make a column bigger. alter table [table name] add unique ([column name]); Make a unique column so you get no dupes. alter table [table name] change [old column name] [new column name] varchar (50); Change column name. alter table [table name] add column [new column name] varchar (20); Add a new column to db. alter table [table name] drop column [column name]; Delete a column.
  30. 31. Summary <ul><li>SQL is a simple, reliable, and standard way to save and retrieve information </li></ul><ul><li>mySQL is open source (basically free for non-commercial uses) </li></ul><ul><li>mySQL supports Windows, UNIX, Linux, etc. and so has widespread support </li></ul><ul><li>mySQL is mature and stable </li></ul><ul><li>There are some fairly slick tools to use with mySQL (notably MySQL Administrator, Query Browser, and Squirrel SQL Client) </li></ul>
  31. 32. Squirrel SQL Client <ul><li>Java GUI that can be installed without admin privileges </li></ul><ul><li>Cross platform compatible (Java, of course) </li></ul><ul><li>It is open source (free) </li></ul><ul><li>Can download it from SourceForge.net </li></ul><ul><li>Download from here: </li></ul><ul><li>http://squirrel-sql.sourceforge.net/ </li></ul>
  32. 33. Squirrel SQL Client Installation <ul><li>Downloading the JAR file (note that IE might rename the file .zip—if it does, just rename it .jar) </li></ul><ul><li>Run the JAR file: </li></ul><ul><li>java –jar squirrel-sql-2.4-install.jar </li></ul><ul><li>(After a few seconds, the installation </li></ul><ul><li>program will start running) </li></ul>
  33. 34. Squirrel SQL Client Installation -1 <ul><li>You may not have permission to install the program under C:Program Files </li></ul>
  34. 35. Squirrel SQL Client Installation -2 <ul><li>Select the optional MySQL plugin option </li></ul>
  35. 36. Squirrel SQL Client Installation -3 <ul><li>Add shortcuts to the desktop </li></ul>
  36. 37. Squirrel SQL Client Installation -4 <ul><li>Double click on the desktop icon </li></ul><ul><li>If you get a “main class not found” type error, go to the “Squirrel SQL Client” directory and run the following command </li></ul><ul><li>java -jar -Xmx256m squirrel-sql.jar </li></ul>
  37. 38. Squirrel SQL Client Installation -5 <ul><li>When the program is up and running, select the MySQL option in the left box </li></ul>
  38. 39. Squirrel SQL Client Installation -6 <ul><li>Click on the Extra Class Path tab and then click on the Add button. Select the mysql jar </li></ul>
  39. 40. Squirrel SQL Client Installation -7 <ul><li>Click on the + to add a new alias to your mySQL database </li></ul>
  40. 41. Squirrel SQL Client Installation -8 <ul><li>Add your alias. An alias basically stores connection information to connect to a database. An IP address other than localhost connects you to remote mySQL </li></ul><ul><ul><li>Instructor IP address is 140.172.8.164 </li></ul></ul>
  41. 42. Squirrel SQL Client Installation -9 <ul><li>If you get an error message like this, it probably means mySQL isn’t running </li></ul>
  42. 43. Squirrel SQL Client Installation -10 <ul><li>If you connect, you’ll see a screen like this </li></ul>
  43. 44. Squirrel SQL Client Installation -11 <ul><li>Click on the SQL tab to type in your SQL </li></ul>
  44. 45. WHERE Clause <ul><li>Can be quite complex with AND and OR statements </li></ul><ul><li>Can include LIKE clause to do wildcard matches (LIKE ‘Sm%’ or LIKE ‘%M’) </li></ul><ul><li>SELECT * </li></ul><ul><li>FROM employee </li></ul><ul><li>WHERE NAME LIKE ‘S%’ </li></ul><ul><li>AND (SALARY < 20000 OR SALARY >= 100000) </li></ul><ul><li>Select employees whose names start with S and whose </li></ul><ul><li>salary is less than 20k or greater than or equal to 100k </li></ul>
  45. 46. Selecting the COUNT <ul><li>Sometimes you want to select the count of rows that match the given constraints </li></ul><ul><li>SELECT COUNT(*) </li></ul><ul><li>FROM employee </li></ul><ul><li>WHERE NAME LIKE ‘%TH’ </li></ul><ul><li>Select the number of employees whose names end with </li></ul><ul><li>the letters ‘TH’ </li></ul>
  46. 47. Selecting the MIN or MAX <ul><li>Sometimes you want to select the max or min value for a field in a given table </li></ul><ul><li>SELECT MAX(salary) </li></ul><ul><li>FROM employee </li></ul><ul><li>WHERE dept_no = 22 </li></ul><ul><li>Select the highest salary or all employees in dept. 22 </li></ul>
  47. 48. Selecting the SUM <ul><li>Sometimes you want to select the sum of field for a field in a given table </li></ul><ul><li>SELECT SUM(salary) </li></ul><ul><li>FROM employee </li></ul><ul><li>WHERE dept_no = 22 </li></ul><ul><li>Select the sum of all salaries for employees in dept. 22 </li></ul>
  48. 49. Joining Tables <ul><li>Sometimes the information you want is scattered in more than one table </li></ul><ul><li>You can join tables in a SELECT statement </li></ul><ul><li>SELECT E.name, E.salary, D.dept_name </li></ul><ul><li>FROM employee E, department D </li></ul><ul><li>WHERE E.dept_no = D.dept_no </li></ul><ul><li>Select the employee name, salary and department name </li></ul><ul><li>for all employees </li></ul><ul><li>The join condition here is E.dept_no = D.dept_no </li></ul>
  49. 50. Sub Queries -1 <ul><li>You can imbed sub queries into your WHERE clause to create sophisticated constraints </li></ul><ul><li>Sub queries can be correlated or non-correlated </li></ul><ul><ul><li>A correlated sub query refers to a column from a table in the parent query </li></ul></ul><ul><ul><li>A non-correlated sub query does not </li></ul></ul>
  50. 51. Sub Queries -1 <ul><li>Non-correlated sub query example </li></ul>SELECT name FROM employee E WHERE E.dept_no = (SELECT dept_no FROM employee WHERE name = 'Zirsky') This selects the names of all the people who work in the same department as ‘Zirsky’ This sub query must return a single row (or no rows) since the Comparator is an ‘=‘ (equals sign). If there are two ‘Zirsky’s, you’ll get a SQL error
  51. 52. Sub Queries -2 <ul><li>A sub query can also return a set of rows (instead of a single row) </li></ul><ul><li>To do this, use ‘IN’ or ‘NOT IN’ </li></ul>SELECT name FROM employee E WHERE E.dept_no IN (SELECT dept_no FROM employee WHERE name = 'Zirsky‘ OR name = ‘Thompson’) This selects the names of all the people who work in the same department as ‘Zirsky’ or ‘Thompson’
  52. 53. Correlated Sub Queries -2 <ul><li>NOT IN sub query example </li></ul>SELECT name FROM employee E WHERE E.employee_id NOT IN (SELECT employee_id FROM benefits) This selects the names of all the people who are not in the benefits table (they have no benefits)
  53. 54. Aggregate Selects (GROUP BY) -1 <ul><li>You can aggregate information (e.g. sub total it) in your select statements by using GROUP BY in conjunction with COUNT, MAX, MIN or SUM </li></ul><ul><li>Since aggregate functions (like MAX) return the aggregate of all column values every time they are called, the GROUP BY clause enables you to find the aggregate for individual groups (i.e. subtotal) </li></ul>SELECT count(*), E.name FROM employee E, doctor_visits DV WHERE E.emp_id = DV.emp_id GROUP BY E.name This selects the employee names and number of doctor visits they’ve had. For example 4 John Doe 2 Maggie Smith
  54. 55. Aggregate Selects (GROUP BY) -2 <ul><li>You can aggregate by COUNT, SUM, MIN, or MAX </li></ul>SELECT count(*), E.name FROM employee E, doctor_visits DV WHERE E.emp_id = DV.emp_id GROUP BY E.name This selects the employee names and number of doctor visits they’ve had. For example 4 John Doe 2 Maggie Smith 3 Tom Jones
  55. 56. Aggregate Selects (GROUP BY) -3 <ul><li>You can add a HAVING clause to add a further constraint to the grouping condition </li></ul>SELECT count(E.name), E.name FROM employee E, doctor_visits DV WHERE E.emp_id = DV.emp_id GROUP BY E.name HAVING (COUNT(E.name) > 2) This selects the employee names and number of doctor visits they’ve had IF they’ve had more than 2 visits. For example 4 John Doe 3 Tom Jones
  56. 57. Outer Joins -1 <ul><li>Sometimes you want to select fields from multiple tables 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 OUTER JOIN </li></ul><ul><li>A LEFT OUTER JOIN returns all the rows that an inner join returns plus one row for each of the other rows in the first table that did not have a match in the second table </li></ul><ul><li>A RIGHT OUTER JOIN returns all the rows that an inner join returns plus one row for each of the other rows in the second table that did not have a match in the first table. </li></ul><ul><li>A FULL OUTER JOIN acts like the combination of a LEFT and RIGHT outer join </li></ul>
  57. 58. Outer Joins -2 <ul><li>The LEFT OUTER JOIN is the most common </li></ul>SELECT E.name FROM employee E LEFT OUTER JOIN DOCTOR_VISITS DV ON E.emp_id = DV.emp_id Selects employee names and doctor visits, one row per doctor visit. If the employee has no doctor visits, his name still appears in the results, but with NULL values for doctor visits. In this example, John Doe had a doctor visit while Tom Jones did not. E.Name DV.Date DV.Reason ---------------------------------------------------- John Doe 02/10/2005 Sore throat Tom Jones NULL NULL
  58. 59. Outer Joins -2 <ul><li>The LEFT OUTER JOIN is the most common </li></ul>SELECT E.name FROM employee E LEFT OUTER JOIN DOCTOR_VISITS DV ON E.emp_id = DV.emp_id WHERE DV.emp_id IS NULL Selects employee names who have no doctor visits E.Name DV.Date DV.Reason ---------------------------------------------------- Tom Jones NULL NULL
  59. 60. What We Didn’t Cover <ul><li>ALTER TABLE </li></ul><ul><li>SQL Optimization and Tuning </li></ul><ul><li>Stored procedures </li></ul><ul><li>Triggers </li></ul><ul><li>Cursors </li></ul><ul><li>Database transactions </li></ul>
  60. 61. MySQL Exercise -1 <ul><li>Create a database named MYNAME_DB (e.g. JEFF_DB) CREATE DATABASE IF NOT EXISTS jeff_db; </li></ul><ul><li>Create the following three tables </li></ul>STUDENT ------------------- STUDENT_ID (PK) FIRST_NAME LAST_NAME GENDER (CHAR ‘M’ or ‘F’) First name/Last name combo Must Be unique COURSE ---------------------------------- COURSE_ID (PK) COURSE_NAME COURSE_NUMBER (INT) Course Name/Number combo should be unique
  61. 62. MySQL Exercise -2 REGISTRATION ---------------------- REGISTRATION_ID (PK) STUDENT_ID COURSE_ID STUDENT_ID and COURSE_ID should be foreign keys
  62. 63. MySQL Exercise -3 <ul><li>Add the following records to your database </li></ul>STUDENTS ---------------- John Doe Tom Jones Sally Smith Jennifer Smith COURSES --------------- Physics 101 French 101 French 201 REGISTRATIONS ------------------------ John Doe, Sally Smith, Tom Jones in Physics 101 Tom Jones in French 101 Sally Smith in French 201
  63. 64. MySQL Exercise -4 <ul><li>Now that the database has been built and populated with data, we can run some queries </li></ul><ul><li>Easier queries </li></ul><ul><ul><li>Select all the female students in descending ALPHA </li></ul></ul><ul><ul><li>Select all the courses sorted first by course name, second by course number </li></ul></ul><ul><ul><li>Select all the students with last name that starts with the letter S, order by last name then first name </li></ul></ul><ul><ul><li>Select the count of male students </li></ul></ul>
  64. 65. MySQL Exercise -5 <ul><li>More difficult queries </li></ul><ul><ul><li>Select the number of students registered for Physics 101 </li></ul></ul><ul><ul><li>Select the names of the students registered for the Physics 101 class </li></ul></ul><ul><ul><li>Select all the students who are not registered for any classes </li></ul></ul><ul><ul><li>Select the count of students who are not registered for any classes </li></ul></ul><ul><ul><li>Select the names of students registered for classes, and how many classes each is registered for </li></ul></ul>
  65. 66. MySQL Exercise -6 <ul><li>Extra </li></ul><ul><ul><li>Try to delete a student from the student table who has been registered for a class. What happens? </li></ul></ul><ul><ul><li>Update a student who has already been registered for a class (e.g. change the first name). Do you get an error? </li></ul></ul><ul><ul><li>Create a single script that creates your database, creates the tables, and inserts the records. Run it from Squirrel. </li></ul></ul><ul><ul><li>Experiment with other SQL statements </li></ul></ul>

×