קורס קבצים ובסיסי נתונים

Slides:



Advertisements
Similar presentations
1 Relational Algebra & Calculus Chapter 4, Part A (Relational Algebra) Query Formulation Exercise.
Advertisements

1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
1 Database Systems ( 資料庫系統 ) October 22/24, 2007 Lecture #5.
Review Session ER and Relational –ER  Relational –Constraints, Weak Entities, Aggregation, ISA Relational Algebra  Relational Calculus –Selections/Projections/Joins/Division.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
CS 166: Database Management Systems
SQL and Relational Algebra Zaki Malik September 02, 2008.
SQL.
SQL: The Query Language Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY courtesy of Joe Hellerstein and etc for some slides.
SQL Part II: Advanced Queries. 421B: Database Systems - SQL Queries II 2 Aggregation q Significant extension of relational algebra q “Count the number.
CS 405G: Introduction to Database Systems
CMPT 258 Database Systems SQL: Queries, Constraints, Triggers (Chapter 5) Part II home.manhattan.edu/~tina.tian.
SQL Review.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
1 Reminder We have covered: –Creating tables –Converting ER diagrams to table definitions Today we’ll talk about: –Altering tables –Inserting and deleting.
SQL 2 – The Sequel R&G, Chapter 5 Lecture 10. Administrivia Homework 2 assignment now available –Due a week from Sunday Midterm exam will be evening of.
1 SQL (Simple Query Language). 2 Query Components A query can contain the following clauses –select –from –where –group by –having –order by Only select.
1 Views and Null values. 2 What does this return? SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bid and B.color=‘red’ GROUP BY B.bid For.
1 Sub-queries and Views. 2 A Complex Query We would like to create a table containing 3 columns: –Sailor id –Sailor age –Age of the oldest Sailor How.
1 Views. 2 Views A view is a "virtual table" defined using a query You can use a view as if it were a table, even though it doesn't contain data The view.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation –Adding columns –Changing columns’ definition –Dropping columns.
1 Rewriting Minus Queries Using Not In SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ MINUS.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 The Oracle Database System Querying the Data Database Course The Hebrew University of Jerusalem.
1 Views. 2 What are views good for? (1) Simplifying complex queries: We saw one example. Here is another that allows the user to "pretend" that there.
1 Rewriting Intersect Queries Using In SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ INTERSECT.
1 Advanced SQL. 2 Consider the following relations: –pupil (pupil_name, address, class, birthyear) –subject (subject_name, class, teacher) –grades (pupil_name,
Exercises Find the names of sailors who’ve reserved boat #103 { N |  S  Sailors (S.name = N.name   R  Reserves(S.sid = R.sid  R.bid = 103)) }
Chapter 5.  Data Manipulation Language (DML): subset of SQL which allows users to create queries and to insert, delete and modify rows.  Data Definition.
LeongHW, SoC, NUS (UIT2201: Database) Page 1 © Leong Hon Wai, Animation of SQL Queries To illustrate three SQL queries: –Q1: simple select (one.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L6_SQL(1) 1 SQL: Queries, Constraints, Triggers Chapter 5 – Part 1.
10/20/20151 Introduction to SQL and the Relational Model ICOS Big Data Summer Camp June 2, 2015 Mike Anderson (slides from Mike Cafarella)
SQL Examples CS3754 Class Note 11 CS3754 Class Note 11, John Shieh,
SQL 2 Introduction Structured Query Language (SQL): the most widely used commercial relational database language Originally.
ICS 321 Fall 2009 SQL: Queries, Constraints, Triggers Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 9/8/20091Lipyeow.
1 Database Systems ( 資料庫系統 ) October 24, 2005 Lecture #5.
The Oracle Database System. Connecting to the Database At the command line prompt, write: sqlplus In the beginning your password.
CMPT 258 Database Systems SQL Queries (Chapter 5).
SQL II.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
CSCI 4333 Database Design and Implementation – Exercise (2) Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
SQL: The Query Language Part 1 R &G - Chapter 5 The important thing is not to stop questioning. Albert Einstein.
Spring 2011 ITCS3160: Database Design and Implementation Hands-on Learning.
DataBase - Check 01 DataBase 2 nd year Computer Science & Engineer 1.
1 SQL Structured Query Language. Query Language SQL is a query language Used to examine data in the database SQL queries do not change the contents of.
1 SQL Structured Query Language. Query Language SQL is a query language Used to examine data in the database SQL queries do not change the contents of.
SQL Database Management Systems, 3rd ed., Ramakrishnan and Gehrke, Chapter 5.
Relational Calculus Database Management Systems, 3rd ed., Ramakrishnan and Gehrke, Chapter 4.
Database Systems (資料庫系統)
Basic SQL Queries Go over example queries, like 10 > ALL.
COP Introduction to Database Structures
© פרופ' יהושע שגיב, האוניברסיטה העברית
Structured Query Language
01/31/11 SQL Examples Edited by John Shieh CS3754 Classnote #10.
SQL The Query Language R & G - Chapter 5
Database Systems October 14, 2009 Lecture #5.
DB Review.
Database Systems (資料庫系統)
Database Applications (15-415) SQL-Part II Lecture 9, February 04, 2018 Mohammad Hammoud.
Database Systems 10/13/2010 Lecture #4.
CS 405G: Introduction to Database Systems
CSCI 6315 Applied Database Systems – Exercise (3)
Relational Calculus.
SQL: The Query Language Part 1
? Data Science 100 Databases Part 2 (The SQL) Slides by:
CS4222 Principles of Database System
SQL: Structured Query Language
Textbook Chapter 9 (incl. example queries at end)
SQL: The Query Language (Part III)
Relational Calculus Chapter 4 – Part II.
Presentation transcript:

קורס קבצים ובסיסי נתונים SQL Structured Query Language (Part 2) © פרופ' יהושע שגיב, האוניברסיטה העברית

שפת SQL שפת שאילתה מסחרית למסדי נתונים טבלאיים כיום, כמעט כל מערכות מסדי הנתונים משתמשות בה כוללת: DDL = Data Definition Language Creating tables, views, indexes, triggers, assertions DML = Data Manipulation Language Insertions, Queries, Updates, Deletes

שאילתת SQL שאילתה כוללת את החלקים הבאים : Select From Where Group By Having Order By שאילתה לא חייבת לכלול את כל המרכיבים מסדי נתונים תשס"ג הסדר בין מרכיבי שאילתה תמיד נשמר

שאילתת SQL בסיסית SELECT [Distinct] target-list FROM relation-list WHERE condition; relation-list: רשימת היחסים המשתתפים בשאילתה target-list: רשימת התכונות שעליהן מתבצעת הטלת התוצאה condition: תנאי בוליאני DISTINCT: הורדת כפילויות מהתוצאה

הסמנטיקה של שאילתה A1,…,An((r1 … rm)) Select Distinct A1,…,An From r1,…,rm Where  A1,…,An((r1 … rm))

שאילתה בלא Where A1,…,An(r1 … rm) Select Distinct A1,…,An From r1,…,rm A1,…,An(r1 … rm)

שאילתה בלא הטלה Select Distinct * From r1,…,rm Where  (r1 … rm)

שאילתה בלא בחירה ובלא הטלה Select Distinct * From r1,…,rm (r1 … rm)

טבלאות דוגמה Sailors sid sname rating age 22 31 58 Dustin Lubber Rusty 7 8 10 45.0 55.5 35.0 Boats bid bname color 101 103 Nancy Gloria red green Reserves sid bid day 22 58 101 103 10/10/02 11/12/02

שמות השייטים שהזמינו סירה אדומה לפחות פעם אחת Select sname From Sailors S, Reserves R, Boats B Where S.sid = R.sid and B.bid = R.bid and color = ‘red’; Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שמות של שייטים שמעולם לא הזמינו סירה אדומה (גרסה א') Sailors that reserved a red boat All sailors Select sname From Sailors Minus Select sname From Sailors S, Reserves R, Boats B Where S.sid = R.sid and B.bid = R.bid and color = ‘red’; Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שמות של שייטים שמעולם לא הזמינו סירה אדומה (גרסה ב') Select sname From Sailors Where sid not in (Select R.sid From Reserves R, Boats B Where R.bid = B.bid and color = ‘red’); All sailors that are not in… Sailors that reserved a red boat Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שמות של שייטים שמעולם לא הזמינו סירה אדומה (גרסה ג') Select sname From Sailors S Where not exists (Select * From Reserves R, Boats B Where S.sid = R.sid and B.bid = R.bid and color = ‘red’); מדוע היחס Sailors לא מופיע בפסוקית From של תת השאילתה? Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שאילתות לביטוי הכלה B  A  B – A =  In B and not in A A B A B not in B  A  B – A =  not exists מסדי נתונים תשס"ג

שייט שהזמין את כל הסירות שייט S שקבוצת הסירות שהזמין מכילה את קבוצת הסירות שיש ביחס Boats שייט S שעבורו לא קיימת סירה B ביחס Boats שהוא לא הזמין שייט S שעבורו לא קיימת (not exists) סירה B ביחס Boats כך ש-B אינה בקבוצת הסירות (not in) שהוזמנו על ידי S

שייטים שהזמינו את כל הסירות (I) Select sname From Sailors S Where not exists (Select B.bno From Boats B Where B.bno not in (Select R.bno From Reserves R Where R.sid = S.sid)); סירות ש-S לא הזמין סירות ש-S הזמין

שייטים שהזמינו את כל הסירות (II) Select sname From Sailors S Where not exists (Select bno From Boats B Minus Select R.bno From Reserves R Where R.sid = S.sid);

שייטים שהזמינו את כל הסירות (III) Select sname From Sailors S Where not exists (Select * From Boats B Where not exists ( Select * From Reserves R Where R.bid = B.bid and R.sid = S.sid));

שאילתות SQL עם הקבצה Aggregate Queries

שאילתות עם הקבצה מוסיפים לשאילתות פסוקיות ליצירת הקבצה: Select From Where Group By Having Order By Aggregation

פונקציות ההקבצה פונקציות ההקבצה (aggregate operators) ב-SQL הן: COUNT(*) COUNT([DISTINCT] A) SUM([DISTINCT] A) AVG([DISTINCT] A) MAX(A) MIN(A)

מספר הסירות שיש ביחס Boats Select count(*) From Boats; Select count(bid) From Boats; or Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

מספר הצבעים שיש לסירות Select count(distinct color) From Boats; Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

הגיל הממוצע של שייטים שהזמינו סירות אדומות Select avg(age) From Sailors S, Boats B, Reserves R Where S.sid = R.sid and B.bid = R.bid and color = ‘red’; Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

מהו הגיל של השייט המבוגר ביותר? Select sname, max(age) From Sailors; Is this correct?  Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

מהו הגיל של השייט המבוגר ביותר? (גרסה I) Select sname, age From Sailors Where age = ( Select max(age) From Sailors); Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

מהו הגיל של השייט המבוגר ביותר? (גרסה II) Select sname, age From Sailors Where age >=all(Select age From Sailors); Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שאילתות SQL בסיסיות SELECT [Distinct] target-list FROM relation-list WHERE condition GROUP BY grouping-list HAVING group-condition; target-list: שדות שמופיעים ב- grouping-list ופונקציות הקבצה group-condition: תנאי על פונקציות הקבצה ושדות שמופיעים ב- grouping-list

חישוב שאילתה מחשבים מכפלה קרטזית של היחסים שמופיעים ב- From מוחקים רשומות שלא מקיימות את התנאי המופיע ב- Where מחלקים את הרשומות לקבוצות על פי ערכיהן בשדות המופיעים ב- grouping-list של ה- Group by מוחקים קבוצות שאינן מקיימות את התנאי המופיע ב- Having (group-condition) מכל קבוצה יוצרים רשומת תוצאה אחת על פי המופיע ב- Select

לכל דרגה, ממוצע הגילאים של שייטים מדרגה זו כיצד מחשבים את הממוצע? כיצד בוחרים את השדות שלפיהם תתבצע ההקבצה (שימו לב ל-"לכל")

לכל דרגה, ממוצע הגילאים של שייטים מדרגה זו Select rating, avg(age) From Sailors Group By rating; Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

40 55.5 34 Sailors sid sname rating age 22 31 58 63 78 84 Dustin Lubber Rusty Fluffy Morley Popeye 7 8 10 45.0 55.5 35.0 44.0 31.0 33.0 Sailors sid sname rating age 22 63 78 31 58 84 Dustin Fluffy Morley Lubber Rusty Popeye 7 8 10 45.0 44.0 31.0 55.5 35.0 33.0 40 55.5 34

מספר ההזמנות לכל סירה אדומה Select B.bid, count(*) as ResNo From Boats B, Reserves R Where R.bid = B.bid and B.color = ‘red’ Group By B.bid; האם ניתן להעביר את התנאי על הצבע ל- Having? Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שמות של סירות שהוזמנו בלא יותר מ-5 ימים שונים Select bname From Boats B, Reserves R Where B.bid = R.bid Group By B.bid, bname Having count(distinct day)<=5; האם ניתן להעביר את התנאי שמופיע ב- Having ל-Where? Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

הצבע שיש ממנו הכי הרבה סירות האם השאילתה הבאה נכונה? Select color From Boats B Group By color Having max(count(bid)); מה הבעיה ?

הצבע שיש ממנו הכי הרבה סירות Select color From Boats B Group By color Having count(bid) >=all (Select count(bid) Group By color);

שימוש בהקבצה לביטוי של כמתים ניתן לעיתים להשתמש בפונקציות הקבצה כדי לבטא תנאי קיים (Exists) לכל (For all)

צבע שקיימת רק סירה אחת מצבע זה Select color From Boats B1 Where not exists ( Select * From Boats B2 Where B1.bno <> B2.bno and B1.color = B2.color); בלא הקבצה כיצד ניתן להשתמש כאן בהקבצה? Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

צבע שקיימת רק סירה אחת מצבע זה עם הקבצה Select color From Boats Group By color Having count(bid) = 1; Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שייטים שהזמינו את כל הסירות Select sname From Sailors S Where not exists (Select B.bno From Boats B Where B.bno not in (Select R.bno From Reserves R Where R.sid = S.sid)); בלי הקבצה, כפי שראינו קודם כיצד ניתן להשתמש כאן בהקבצה?

שייטים שהזמינו את כל הסירות Select sname From Sailors S, Reserves R Where S.sid = R.sid Group By S.sid, sname Having count(distinct bno) = (Select count(bno) From Boats); עם הקבצה Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

מיון התוצאות ניתן להשתמש בפסוקית ORDER BY על מנת למיין את התוצאות של שאילתה לפי שדה אחד או יותר ניתן לקבוע האם המיון יהיה בסדר עולה ASC או יורד DESC ברירת המחדל היא סדר עולה

שמות השייטים שגילם מעל 50 בסדר עולה על פי דירוג ותת סידור יורד לפי גיל Select sname, rating, age From Sailors S Where age > 50 Order By rating Asc, age Desc Sailors(pid, sname, rating, age) Boats(bid, bname, color) Reserves(sid, bid, day)

שאילתות מורכבות מעוניינים בשאילתה שתוצאתה כוללת את שלוש העמודות הבאות: מזהה שייט גיל שייט גיל מכסימלי של כל שייטים כיצד ניתן לבצע זאת?

ניסיון 1 האם זהו פתרון נכון? Select S.sid, S.age, MAX(S.age) From Sailors S; האם זהו פתרון נכון?

ניסיון 2 האם זהו פתרון נכון? Select S.sid, S.age, MAX(S.age) From Sailors S Group By S.name, S.age; האם זהו פתרון נכון?

פתרון 1: תת-שאילתה ב- From Select S.sid, S.age, M.mxage From Sailors S,(Select MAX(S2.age) as mxage From Sailors S2) M; ניתן לכתוב תת-שאילתה ב- From ולהתייחס אל תוצאת השאילתה כאל טבלה לשאילתה ב- From יש לתת שם על ידי משתנה (M בדוגמה זו)

פתרון 2: תת-שאילתה ב- Select Select S.sid, S.age, (Select MAX(S2.age) From Sailors S2) From Sailors S; שאילתה ב- Select חייבת להחזיר ערך יחיד עבור כל שורת Select

דוגמה נוספת לתת-שאילתה ב- Select Select S.sid, S.age, (Select MAX(S2.age) From Sailors S2 Where S2.age<S.age) From Sailors S; השאילתה מחזירה, לכל שייט S, את הגיל של השייט המבוגר ביותר מבין השייטים הצעירים מ- S שימו לב לשימוש של המשתנה S, שמוגדר מחוץ לשאילתה הפנימית, בשאילתה

דוגמה נוספת לתת-שאילתה ב- From Select S.sid, S.age, M.mxage From Sailors S, (Select MAX(S2.age) as mxage From Sailors S2 Where S2.age<S.age); האם זוהי שאילתה תקינה?

פתרון 3: טבלת ביניים ניתן לייצר טבלה שהיא תוצאה של שאילתה Create Table MaxAge as Select MAX(S.age) as mxage From Sailors S; Select S.sid, S.age, M.mxage From Sailors S, MaxAge M;

תצפיות (Views) תצפית (View) היא מעין טבלה וירטואלית המוגדרת בעזרת שאילתה ניתן להתייחס ל-View כאל טבלה ולהשתמש בו כטבלה אף שהוא לא מכיל נתונים (פרט למקרה מיוחד שנקרא materialized view) תצפית מאפשרת למשל הסתרה של הלוגיקה של שאילתה מסובכת לשימוש בשאילתות עתידיות

תצפיות יתרונות: חסרונות: לא נדרשת הקצאת זיכרון כמו לטבלה עדכון טבלאות לא דורש עדכון של תצפיות שמתבססות על טבלאות אלו (מדוע?) מאפשר אופטימיזציה של שאילתות שתצפית משולבת בהן חסרונות: עלות של זמן חישוב ושל משאבי חישוב בעת חישוב שאילתות מעל תצפיות תצפית לא נשמרת אם נעשית מחיקה של טבלאות שהתצפית מתבססת עליהן

הגדרת תצפיות (Views) במקום לייצר טבלה ניתן לייצר תצפית (View) Create Or Replace View MaxAge as Select MAX(S.age) as mxage From Sailors S; Select S.sid, S.age, M.mxage From Sailors S, MaxAge M;

דוגמה נוספת לשימוש בתצפית Create Or Replace View MaxAges as Select S1.sid, S2.age as mxage From Sailors S1, Sailors S2 Where S2.age = (Select MAX(S3.age) From Sailors S3 Where S3.age < S1.age); Select S.sid, S.age, M.mxage From Sailors S, MaxAges M Where S.sid = M.sid;

Grades(Login, Exercise, Grade) תצפיות להגבלת גישה נתונה הטבלה הבאה: Grades(Login, Exercise, Grade) רוצים שמשתמש יוכל לראות את הציונים שלו בלבד יוצרים את התצפית הבאה ומעניקים הרשאות לשאילתות על התצפית Create Or Replace View UserGrades as Select * From Grades Where Login = User; שדה שמגדירה המערכת ומכיל את שם המשתמש