LIS569 – Database Systems Dr

Slides:



Advertisements
Similar presentations
Chapter 4 5 6_ SQL SQL Is: Structured Query Language
Advertisements

Introduction to Structured Query Language (SQL)
Chapter 7: Introduction to SQL
Introduction to Structured Query Language (SQL)
1 © Prentice Hall, 2002 Chapter 7: SQL Modern Database Management 6 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.
1 IS 4420 Database Fundamentals Chapter 7: Introduction to SQL Leon Chen.
Introduction to Structured Query Language (SQL)
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
ASP.NET Programming with C# and SQL Server First Edition
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Chapter 6: Introduction to SQL
Database System SQL November 1st, 2009 Software Park, Bangkok Thailand Pree Thiengburanathum College of Arts and Media Chiang Mai University.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
1 Chapter 7 Introduction to SQL. 2 Objectives Definition of terms Interpret history and role of SQL Define a database using SQL data definition language.
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Introduction to SQL.
CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer,
© 2009 Pearson Education, Inc. Publishing as Prentice Hall 1 UNIT 6: Chapter 7: Introduction to SQL Modern Database Management 9 th Edition Jeffrey A.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 6: Introduction to SQL Modern Database Management 10 th Edition Jeffrey A. Hoffer,
© 2007 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 8 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.
Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
Dr. Chen, Data Base Management Chapter 6: Introduction to SQL Jason C. H. Chen, Ph.D. Professor of MIS School of Business Administration Gonzaga University.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall Chapter 6: Introduction to SQL Modern Database Management 11 th Edition Jeffrey A.
CHAPTER 6: INTRODUCTION TO SQL Copyright © 2014 Pearson Education, Inc. 1 Essentials of Database Management Jeffrey A. Hoffer, Heikki Topi, V. Ramesh.
1 © Prentice Hall, 2002 Chapter 8: Advanced SQL Modern Database Management 6 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
© 2009 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 7 (Part a): Introduction to SQL Modern Database Management 9 th Edition Jeffrey A.
Lec 3- B Database Integrity 1. Overview Define a database using SQL data definition language Work with Views Write single table queries Establish referential.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
© 2005 by Prentice Hall 1 Chapter 7: Introduction to SQL Modern Database Management 7 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.
Chapter 7: Introduction to SQL
© 2011 Pearson Education 1 Chapter 6: Basic SQL Modern Database Management 10 th Edition, International Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
Chapter 6: Introduction to SQL
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
SQL Overview Structured Query Language
1 © Prentice Hall, 2002 Chapter 7: SQL Modern Database Management 6 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Querying Single Tables with SQL.
SQL. Originally developed by IBM Standardized in 80’s by ANSI and ISO Language to access relational database and English-like non-procedural Predominant.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
Lecture # 24 Introduction to SQL Muhammad Emran Database Systems.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
1 Database Fundamentals Introduction to SQL. 2 SQL Overview Structured Query Language The standard for relational database management systems (RDBMS)
© 2009 Pearson Education, Inc. Publishing as Prentice Hall 1 Lecture 7: Introduction to SQL Modern Database Management 9 th Edition Jeffrey A. Hoffer,
Copyright © 2016 Pearson Education, Inc. Modern Database Management 12 th Edition Jeff Hoffer, Ramesh Venkataraman, Heikki Topi CHAPTER 6: INTRODUCTION.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
CHAPTER 6: INTRODUCTION TO SQL © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer,
3 A Guide to MySQL.
SQL Query Getting to the data ……..
Introduction to SQL Karolina muszyńska
SQL and SQL*Plus Interaction
Normalization Karolina muszyńska
“Introduction To Database and SQL”
CHAPTER 7: ADVANCED SQL.
DATABASE MANAGEMENT SYSTEM
CHAPTER 6: INTRODUCTION TO SQL
Chapter 7 Working with Databases and MySQL
Chapter 8 Working with Databases and MySQL
Chapter 6: Introduction to SQL
SQL-1 Week 8-9.
Contents Preface I Introduction Lesson Objectives I-2
Chapter # 7 Introduction to Structured Query Language (SQL) Part I.
INTRODUCTION A Database system is basically a computer based record keeping system. The collection of data, usually referred to as the database, contains.
Presentation transcript:

