Relational Operators, SQL, and Access Query ISYS 562.

Slides:



Advertisements
Similar presentations
© Abdou Illia MIS Spring 2014
Advertisements

TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
SQL Sub (or Nested ) Query. Examples Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student.
Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
SQLPlus Commands. Oracle Account Server: libra.sfsu.edu Telnet: libra.sfsu.edu How to use Oracle: –
Structured Query Language Review ISYS 650. Language Overview Three major components: –Data definition language, DDL Create, Drop and Alter Tables or Views.
Introduction to Structured Query Language, SQL. SQL Select Command SELECT * FROM tableName WHERE criteria;
Basic SQL Select Commands. Basic Relational Query Operations Selection Projection Natural Join Sorting Aggregation: Max, Min, Sum, Count, Avg –Total –Sub.
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
Introduction to Access BUS 782. Access Objects Tables –Open –Design –New –Wizard Queries Forms Reports Pages.
Structured Query Language Part I Chapter Three CIS 218.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Relational Algebra. Set operations: Union, intersection, difference, Cartesian product Relational operations: Selection, projection, join, division.
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Querying Database. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy Calculated.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
Chapter 6 SQL: Data Manipulation Cont’d. 2 ANY and ALL u ANY and ALL used with subqueries that produce single column of numbers u ALL –Condition only.
Other Joins ISYS 464. Outer Join Records in a relation that do not have matching values are included in the result relation. Missing values are set to.
Introduction to Structured Query Language SQL. SQL Select Command SELECT * FROM tableName WHERE criteria;
Concepts of Database Management, Fifth Edition
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Relational Query Operators (ii). Other Joins Theta join: Apply any specified condition on the product of two relations. Example: BoyStudent: BID, Bname,
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
Agenda TMA01 M876 Block 3 – Using SQL Structured Query Language - SQL A non-procedural language to –Create database and relation structures. –Perform.
Oracle Database Administration Lecture 2 SQL language.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
BACS--485 SQL 11 BACS 485 Structured Query Language.
INLS 623– S QL Instructor: Jason Carter. SQL SELECT DISTINCT SELECT DISTINCT column_name, column_name FROM table_name ;
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) Structured Query Language Introduction to SQL Structured Query Language.
Advanced SQL for Decision Support ISYS 650. Set Operators Union Intersect Difference Cartesian product.
Using Special Operators (LIKE and IN)
Structured Query Language. Group Functions What are group functions ? Group Functions Group functions operate on sets of rows to give one result per group.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 5 © Akhilesh Bajaj, 2000, 2002, 2003, All.
Introduction to Access ISYS 363. Creating a New Database MS Office button/New –Blank database –New database name and location.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Relational Query Operators (Algebra). Relational Query Operators Set operations: Union, intersection, difference, Cartesian product Relational operations:
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
Querying Database ISYS 363.
Introduction to Query Language and SQL. Basic Query Language Operators Selection Projection Join Aggregates –Sum, Count, Max, Min, Avg SubTotal Calculated.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Introduction to Access BUS 782. Creating a New Database MS Office button/New –Blank database –New database name and location.
Introduction to Access ISYS 363. Access Objects Tables –Open –Design –New –Wizard Queries Forms Reports Pages.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
SQL Miscellaneous Topics. Views A database view is: – a virtual or logical table based on a query. – a stored query. CREATE VIEW viewname AS query; –CREATE.
Introduction to Access ISYS 363. Access Objects Tables –Open a table: Double click the table name –Home/View: Datasheet view Design view Queries Forms.
Set Operators. Union Intersect Difference Cartesian product.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
Chapter 3 Introduction to SQL(3)
The Database Exercises Fall, 2009.
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Lecture#7: Fun with SQL (Part 2)
Chapter Name SQL: Data Manipulation
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Querying Database ISYS 363.
Creating and Maintaining
Database systems Lecture 3 – SQL + CRUD
Structured Query Language
Agenda SQL Queries Join. MGS 4020 Business Intelligence Relational Algebra and Structured Query Language Jul 3, 2018.
CSC 453 Database Systems Lecture
Presentation transcript:

Relational Operators, SQL, and Access Query ISYS 562

Relational Operators Set operators: Union, intersection, difference, Cartesian product Relational operators: Selection, projection, join, etc.

Union Set1={A, B, C} Set2={C, D, E} Union: Members in Set 1 or in Set 2 –Set1 U Set 2 = {A, B, C, D, E} Or

Intersect Members in Set 1 and in Set 2 –Set1 ∩ Set2={C} And

