SQL: Interactive Queries (2)

Similar documents
Microsoft PowerPoint - 05-SQL3-advanced.ppt

数据库系统概论

目錄 C ontents Chapter MTA Chapter Chapter

國 立 政 治 大 學 教 育 學 系 2016 新 生 入 學 手 冊 目 錄 表 11 國 立 政 治 大 學 教 育 學 系 博 士 班 資 格 考 試 抵 免 申 請 表 論 文 題 目 申 報 暨 指 導 教 授 表 12 國 立 政 治 大 學 碩 博 士 班 論

untitled

Oracle Database 10g: SQL (OCE) 的第一堂課

Microsoft PowerPoint _代工實例-1

6-1 Table Column Data Type Row Record 1. DBMS 2. DBMS MySQL Microsoft Access SQL Server Oracle 3. ODBC SQL 1. Structured Query Language 2. IBM

學 科 100% ( 為 單 複 選 題, 每 題 2.5 分, 共 100 分 ) 1. 請 參 閱 附 圖 作 答 : (A) 選 項 A (B) 選 項 B (C) 選 項 C (D) 選 項 D Ans:D 2. 下 列 對 於 資 料 庫 正 規 化 (Normalization) 的 敘

東莞工商總會劉百樂中學

untitled

BC04 Module_antenna__ doc


Preface This guide is intended to standardize the use of the WeChat brand and ensure the brand's integrity and consistency. The guide applies to all d

<4D F736F F D205F FB942A5CEA668B443C5E9BB73A740B5D8A4E5B8C9A552B1D0A7F75FA6BFB1A4ACFC2E646F63>

穨control.PDF

Microsoft Word - 生活禮儀柯友惠981

Microsoft Word - (web)_F.1_Notes_&_Application_Form(Chi)(non-SPCCPS)_16-17.doc

Microsoft PowerPoint 馮天俊-問題分析與決策力

Microsoft Word - 論文封面 修.doc

目 录 第 一 章 电 力 行 业 内 部 控 制 操 作 指 南 概 述... 1 第 二 章 内 部 控 制 规 范 体 系 建 设 与 运 行 第 三 章 内 部 环 境 建 设 第 一 节 组 织 架 构 第 二 节 发 展 战 略 第 三 节

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

Chn 116 Neh.d.01.nis

Windows XP

untitled

DB2 (join) SQL DB2 11 SQL DB2 SQL 9.1 DB2 DB2 ( ) SQL ( ) DB2 SQL DB2 DB2 SQL DB2 DB2 SQL DB2 ( DB2 ) DB2 DB2 DB2 SQL DB2 (1) SQL (2) S

ebook46-23

Logitech Wireless Combo MK45 English

untitled

編輯要旨 一 教育部為了協助本國失學民眾 新住民及 其他國外朋友 有系統的學習華語文的 聽 說 讀 寫 算等識字能力及跨文化 適應 以培養具有基本公民素養的終身學 習者 特別委託新北市政府教育局新住民 文教輔導科團隊編輯本教材 二 依據上述目的 本教材共有六冊 並分為 六級 分級及單元名稱詳如下表

untitled

软件测试(TA07)第一学期考试

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

数据库系统概论

Lorem ipsum dolor sit amet, consectetuer adipiscing elit

國 史 館 館 刊 第 23 期 Chiang Ching-kuo s Educational Innovation in Southern Jiangxi and Its Effects ( ) Abstract Wen-yuan Chu * Chiang Ching-kuo wa

國立中山大學學位論文典藏.PDF

1. 請 先 檢 查 包 裝 內 容 物 AC750 多 模 式 無 線 分 享 器 安 裝 指 南 安 裝 指 南 CD 光 碟 BR-6208AC 電 源 供 應 器 網 路 線 2. 將 設 備 接 上 電 源, 即 可 使 用 智 慧 型 無 線 裝 置 進 行 設 定 A. 接 上 電 源