LIS569 – Database Systems Dr LIS569 – Database Systems Dr. Jianqiang Wang Introduction to SQL and MySQL Week 8, Mar. 4, 2013

Agenda Team project update SQL history, purposes, and benefits Basic SQL syntax MySQL environment and commands involving only one table

Objectives Define terms Interpret history and role of SQL Define a database using SQL DDL Write single table queries using MySQL commands

SQL Overview Structured Query Language (SQL) The standard for relational database management systems (RDBMS) RDBMS: A database management system that manages data as a collection of tables in which all relationships are represented by common values in related tables

History of SQL 1970: E. Codd develops relational database concept 1974-1979: System R with Sequel at IBM 1979–Oracle markets first relational DB with SQL 1986–ANSI SQL standard released 1989, 1992, 1999, 2003: Major ANSI standard updates Current: SQL is supported by most major DB vendors

Purpose of SQL Standard Specify syntax/semantics for data definition and manipulation Define data structures and basic operations Enable portability of database definition and application modules Specify minimal (level 1) and complete (level 2) standards Allow for later growth/enhancement to standard

Benefits of a Standardized Relational Language Reduced training costs Productivity Application portability Application longevity Reduced dependence on a single vendor Cross-system communication

SQL Environment Catalog Schema Data Definition Language (DDL) A set of schemas that constitute the description of a database Schema The structure that contains descriptions of objects created by a user (base tables, views, constraints) Data Definition Language (DDL) Commands that define a database, including creating, altering, and dropping tables and establishing constraints Data Manipulation Language (DML) Commands that maintain and query a database Data Control Language (DCL) Commands that control a database, including administering privileges and committing data

A simplified schematic of a typical SQL environment

DDL, DML, DCL, and the DB development process

Introduction to MySQL Most popular open source, cross-platform RDBMS Commercial examples: WordPress, Drupal, Google, Facebook, Twitter, Wikipedia Web application development: downloadable in many ways including LAMP and XAMPP Owned by Oracle Corporation Source code available under GNU General Public License Many frontend tools to use MySQL Graphical: Navicat, phpMyAdmin, … Command line: mysql

MySQL on gsestudent6 Server Gsestudent6 server has MySQL server, Apache Web server, and PHP environment Hosts web-accessible MySQL database Web publishing and PHP programming will be covered in later weeks Developing and accessing MySQL databases via Navicat Lite Week 8-11

Using gsestudent6 MySQL via Navicat Launch Navicat Lite Assuming Navicat Lite has been installed on the local computer, look for icon on the desktop and double click it This window will display

Using gsestudent6 MySQL via Navicat Set up a connection Select “Connection”  “MySQL” Fill information in the dialogue window User name: your UBIT name Password: password Click OK

Using gsestudent6 MySQL via Navicat You’ll see the newly created connection Double click it to open the connection

Using gsestudent6 MySQL via Navicat You’ll see three databases, one of which is named after your UBIT name, and that’s the one you’ll use to practice SQL commands (Carolyn’s is used as the example here)

Change your Password Select “Tools”“Console” to open a console (command line) window In the console window, type in SET PASSWORD = PASSWORD('mypass'); (where mypass is the password you want to use) Hit “Enter” key to run the command Close the console Select “File”  “Close Connection”

Test your New Password Double click “gsestudent6” connection You’ll see an error message Mouse cursor on “gsestudent6” connection and right click to select “connection properties” In the “Connection Properties” window, change the password to the one that you just set and click “OK” You should be successful now

SQL Database Definition Data Definition Language (DDL) Major CREATE statements: CREATE SCHEMA–defines a portion of the database owned by a particular user CREATE TABLE–defines a new table and its columns CREATE VIEW–defines a logical table from one or more tables or views Other CREATE statements: CHARACTER SET, COLLATION, TRANSLATION, ASSERTION, DOMAIN