Difference Set1 – Set2: Members in Set1 but not in set2 = {A,B} Set2 – Set1:Members in Set2 but not in set1 = {D, E} Set1-Set2 ≠ Set2 – Set1

Use Union and Difference to Simulate Intersect Set1 ∩ Set2 = Set1 – (Set1 – Set2)

Files as Sets Business students’ file: BusSt Science student’s file: SciSt –BusSt U SciSt: –BusSt ∩ SciSt –BusSt – SciSt Spring 04 Student file: S04St Fall 04 Student file: F04St –S04St – F04St –F04St – S04St

Product Set1 = {a, b, c} Set2 = {X, Y, Z} Set1 X Set2 = {aX, aY aZ, bX, bY, bZ, cX, cY, cZ}

Faculty File: FIDFname F1Chao F2Smith Student File: SIDSname FID S1PeterF1 S2PaulF2 S3SmithF1 Faculty X Student:

Projection Projection operation works on a single relation and defines a vertical subset of the relation, extracting the values of specified attributes.

Duplications due to Projection WorkLog file: EIDPjIDHours E1P25 E1P14 E2P26 E2P18 E3P14 Project eid from (WorkLog) Project Hours from (WorkLog) In practice, users determine whether to eliminate duplicates: –SELECT DISTINCT EID FROM WorkLog; –SELECT HOURS FROM WorkLog WHERE PjID = ‘P1’;

Natural Join The two relations must have common attributes. Combines two relations to form a new relation where records of the two relations are combined if the common attributes have the same value. One occurrence of each common attribute is eliminated.

Aggregate Functions Max, Min, Sum, Count, Avg Aggregates by grouping fields

Student: SID,Sname, GPA, Sex, Major Enroll: SID, CID Course: CID, Cname, Credits Queries: –Number of students in each course CID, CName, NumbeOfStudents –Total credits for each student: SID, Sname, TotalCredits

Outer Join Records in a relation that do not have matching values are included in the result relation. Missing values are set to null.

Outer Join Exmple Product Table: –PIDPname –P1TV –P2VCR –P3Computer –P4Tape –P5DVD TotalSales –PIDTotalSales –P150 –P360 –P540 Product Join TotalSales Product OuterJoin Totalsales

Branch: BIDCity B1SF B2SM B3SJ Full Outer Join: BIDCityPID B1SFP3 B2SMNull B3SJP2 NullLAP1 Right Outer Join: BIDCityPID B1SFP3 B3SJP2 NullLAP1 Property: PIDCity P1LA P2SJ P3SF Left Outer Join: BIDCityPID B1SFP3 B2SMNull B3SJP2

Structured Query Language

Language Overview Two major components: –Data definition language Create Table –Data manipulation language Updating database: –Insert, Delete, Update Query database: –Select

CREATE TABLE CREATE TABLE tableName(fields and data type separated by commas); Ex. –CREATE TABLE employee( eid CHAR(5), ename VARCHAR(40), sex CHAR, salary NUMERIC(9,2), hire_Date DATE);

SQL Insert Command INSERT INTO tableName VALUES (field values separated by commas); INSERT INTO tableName (Column names separated by commas)VALUES (field values separated by commas); Ex 1. Customer table with CID, CNAME, CITY, RATING. a. INSERT INTO CUSTOMER VALUES (‘C1’, ‘SMITH’, ‘SF’, ‘A’); b. INSERT INTO CUSTOMER (CID, CNAME,RATING) VALUES (‘C1’, ‘SMITH’, ‘A’);

SQL Delete Command DELETE FROM tableName [WHERE criteria]; Ex 1. Delete a record from the Customer table. DELETE FROM CUSTOMER WHERE CID = ‘C1’;

SQL Update Command UPDATE tableName SET field = new value [WHERE criteria]; Ex 1. UPDATE CUSTOMER SET RATING = ‘A’ WHERE CID=‘C1’; Ex 2. UPDATE CUSTOMER SET CITY = ‘SF’, SET RATING = ‘A’ WHERE CID=‘C1’;

Selection SELECT * FROM tableName WHERE criteria; Criteria: –=, <>,, = –(), NOT, AND, OR –BETWEEN WHERE salary BETWEEN 1000 AND 10000; –LIKE, NOT LIKE: *, %, _ WHERE ename LIKE “C*” –IN, NOT IN WHERE eid IN (‘e1’,’e3’) –IS NULL WHERE rating IS NULL