PowerPoint Presentation

ebook 165-5

Microsoft PowerPoint - STU_EC_Ch08.ppt

K7VT2_QIG_v3

Microsoft Word doc

Important Notice SUNPLUS TECHNOLOGY CO. reserves the right to change this documentation without prior notice. Information provided by SUNPLUS TECHNOLO

ENGG1410-F Tutorial 6

Process Data flow Data store External entity 6-10 Context diagram Level 0 diagram Level 1 diagram Level 2 diagram

EXCEL EXCEL

入學考試網上報名指南

Microsoft Word - template.doc

Knowledge and its Place in Nature by Hilary Kornblith

Microsoft Word 記錄附件

2015 Chinese FL Written examination

國立中山大學學位論文典藏

2015年4月11日雅思阅读预测机经(新东方版)

QQGQ2.E Power Supplies, Information Technology Equipment Including Ele... 1/10

Some experiences in working with Madagascar: installa7on & development Tengfei Wang, Peng Zou Tongji university

ch_code_infoaccess

RAID RAID 0 RAID 1 RAID 5 RAID * ( -1)* ( /2)* No Yes Yes Yes A. B. BIOS SATA C. RAID BIOS RAID ( ) D. SATA RAID/AHCI ( ) SATA M.2 SSD ( )

数据库系统概论

习题1

Microsoft PowerPoint - ch6 [相容模式]


Guide to Install SATA Hard Disks

XML SOAP DOM B2B B/S B2B B2B XML SOAP

PowerPoint Presentation

Microsoft Word - ApL Student Manual_BFE_ _final.doc

LH_Series_Rev2014.pdf

基于UML建模的管理管理信息系统项目案例导航——VB篇

有 不 同 想 法 馬 上 記 錄 下 來, 作 為 寫 作 和 較 特 殊 題 型 的 答 題 材 料 把 握 這 四 到, 再 加 上 考 試 用 書 的 重 點 整 理, 搭 配 服 用, 讓 課 文 與 你 不 再 有 距 離 2. 考 試 成 績 好 差, 心 情 也 好 差, 可 不 可

目錄

Business Objects 5.1 Windows BusinessObjects 1

99


untitled

台灣地區同學

Microsoft Word - 100碩士口試流程

1.ai

國立桃園高中96學年度新生始業輔導新生手冊目錄

高中英文科教師甄試心得

目 感恩与代祷 录 编 者 1 牧者心声 勒住你的舌头 龚明鹏 3 见证与分享 我的见证 吴权伟 8 相信就能够看见 卓艳梅 12 再述主恩 爱的雕凿 张英治 19 万怡杉 28 母亲节征文 记念母亲节 凌励立 43 父母的爱和神的爱 曹 红 47 Love Lisa Wang 50

Microsoft Word - Final Exam Review Packet.docx

104學年度自行招收僑生招生簡章(核定版)

2/80 2

OA-253_H1~H4_OL.ai

2009 Japanese First Language Written examination

Computer Architecture

數位教學平台介面操作

2010 Japanese First Language Written examination

Improved Preimage Attacks on AES-like Hash Functions: Applications to Whirlpool and Grøstl

唐彪《讀書作文譜》述略

2009 Korean First Language Written examination

Microsoft Word 谢雯雯.doc

(baking powder) 1 ( ) ( ) 1 10g g (two level design, D-optimal) 32 1/2 fraction Two Level Fractional Factorial Design D-Optimal D

中山大學學位論文典藏


<4D F736F F D20BEDBC9B3B3C9CBFEA1AAA1AAC9CCBDADBDCCD3FDCEC4BCAF20A3A8D6D0A3A92E646F63>

目 錄 壹 青 輔 會 結 案 附 件 貳 活 動 計 劃 書 參 執 行 內 容 一 教 學 內 容 二 與 當 地 教 師 教 學 交 流 三 服 務 執 行 進 度 肆 執 行 成 效 一 教 學 課 程 二 與 當 地 教 師 教 學 交 流 三 服 務 滿 意 度 調 查 伍 服 務 檢