Table Creation Steps in table creation: Identify data types for attributes Identify columns that can and cannot be null Identify columns that must be unique (candidate keys) Identify primary key–foreign key mates Determine default values Identify constraints on columns (domain specifications) Create the table and associated indexes

An Enterprise Data Model

Corresponding Relations Customer_T (CustomerID, CustomerName) Product_T (ProductID, ProductStandardPrice) Order_T (OrderID, CustomerID, OrderDate) OrderLine_T (OrderID, ProductID, OrderedQuantity)

Open a Database in Navicat Double click the database named after your UBIT name to open it You have to select and open a database before you can do anything with it Click Tables, Views, etc. under it There is nothing since the database is empty at this point Select “Tools”  “Console” You’ll practice MySQL commands in the Console window

A Navicat Console Looks Like

MySQL Commands to Create Tables Type in the following command in the Console window to create Customer_T table and hit “enter” CREATE TABLE Customer_T (CustomerID INT(10) NOT NULL, CustomerName VARCHAR(25) NOT NULL, CONSTRAINT Customer_PK PRIMARY KEY (CustomerID)); If the command is run successfully, you’ll see the following message: Query OK, 0 rows affected

Command Explained Non-nullable specification Identifying primary key CREATE TABLE Customer_T (CustomerID INT(10) NOT NULL, CustomerName VARCHAR(25) NOT NULL, CONSTRAINT Customer_PK PRIMARY KEY (CustomerID)); Identifying primary key Primary keys can never have NULL values

A few Things to Keep in Mind SQL is usually case-insensitive on Windows So ‘NOT NULL’ is the same as ‘not null’ Could be different on other OS’s or with different implementations of SQL Punctuations are important Line breaks are not required but they make your SQL easier to read by humans It’s a good habit NOT to use space in names White space in names can easily confuses the system Use “-” or “_” instead

Edit/Save Queries in Navicat Queries (i.e., MySQL commands) can be created, edited, and saved in Navicat’s Query Editor Click “Query” on the top of the window and then select “New Query”

Edit/Save Queries in Navicat In the newly opened Query Editor, you can type in your query and Run or Save it. To save it, give a name in the pop-up window and click “OK”. You’ll see the new query appears in the main Navicat query window.

Create Product_T Table CREATE TABLE Product_T (ProductID INT(10) NOT NULL, ProductStandardPrice DECIMAL(6,2), CONSTRAINT Product_PK PRIMARY KEY (ProductID));

Create Order_T Table CREATE TABLE Order_T (OrderID INT(10) NOT NULL, CustomerID INT(10), OrderDate DATE, CONSTRAINT Order_PK PRIMARY KEY (OrderID), CONSTRAINT Order_FK1 FOREIGN KEY (CustomerID) REFERENCES Customer_T(CustomerID));

Create OrderLine_T Table CREATE TABLE OrderLine_T (OrderID INT(10) NOT NULL, ProductID INT(10) NOT NULL, OrderedQuantity INT(10) , CONSTRAINT OrderLine_PK PRIMARY KEY (OrderID, ProductID), CONSTRAINT OrderLine_FK1 FOREIGN KEY (OrderID) REFERENCES Order_T(OrderID), CONSTRAINT OrderLine_FK2 FOREIGN KEY (ProductID) REFERENCES Product_T(ProductID));

Find Information of Tables To see what tables are included in the database: SHOW tables; Or click icon in Navicat window. To see the structure of a table: DESCRIBE table_name; Or first select a table and then click “Design Table” To see the content of a table: SELECT * FROM table_name; Or double click on a table name.

Data Integrity Controls Referential integrity: constraint that ensures that foreign key values of a table must match primary key values of a related table in 1:M relationships Restricting: Deletes of primary records Updates of primary records Inserts of dependent records

Ensuring data integrity through updates Relational integrity is enforced via the primary-key to foreign-key match

Changing Tables ALTER TABLE statement allows you to change column specifications: Table Actions:

