CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Relational Schema and SQL Queries James Wang.

Slides:



Advertisements
Similar presentations
Chapter 4 Joining Multiple Tables
Advertisements

Review Indra Budi Fakultas Ilmu Komputer UI 2 Database Introduction Database vs File Processing Main purpose of database Database Actors.
Review for Final Test Indra Budi
Greg Riccardi Florida State University. Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)MySQL Recap.
Database Systems: Design, Implementation, and Management Tenth Edition
Introduction to Structured Query Language (SQL)
Midterm Review Lecture 14b. 14 Lectures So Far 1.Introduction 2.The Relational Model 3.Disks and Files 4.Relational Algebra 5.File Org, Indexes 6.Relational.
Introduction to Structured Query Language (SQL)
Introduction to SQL, the Structured Query Language Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 16, 2003.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
CIS552SQL1 Data Definition Language Insertions Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations.
CSC3530 Software Technology Tutorial 4 SQL. SQL / RDBMS Structured Query Language 4 th Generation programming language Tell computer what to do instead.
Chapter 7: SQL, the Structured Query Language Soid Quintero & Ervi Bongso CS157B.
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
Introduction to SQL J.-S. Chou Assistant Professor.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
3.1 Chapter 3: SQL Schema used in examples p (omit 3.8.2, , 3.11)
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
Oracle Database Administration Lecture 2 SQL language.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
CSC 2720 Building Web Applications Database and SQL.
Structured Query Language Chris Nelson CS 157B Spring 2008.
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
Information Technologies and Microsoft SQL Server Day 2 by Alper Özpınar
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
SQL LANGUAGE and Relational Data Model TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
1/18/00CSE 711 data mining1 What is SQL? Query language for structural databases (esp. RDB) Structured Query Language Originated from Sequel 2 by Chamberlin.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
From the Calculus to the Structured Query Language Zachary G. Ives University of Pennsylvania CIS 550 – Database & Information Systems September 19, 2007.
1 MySQL and SQL. 2 Topics  Introducing Relational Databases  Terminology  Managing Databases MySQL and SQL.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL LANGUAGE TUTORIAL Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
 MySQL  DDL ◦ Create ◦ Alter  DML ◦ Insert ◦ Select ◦ Update ◦ Delete  DDL(again) ◦ Drop ◦ Truncate.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
How to: SQL By: Sam Loch.
More SQL: Complex Queries,
Databases.
Chapter 5 Introduction to SQL.
MySQL Subquery Source: Dev.MySql.com
Database Systems: Design, Implementation, and Management Tenth Edition
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Chapter 4 Summary Query.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Database systems Lecture 3 – SQL + CRUD
Chapter 7 Introduction to Structured Query Language (SQL)
Contents Preface I Introduction Lesson Objectives I-2
Database Systems: Design, Implementation, and Management Tenth Edition
SQL: Structured Query Language
Presentation transcript:

CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Relational Schema and SQL Queries James Wang

2 Partial ER Diagram for MeTube Account Media type username password Name type path Datetime Downloaded By Uploaded by IP Datetime M N 1 N

3 Create Table Create the Account table: CREATE TABLE ACCOUNT ( type INTEGER, username varchar(100), password varchar(100), varchar(2048) primary key ); Is it good to use as the primary key for ACCOUNT? sometimes is very long. String comparison is more expensive. Be better create an artificial integer key. Some DBMS systems do not allow long key.

4 The use of artificial key Create the Account table: CREATE TABLE ACCOUNT ( AccountID INTEGER AUTO_INCREMENT PRIMARY KEY, VARCHAR(1024) NOT NULL, username VARCHAR(100) NOT NULL, password VARCHAR(100) NOT NULL, type TINYINT NOT NULL ); Create the Media table: CREATE TABLE MEDIA ( MediaID INTEGER AUTO_INCREMENT PRIMARY KEY, type INTEGER NOT NULL, name varchar(100) NOT NULL, path varchar(4096) NOT NULL, lastaccess DATETIME NOT NULL );

5 Create Associative Table It is easy to represent an M:N relationship in ER diagram. However, in the relational model, an associative relation must be used to represent the M:N relationship Create the Downloads table: CREATE TABLE DOWNLOADS ( DownloadID INTEGER AUTO_INCREMENT PRIMARY KEY, AccountID INTEGER REFERENCES ACCOUNT(AccountID), MediaID INTEGER NOT NULL REFERENCES MEDIA(MediaID), ip varchar(128) NOT NULL, downloadtime DATETIME NOT NULL, FOREIGN KEY(AccountID) REFERENCES ACCOUNT(AccountID), FOREIGN KEY(MediaID) REFERENCES MEDIA(MediaID) );

6 Deal with 1:N relationship We don’t need to create a table for uploadedby relationship because it is a 1:N relationship. In the relational model, relationships are represented through foreign keys. ALTER TABLE MEDIA ADD COLUMN AccountID INTEGER NOT NULL; ALTER TABLE MEDIA ADD COLUMN uploadtime DATETIME; ALTER TABLE MEDIA ADD FOREIGN KEY(AccountID) REFERENCES ACCOUNT(AccountID);

7 A Improved Version of ER Diagram Account Media type username password Name type path Lastaccesstime AD Uploadedby IP Downloadtime M N 1 N Uploadtime MediaID Downloads 1 MD 1 DownloadID AccountID