Projection: –SELECT fields FROM tableName WHERE criteria; –SELECT DISTINCT fields FROM tableName WHERE criteria; –Field name alias: AS Ex: SELECT eid AS empID, ename AS empName FROM emp; Product: –SELECT fields FROM table1, table2; –table name alias: Ex: SELECT s.*, f.* FROM student s, faculty f;

Natural Join SELECT * FROM table1 NATURAL JOIN table2; –SELECT * FROM student NATURAL JOIN faculty; SELECT * FROM table1, table2 WHERE table1.JoinAttribute = table2.JoinAttribute; –SELECT * FROM student, faculty WHERE student.fid = faculty.fid; Table name alias: –SELECT * FROM student s, faculty f WHERE s.fid = f.fid; Other forms: –FROM student s JOIN faculty f ON s.fid=f.fid; –FROM student s INNER JOIN faculty f ON s.fid=f.fid; –FROM student JOIN faculty USING fid; Not supported by Oracle

Sorting ORDER BY fieldName [DESC] –SELECT * FROM student ORDER BY sname; –SELECT * FROM student ORDER BY sname DESC; More than one field: –SELECT * FROM student ORDER BY major, sname;

Set Operators Union compatible (SELECT * FROM table1) –UNION (SELECT * FROM table2); –INTERSECT (SELECT * FROM table2); –MINUS (SELECT * FROM table2);

Aggregates SELECT AVG(fieldName) FROM tableName; –COUNT(fieldName), COUNT(*) –COUNT(DISTINCT fieldName) –MAX(fieldName) –MIN(fieldName) –SUM(fieldName) More than one aggregate: SELECT AVG(fieldName), MAX(fieldName), MIN(fieldName) FROM tableName; With alias: –SELECT AVG(gpa) AS avggpa, COUNT(sid) AS scount FROM student;

GROUP BY SELECT groupingField, function(fieldname) FROM tablename GROUP BY groupingField; –SELECT major, count(sid) FROM student GROUP BY major; All field names in the GROUP BY clause must be included in the retrieved fields. –Compute the number of courses taken by each student: –SELECT sid, sname, COUNT(cid) FROM student NATURAL JOIN enroll GROUP BY sid, sname; WHERE clause must come before the GROUP BY: –SELECT major, count(sid) FROM student WHERE GPA > 3.0 GROUP BY major;

Adding a Criteria for the Sub Totals with HAVING SELECT major, count(sid) FROM student –GROUP BY major –HAVING count(sid) > 5; Sometime the aggregates are not required to display: –Find majors that have more than 5 students: –SELECT major FROM student GROUP BY major HAVING count(sid) > 5;

Sub (or Nested ) Query Q: Find students whose GPA is below the average. –The criteria itself required a SQL statement. –SELECT * FROM student WHERE gpa < (SELECT AVG(gpa) FROM student);

Sub Query with IN Q: Find students who take at least one course and display their ID and name. –SELECT sid, sname FROM student NATURAL JOIN enroll GROUP BY sid HAVING COUNT(cid) > 1; –SELECT sid, sname FROM student WHERE sid IN (SELECT DISTINCT sid FROM enroll); Q: Find students who take more than 5 courses and display their ID and name. –SELECT sid, sname FROM student WHERE sid IN (SELECT sid FROM enroll GROUP BY sid –HAVING COUNT(cid) > 5);

Sub Query with ALL/SOME/ANY Q: Find students whose gpa is greater than all/some bus majors’ gpa: –SELECT sid, sname FROM student WHERE gpa > ALL(SELECT gpa FROM student WHERE major=‘bus’); –SELECT sid, sname FROM student WHERE gpa > SOME (SELECT gpa FROM student WHERE major=‘bus’); –SELECT sid, sname FROM student WHERE gpa > ANY (SELECT gpa FROM student WHERE major=‘bus’);

Access Query Selection, Projection, Product, Join, Outer Join Calculated field, alias, parameter query GroupBy, Having Union, Intersect, Minus Wizards: CrossTab, Find Duplicates, Find Unmatched Others: –Make table, update

Examples University database: –Student: SID, Sname, Sex, Major, GPA, FID –Account: SID, Balance –Faculty: FID, Fname –Course: CID, Cname, Credits –StudentCourse: SID, CID Questions: –Display student names who owe at least –Display faculty names who advise at least one student –Display faculty names who do not advise any student –Display faculty names who advise more than 2 students –Display total credits for all students –Find students enrolled in 263 –Find students enrolled in 263 and 363