Add/Delete One Column Add CustomerState column to Customer_T ALTER TABLE Customer_T ADD CustomerState CHAR(2); Check the structure of Customer_T DESCRIBE Customer_T; Delete CustomerState from Customer_T ALTER TABLE Customer_T DROP CustomerState;

Add/Delete Multiple Columns Add columns to Customer_T table ALTER TABLE Customer_T ADD COLUMN CustomerAddress VARCHAR(30), ADD COLUMN CustomerCity VARCHAR(20), ADD COLUMN CustomerState CHAR(2), ADD COLUMN CustomerPostalCode VARCHAR(10); delete columns from Customer_T table ALTER TABLE Customer_T DROP COLUMN CustomerAddress, DROP COLUMN CustomerCity, DROP COLUMN CustomerState, DROP COLUMN CustomerPostalCode; Add them back

In-Class Exercise: Add columns Add the following two columns to Product_T table ProductDescription VARCHAR(50), ProductFinish VARCHAR(20), Answer: ALTER TABLE Product_T ADD COLUMN ProductDescription VARCHAR(50), ADD COLUMN ProductFinish VARCHAR(20);

Removing Tables DROP TABLE statement allows you to remove tables from your schema Example DROP TABLE Customer_T; Be careful with DROP command You may not be allowed to delete a table due to integrity constrains, e.g., it is involved in a relationship

In-Class Exercise: Delete tables Delete OrderLine_T table Verify it is deleted Recreate the table

In-Class Exercise: Answers DROP TABLE OrderLine_T; SHOW tables; CREATE TABLE OrderLine_T (OrderID INT(10) NOT NULL, ProductID INT(10) NOT NULL, OrderedQuantity INT(10) , CONSTRAINT OrderLine_PK PRIMARY KEY (OrderID, ProductID), CONSTRAINT OrderLine_FK1 FOREIGN KEY (OrderID) REFERENCES Order_T(OrderID), CONSTRAINT OrderLine_FK2 FOREIGN KEY (ProductID) REFERENCES Product_T(ProductID));

Insert Statement Adds one or more rows to a table Inserting one complete row to a table INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity, CustomerState, CustomerPostalCode) VALUES (1, 'Contemporary Casuals', '1355 S Hines Blvd', 'Gainesville', 'FL', '32601-2871'); or INSERT INTO Customer_T VALUES (1, 'Contemporary Casuals', '1355 S Hines Blvd', 'Gainesville', 'FL', '32601-2871');

Insert Statement Inserting a record that has some null attributes requires identifying the fields that actually get data INSERT INTO Customer_T (CustomerID, CustomerName, CustomerAddress, CustomerCity, CustomerState) VALUES (2, 'Value Furniture', '15145 S.W. 17th St.', 'Plano', 'TX'); Inserting multiple rows with one command INSERT INTO Customer_T VALUES (3, 'Home Furnishings', '1900 Allard Ave.', 'Albany', 'NY', '12209-1125'), (4, 'Eastern Furniture', '1925 Beltline Rd.', 'Carteret', 'NJ', '07008-3188');

In-Class Exercises: Add Records For Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice) (1, 'End Table', 'Cherry', 175); (2, 'Coffee Table', 'Natural Ash', 200); For OrderLine_T (1001, 1, 2) What happened? Why? How to fix it?

In-Class Exercises: Answers INSERT Product_T (ProductID, ProductDescription, ProductFinish, ProductStandardPrice) VALUES (1, 'End Table', 'Cherry', 175), (2, 'Coffee Table', 'Natural Ash', 200); You won’t be able insert any record into OrderLine_T table because of a referential constraint, i.e., the foreign key OrderID has not had any value in Order_T table. You’ll have to insert records in that table first.

Delete Statement Remove row(s) from a table Delete certain rows DELETE FROM Customer_T WHERE CustomerState = 'TX'; Delete all rows DELETE FROM Customer_T;

In-Class Exercises: Delete Records Delete the record of the product with an ID of "1" from Product_T table Answer: DELETE FROM Product_T WHERE ProductID = '1';