2 response personnel to speed up the rescue operations after various natural or man-made disasters. Keywords: SMS, Database, Disaster

IBM Rational ClearQuest Client for Eclipse 1/ IBM Rational ClearQuest Client for Ecl

Transcription:

SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu

Aggregate Functions Functions that take a set of tuples and compute an aggregated value. Five standard functions: count, min, max, avg, sum They ignore null values. Find the total number, the average, minimum, and maximum GPA of students whose age is 17. select count(*), avg(gpa), min(gpa), max(gpa) from Students where Age = 17 Lecture 12 SQL: Interactive Queries (2) 2

Aggregate Functions (cont.) Find id and name of students who take 5 or more courses. select SID, Name from Students s where 5 <= (select count(distinct Cno) from Enrollment where SID = s.sid) Count(distinct Cno) distinct count(cno). Why? Must make sure the subquery generates a value comparable in the predicate. Lecture 12 SQL: Interactive Queries (2) 3

Group By Clause List id and name of students together with the number of hours still needed to graduate, assuming 120 hours are required. select s.sid, Name, 120 - sum(hours) Hours-Needed from Students s, Enrollment e, Courses c where s.sid = e.sid and e.cno = c.cno and Grade <= C group by s.sid, Name Enrolled courses are grouped by students. Lecture 12 SQL: Interactive Queries (2) 4

Group By Clause (cont.) Aggregate functions often applied to groups. One tuple is generated per group When using group by, select clause can contain only grouping attributes and aggregate func. Every grouping attribute must be in the select clause.the following is an illegal query (why?): select Age, SID, avg(gpa) from Students group by Age Lecture 12 SQL: Interactive Queries (2) 5

Having Clause For each student age group with more than 50 members, list the age and the number of students with that age. select Age, count(*) from Students group by Age having count(*) > 50 Conditions on aggregate functions are specified in the having clause. Select & Having may have different functions. Lecture 12 SQL: Interactive Queries (2) 6

Order By Clause List student names in ascending order. select Name from Students order by Name asc The default is ascending order. List students with GPA higher than 3.5, first in descending order of GPA, and then in ascending order of name. select * from Students where GPA > 3.5 order by GPA desc, Name asc Lecture 12 SQL: Interactive Queries (2) 7

Some Complex Queries Find the average number of CS courses a student takes. For non-cs major students who take more CS courses than he does with his major courses, and have taken at lease 2 CS courses, list their id, name, number of CS courses, number of major courses, sorted first in descending order of number of CS courses, then in ascending order of name. Lecture 12 SQL: Interactive Queries (2) 8

Interactive SQL Summary A query may have six clauses: select, from, where, group by, having, order by. Conceptual evaluation of the query: 1. Evaluate From (cross product) 2. Evaluate Where (selection) 3. Evaluate Group By (form groups) 4. Evaluate Aggregate functions on groups 5. Evaluate Having (choose groups to output) 6. Evaluate Order By (sorting) 7. Evaluate remaining Select (projection) Lecture 12 SQL: Interactive Queries (2) 9

Interactive SQL Summary (count.) Many ways to express a query. Flat queries may be more efficient. Nested queries may be easier to understand. Duplicate elimination may be costly. <> (not equal) at predicate level often gives a wrong answer. Use set difference, not in, not exists, etc. instead. Need to handle null values explicitly. DBMSs often provide many convenient functions. But need to check the compatibility. Lecture 12 SQL: Interactive Queries (2) 10

Expressive Power of SQL SQL is relational complete. Can express any relational algebraic query. SQL is more powerful then relational algebra. Can express aggregation, ordering, recursion, etc. SQL is not computational complete. Can not do everything a general programming language can do. Lecture 12 SQL: Interactive Queries (2) 11