8 SQL Queries List all media files in the MeTube system: SELECT * FROM MEDIA WHERE 1; Show media name and path that were uploaded before 09/20/ SELECT name, path FROM MEDIA WHERE uploadTime < ‘ ’; List the image files (type = 1) uploaded by User #1. SELECT * FROM MEDIA WHERE type = 1 AND AccountID = 1;

9 SQL Queries (more) List all media files downloaded by user “xyz” in the MeTube system: SELECT username, name, path, ip FROM ACCOUNT, MEDIA, DOWNLOADS WHERE username =‘xyz’ AND ACCOUNT.AccountID = DOWNLOADS.AccountID AND DOWNLOADS.MediaID = MEDIA.MediaID; Find the name of the most recently downloaded media. SELECT name, downloadtime FROM MEDIA, DOWNLOADS WHERE MEDIA.MediaID = DOWNLOADS.MediaID ORDER BY downloadtime DESC LIMIT 1 ;

10 Syntax of SQL Statements SELECT [DISTINCT] {Select-List} FROM {From-List} WHERE {Qualification} Selection-List is in the form of T 1.attrib, …, T 2.attrib, …. They are the expected attributes for the returned results. From-List is a list of tables separated by comma. DISTINCT: Eliminate the redundant rows in the return results. Qualification: Conditions for a record to be selected.

11 Expressions in SQL You can apply operations on the scalars (int, float, string, datetime, etc.) in the qualification or in the select-list. SELECT UPPER(name), DATEDIFF(CURRENT_DATE, downloadtime) FROM MEDIA, DOWNLOADS WHERE MEDIA.MediaID = DOWNLOADS.MediaID AND DATEDIFF(CURRENT_DATE, downloadtime) > 2; Note on strings: Fixed (CHAR(x)) or variable length (VARCHAR(x)) Use single quotes: ’A string’ Special comparison operator: LIKE Not equal: <> Typecasting: CAST(S.sid AS VARCHAR(255))

12 Operations on Two Queries Set operations can be applied on two queries. (SELECT … FROM … WHERE …) {op} (SELECT … FROM … WHERE …) {op}: UNION, INTERSECT, MINUS/EXCEPT. Note: Not all DBMS support “MINUS/EXCEPT”. Nested Queries: IN, NOT IN EXISTS, NOT EXISTS Where to use Nested Queries? Anywhere in from-list or qualification.

13 Examples of Nested Queries Find users downloaded media 1 but not media 3: SELECT username FROM ACCOUNT, DOWNLOADS WHERE ACCOUNT.AccountID = DOWNLOADS.AccountID AND MediaID = 1 AND username NOT IN (SELECT username FROM ACCOUNT, DOWNLOADS WHERE ACCOUNT.AccountID = DOWNLOADS.AccountID AND MediaID = 3 ); Can we write a query by using EXISTS or NOT EXISTS to return the same results? How about nesting query in the from-list? SELECT UA.username FROM ( SELECT ACCOUNT.username, DOWNLOADS.MediaID FROM ACCOUNT, DOWNLOADS WHERE ACCOUNT.AccountID = DOWNLOADS.AccountID AND MediaID =1 ) AS UA WHERE UA.username NOT IN ( SELECT username FROM ACCOUNT, DOWNLOADS WHERE ACCOUNT.AccountID = DOWNLOADS.AccountID AND MediaID =3 )

14 Aggregation GROUP BY SELECT {group-attribs}, {aggregate-operator}(attrib) FROM {relation} T1, {relation} T2, … WHERE {predicates} GROUP BY {group-list} Aggregate operators AVG, COUNT, SUM, MAX, MIN DISTINCT keyword for AVG, COUNT, SUM Example: Find the numbers of times that users downloaded media 1 respectively. SELECT AccountID, count( AccountID ) AS cnt FROM DOWNLOADS WHERE MediaID =1 GROUP BY AccountID ORDER BY cnt

15 HAVING Clause What If you want to only show some groups? The HAVING clause lets you do a selection based on an aggregate (there must be 1 value per group): SELECT AccountID, count( AccountID ) AS cnt FROM DOWNLOADS WHERE MediaID =1 GROUP BY AccountID HAVING cnt > 1 Sometimes, we combine a nested GROUP BY query in the from-list to aggregate twice.

16 JOIN INNER JOIN: Regular JOIN will return results only when the join attribute matches in both tables involved. In MySQL JOIN == CROSS JOIN. LEFT JOIN: Besides returning results matching the join attribute in both tables. It also returns results from left table that do not have matching rows in right table. Some DBMS vendor use syntax LEFT OUTER JOIN. RIGHT JOIN: Return results from right table that table that do not have matching rows in left table. Some DBMS vendor use syntax RIHGT OUTER JOIN

17 Beyond SELECT INSERT: INSERT INTO T(C1, C2, …) VALUES (V1, V2, …) INSERT INTO T(C1, C2, …) SELECT …. DELETE: DELETE FROM tbl WHERE condition-list UPDATE: UPDATE tbl SET C1 = x1, C2 = x2 WHERE condition-list

18 References MySQL documentation, PHP MySQL Tutorial,