Update Statement Modifies data in existing rows UPDATE Product_T SET ProductStandardPrice = 220 WHERE ProductID = '2';

In-Class Exercise: Update Records Change the ProductDescription of the product with an ID of “2” into “Tea Table” Answer: UPDATE Product_T SET ProductDescription = 'Tea Table' WHERE ProductID = '2';

Obtaining CreatePVFC10e.sql Scripts Download CreatePVFC10e.sql script Located in “Software&Tutorials” in LIS569 UBLearns space Save it in a place that you can easily find (e.g., Desktop) Open the script in a text editor (e.g., Notepad) Double click on the file should do it Read through the script To get a basic idea what it does Revisit the ERD on Hoffer et al Page 96

Running CreatePVFC10e.sql Script In Navicat Console window, select “File”  “Load” or directly click “Load” icon on the top In the new dialogue window, locate on your computer CreatePVFC10e.sql and click “Open” Set file type as “SQL Script Files” if necessary You should now notice the script is loaded into the console window Click “Enter” key on your keyboard to run it

Resulting Tables in the PVFC Database

SELECT Statement Used for queries on single or multiple tables Clauses of the SELECT statement: SELECT 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 WHERE Indicate the conditions under which a row will be included in the result GROUP BY Indicate categorization of results HAVING Indicate the conditions under which a category (group) will be included ORDER BY Sorts the result according to specified criteria

SQL statement processing order

SELECT Example Find products with standard price less than $275 SELECT ProductDescription, ProductStandardPrice FROM Product_T WHERE ProductStandardPrice < 275;

SELECT: Using Alias Alias is an alternative column or table name SELECT CUST.CustomerName AS Name, CUST.CustomerAddress AS Address FROM Customer_T AS CUST WHERE CUST.CustomerName = 'Home Furnishings';

SELECT: Using a Function Using the COUNT aggregate function to find totals SELECT COUNT(*) FROM OrderLine_T WHERE OrderID = 1004; Note: with aggregate functions you can’t have single-valued columns included in the SELECT clause, unless they are included in the GROUP BY clause

Boolean Operators AND, OR, and NOT Operators for customizing conditions in WHERE clause SELECT ProductDescription, ProductFinish, ProductStandardPrice FROM Product_T WHERE ProductDescription LIKE '%Desk' OR ProductDescription LIKE '%Table' AND ProductStandardPrice > 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.

Query Result

Figure 6-9 Boolean query without use of parentheses

Boolean Operators (Cont’) With parentheses…these override the normal precedence of Boolean operators SELECT ProductDescription, ProductFinish, ProductStandardPrice FROM Product_T WHERE (ProductDescription LIKE '%Desk' OR ProductDescription LIKE '%Table') AND ProductStandardPrice > 300; Note: by default, the AND operator takes precedence over the OR operator. With parentheses, you can make the OR take place before the AND.

Query Result

Figure 6-9 Boolean query with use of parentheses

Sorting Results with ORDER BY Sort the results first by CustomerState, and within a state by the CustomerName SELECT CustomerName, CustomerCity, CustomerState FROM Customer_T WHERE CustomerState IN ('FL', 'TX', 'CA', 'HI') ORDER BY CustomerState, CustomerName; Note: the IN operator in this example allows you to include rows whose CustomerState value is either FL, TX, CA, or HI. It is more efficient than separate OR conditions.

Query Result

Qualifying Results by Categories Using HAVING For use with GROUP BY SELECT CustomerState, COUNT(CustomerState) FROM Customer_T GROUP BY CustomerState HAVING COUNT(CustomerState) > 1; Note: Like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those groups with total numbers greater than 1 will be included in final result.

Query Result

Practice, Practice, Practice! Install Navicat Lite on your computer Download from UBLearns’ “Software&Tutorials” section Practice commands illustrated in today’s class Especially those you had difficulties with Practice other examples used in Chapter 6 Some (Oracle) queries listed in the textbook may not work. Try to modify them so that they will work on MySQL Complete HW3 (due 3/18)