Create Table Re-visited Can combine table creation with insertion of tuples using a query. create table Full-Professors as select FID, Name, Office from Faculty where Rank = Full Professor Lecture 12 SQL: Interactive Queries (2) 12

Update By Queries Relation: Top_Students (SID, Name, GPA) Insert students with a GPA 3.8 or higher into the Top_Students table. insert into Top_Students select SSN, Name, GPA from Students where GPA >= 3.8 Delete all students who take no courses. delete from Students where SID not in (select SID from Enrollment) Lecture 12 SQL: Interactive Queries (2) 13

Update Statement For every student who takes Database I, set the Grade to A. update Enrollment set Grade = 'A' where Cno in (select Cno from Courses where Title = Database I') Lecture 12 SQL: Interactive Queries (2) 14

Truncate vs Delete * Use delete to remove data and keep the table storage space. delete from Departments; Use truncate to remove data and release table storage space. truncate table Departments; Lecture 12 SQL: Interactive Queries (2) 15

Views A view is a virtual table (as opposed to stored base table) defined by a query, directly or indirectly, on base tables. create view Top_Students as select SSN, Name, GPA from Students where GPA >= 3.8 A view may be defined in terms of other views. Lecture 12 SQL: Interactive Queries (2) 16

Views (cont.) The query in view definition is usually not executed until the view is queried. Typically, no data is stored for a view. A view is queried as if it is a base table. Find name and GPA of top students whose name starts with a `K'. select Name, GPA from Top_Students where Name like 'K%' Lecture 12 SQL: Interactive Queries (2) 17

Query Modification Queries on a view are translated into queries on base tables by folding the view. Previous query is translated first into: select Name, GPA from (select SSN, Name, GPA from Students where GPA >= 3.8) where Name like 'K% Then into select Name, GPA from Students where GPA >= 3.8 and Name like 'K%' Lecture 12 SQL: Interactive Queries (2) 18

Why Use Views? Data independence: keep existing application programs from changes of base table schemas. Access control: provide a mechanism for hiding sensitive data from certain users. Productivity improvement: make user queries easier to express. Lecture 12 SQL: Interactive Queries (2) 19

Example of Using Views Consider following base tables and a view: Students (SID, Name, Birthday, GPA, Phone) Emrollment(SID, Cno, Grade) Courses(Cno, Title, Hours, Dept) create view Student-Course as select SID, Name, Age(Birthday) Age, GPA, c.cno, Title from Students s, Enrollment e, Courses c where s.sid=e.sid and e.cno = c.cno Lecture 12 SQL: Interactive Queries (2) 20

Example of Using Views (cont.) Data independence: Applications using the view are not affected if Age is stored or derived. Access control: Phone and Birthday of students are hidden from users. Productivity improvement: Find all courses taken by a given student is much simpler: select Cno, Title from Student_Course where SID = X Lecture 12 SQL: Interactive Queries (2) 21

Views and Updates What should happen if a user changes the data in the Student-Course view? insert into Student-Course values (1234, Dave Hall, 32, 3.15, CS334, B ) A view can not be updated if Contains group by and aggregate functions Involves multiple tables A single-table view can be updated if it contains a key of the table Lecture 12 SQL: Interactive Queries (2) 22

View Update Example * Which student should be deleted? create view Age_distribution as select Age, count(*) TotalNo from Students group by Age update Age_distribution set TotalNo = TotalNo 1 where Age = 20 Which base relation should be changed? delete from Student_Course where SID = '1234' Lecture 12 SQL: Interactive Queries (2) 23

Maintaining Materialized Views One may want to materialize a view (i.e., run its definition query and store the result) as is commonly done in industry (data warehouse). (Why?) View Maintenance: How to maintain the consistency between a view and its base tables, when base tables are updated? Incremental View Maintenance: How to maintain a view without re-computing the entire view? Lecture 12 SQL: Interactive Queries (2) 24