Structured Query Language Agenda: - SQL commands for DB definition - SQL DML commands - VIEWS and security control using SQL.

Slides:



Advertisements
Similar presentations
Fundamentals of Database Systems Fourth Edition El Masri & Navathe
Advertisements

SQL DESIGN AND IMPLEMENTATION CONTENT SOURCES: ELAMSARI AND NAVATHE, FUNDAMENTALS OF DATABASE MANAGEMENT SYSTEMSELAMSARI AND NAVATHE, FUNDAMENTALS OF.
COMPANY schema EMPLOYEE
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
Basic Queries. 2 Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database; the SELECT statement This is not the.
Your Logo Fundamentals of Database Systems Fourth Edition El Masri & Navathe Instructor: Mr. Ahmed Al Astal Chapter 8 (Cont.) SQL-99: Schema Definition,
Database technology Lecture 2: Relational databases and SQL
Data Definition Languages Atif Farid Mohammad UNCC.
FEN More about SELECT, Nested selects GROUP BY, HAVING, ORDER BY Other joins Aggregate functions Views More about SQL.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
Data Warehousing/Mining 1 Data Warehousing/Mining Comp 150 Aggregation in SQL (not in book) Instructor: Dan Hebert.
1 CSE 480: Database Systems Lecture 10: SQL - DML Reference: Read Chapter 4 of the textbook.
Exploring Microsoft Access 2003 Chapter 4 Proficiency: Relational Databases, External Data, Charts, Pivot, and the Switchboard.
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:
Review Database Application Development Access Database Development ER-diagram Forms Reports Queries.
CS 104 Introduction to Computer Science and Graphics Problems Introduction to Database (2) Basic SQL 12/05/2008 Yang Song.
SQL Winter 2006Ron McFadyen Outline: SQL DDL - creating schemas - modifying schemas DML - select-from-where clause - group by, having, order by.
Jyh-haw Yeh Dept. of Computer Science Boise State University
SQL Jan. 2012Yangjun Chen ACS Outline: SQL Chapter 8 – 3rd ed. (Chap. 8 – 4 th, 5 th ed.; Chap. 4, 5, 6 th ed.) DDL - creating schemas - modifying.
관계 연산자 & SQL. Selection SELECT * FROM r WHERE A=B AND D>5.
SQL The relational DB Standard CS-450 Dr. Ali Obaidi.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1 CREATE/DROP/ALTER TABLE Data types : char, varchar, decimal, date CREATE TABLE DEPARTMENT.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
FEN  Queries: SELECT  Data Manipulation: INSERT, UPDATE, DELETE SQL: Structured Query Language – Part 2.
Review: Application of Database Systems
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
SQL Chapters 4, 5 (ed. 7 Chaps. 6,7). SQL or SEQUEL (Structured English Query Language) Based on relational algebra First called ‘Square’ Developed in.
1 CSE 480: Database Systems Lecture 11: SQL. 2 SQL Query SELECT FROM WHERE –In MySQL, FROM and WHERE clauses are optional –Example:
SQL: Schema Definition, Constraints, & Queries and Views.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Lecture # 11 July 12,2012 More SQL: Complex Queries, Triggers,
Relational Algebra - Chapter (7th ed )
Onsdag The concepts in a relation data model SQL DDL DML.
CS 380 Introduction to Database Systems (Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views)
 Employee (fname, minit, lname, ssn, bdate, address, sex, salary, superssn, dno)  Department (dname, dnumber, mgrssn, mgrstartdate) 
Database Management Systems. NESTING OF QUERIES  Some queries require that existing values in the database be retrieved and then used in a comparison.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Announcements Written Homework 1 due Friday –If you have fourth edition make sure you do the right problems Program 3 out today, due next Friday Nov 10.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
莊裕澤資料庫基本概念 1 Yuh-Jzer Joung 莊 裕 澤 Dept. of Information Management National Taiwan University February, 2002 資料庫管理與資訊科技.
NOEA/IT - FEN: Databases/SQL1 SQL – part 1 SQL: DDL and DML.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Chapter 7 SQL HUANG XUEHUA. AGGREGATE FUNCTIONS Include COUNT, SUM, MAX, MIN, and AVG Query 15: Find the maximum salary, the minimum salary, and the.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
Slide 8- 1 THE HAVING-CLAUSE Provides a condition on the summary information Sometimes we want to retrieve the values of these functions for only those.
Structured Query Language
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Introduction to Database Systems
1Fundamentals of Database Systems 기본키에 밑줄을 그은 COMPANY 관계 데이타베이스 스키마 FNAMEMINITLNAMESSNBDATEADDRESSSEXSALARYSUPERSSNDNO EMPLOYEE DNAMEDNUMBERMGRSSNMGRSTARTDATE.
FEN Introduction to the database field:  SQL: Structured Query Language Seminar: Introduction to relational databases.
603 Database Systems Senior Lecturer: Laurie Webster II, M.S.S.E.,M.S.E.E., M.S.BME, Ph.D., P.E. Lecture 20 A First Course in Database Systems.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
1 COMP 1100 Basic SQL David J. Stucki. Outline SQL Overview Retrievals Schema creation Table creation Constraints Inserts Updates 2.
SQL- Updates, Assertions and Views. Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
The SQL Database Grammar
CS580 Advanced Database Topics
Chapter 4 Basic SQL.
6/22/2018.
CS580 Advanced Database Topics
376a. Database Design Dept. of Computer Science Vassar College
Joining Tables ضم الجداول وإستخراج مناظر views منها الهدف : 1- استخراج المعلومات من جدولين أو اكثر بالإستفادة من الرابط بينهما وبإستخدام SQL 2- شروط قواعد.
Company Requirements.
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
SQL Grouping, Ordering & Arithmetics Presented by: Dr. Samir Tartir
Presentation transcript:

Structured Query Language Agenda: - SQL commands for DB definition - SQL DML commands - VIEWS and security control using SQL

CREATE TABLE command - Table name - Description of the attributes: -- Attribute name -- Data type -- Constraints on the attribute values, including: --- NULL or NOT NULL --- Domain of attribute --- Referential constraints on the attribute - Primary key attributes - Foreign key attributes

CREATE TABLE, example 1 CREATE TABLE Book ( isbnVARCHAR(15)NOT NULL, titleVARCHAR(200)NOT NULL, catalog_noVARCHAR(15)NOT NULL, copy_noINTNOT NULLDEFAULT 1, keywordsCHAR(100)NULL, purchase_dateDATENULL, PRIMARY KEY CLUSTERED(catalog_no, copy_no)) Attribute name Table name Data type Domain constraint Default PK composed of two attributes

CREATE TABLE, example 2 CREATE TABLE Borrows ( catalog_numVARCHAR(15)NOT NULL, copy_numINTNOT NULL, issue_dateDATENOT NULL, person_idCHAR(8)NOT NULL, PRIMARY KEY CLUSTERED(catalog_num, copy_num, person_id, issue_date), CONSTRAINT fk_borrows_book FOREIGN KEY(catalog_num, copy_num) REFERENCES Books(catalog_no, copy_no), CONSTRAINT fk_borrows_person FOREIGN KEY(person_id) REFERENCES Person( id) ) Referential constraints

CREATE TABLE, example 3 CREATE TABLE Person ( lnameVARCHAR(35)NOT NULL, fnamesVARCHAR(50)NOT NULL, VARCHAR(60)NOT NULLUNIQUE CHECK ( LIKE idCHAR(8)NOT NULL, phoneCHAR(12)NULL, PRIMARY KEY (id) ) Domain constraint Key (but not PK)

DROP TABLE command DROP TABLE Person; DROP TABLE Person CASCADE; Step 1. Referential constraints are deleted Step 2. All data in the table is deleted Step 3. The definition of the table is deleted from the DB. Problem: Borrows( person_id) REFERENCES Person( id)

ALTER TABLE command - Add a new column in a table - Delete a column from a table - Add/Delete a constraint specified on a table Example 1 ALTER TABLE Person ADD fines FLOAT; Person lnamefnames idphone Person lnamefnames idphonefines Initial design ALTER-ed design

ALTER TABLE command… Example 2: add a new attribute ALTER TABLE Book ADD category VARCHAR(10) NOT NULL DEFAULT “normal” CHECK (category in (“normal”, “reserve”, “media”)); Example 3: drop a constraint ALTER TABLE Borrows DROP CONSTRIANT fk_borrows_person; Example 4: add a constraint ALTER TABLE Borrows ADD CONSTRAINT fk_borrows_person FOREIGN KEY(person_id) REFERENCES Person( id); Q: What happens to data entered in a table BEFORE adding a constraint?

INSERT INTO command, populating a DB Example 1: INSERT INTO Person VALUES ( ‘Bush’, ‘George W.’, ‘ ’, NULL, 0); Person lnamefnames idphonefines Example 2: INSERT INTO Book VALUES ( ‘ ’, ‘Fundamentals of Database Systems’, ‘QA76.9.D3’, 1, ‘Databases’, ‘ ’); Book isbntitlecatalog_nocopy_nokeywordsPurchase_date

DELETE FROM command - to delete one or more rows of data from a table Example 1: DELETE FROM Person WHERE id= ‘ ’; Example 2: DELETE FROM Person WHERE lname=’Bush’; Example 3: DELETE FROM Borrows WHERE 1

DELETE FROM command … Example 4: DELETE FROM Borrows WHERE person_id IN (“ ”, “ ”, “ ”); Example 5: DELETE FROM Borrows WHERE person_id IN ( SELECT id FROM Person WHERE lname= ‘Bush’);

UPDATE command - Modify the value of one or more cells in a table Example 1: UPDATE Borrows SET issue_date=CURRENT_DATE( ) WHERE person_id=’ ’; Borrows catalog_numcopy_numissue_dateperson_id Example 2: UPDATE Person SET fines= fines*2.0 WHERE id=’ ’; Function provided by SQL SQL allows the use of arithmetic expressions Person lnamefnames idphonefines

SELECT command - Output required information from one or more tables For the following examples (unless stated otherwise): - Use the EMPLOYEE-DEPARTMENT-PROJECTS database - Assume the initial data in the tables as provided earlier

SELECT command (1) Example 1: Report the birth date and address of employee named "John Smith" OUTPUT BDateAddress 9-Jan Fonden SELECTBDate, Address FROMEMPLOYEE WHEREFname = ‘John’ AND Lname = ‘Smith’;

SELECT command (1a) Example 1a: Report the SSN of Employees who spend more than 15 hours on some project. SELECT DISTINCT ESSN FROM WORKS_ON WHERE Hours > 15; SELECT ESSN FROM WORKS_ON WHERE Hours > 15; OUTPUT ESSN OUTPUT ESSN

SELECT command (2) Example 2: Report the Name and address of employees working in the “Research” department. OUTPUT FnameLnameAddress JohnSmith731 Fonden FranklinWong638 Voss RameshNarayan975 Fire Oak JoyceEnglish5631 Rice SELECTFname, Lname, Address FROMEMPLOYEE, DEPARTMENT WHEREDname = ‘Research’ AND Dnumber = Dno

SELECT command (3) Example 3: For each project located in Stafford, list the project number, the controlling department, and the department manager's last name and address. SELECTPnumber, Dnum, Lname, Address FROMPROJECT, DEPARTMENT, EMPLOYEE WHEREDnum = Dnumber AND MgrSSN = SSN AND Plocation = ‘Stafford’; OUTPUT PnumberDnumLnameAddress 104Wallace291 Berry 304Wallace291 Berry

SELECT command (4): Alias and Dot-notation Example 4:For each employee, give the last name, and the last name of his/her supervisor. SELECTE.Lname, S.Lname FROMEMPLOYEE AS E, EMPLOYEE AS S WHEREE.SuperSSN = S.SSN OUTPUT E.LnameS.Lname SmithWong Borg ZeleyaWallace Borg NarayanWong EnglishWong JabbarWallace

SELECT command (5, 6): no WHERE Example 5: Print SSN of all employees. SELECTSSN FROMEMPLOYEE OUTPUT SSN SELECTSSN, Dname FROMEMPLOYEE, DEPARTMENT How many rows in output ?

SELECT command (7): wildcard Example 7: Show the EMPLOYEE table SELECT * FROM EMPLOYEE SELECTDEPT_LOCATION.*, DEPARTMENT.Dname FROMDEPT_LOCATION, DEPARTMENT WHEREDEPT_LOCATION.Dnumber = DEPARTMENT.Dnumber Example 7a: Report Department information including locations OUTPUT DnumberDlocationDname 1HoustonHeadquarters 4StaffordAdministration 5BellaireResearch 5SugarlandResearch 5HoustonResearch

SELECT command (8): UNION Example 8: List all projects which either use employee "Wong", or are controlled by a department managed by "Wong". (SELECT Pname FROM PROJECT, WORKS_ON, EMPLOYEE WHERE Pnumber = PNo AND ESSN = SSN AND LName = 'Wong' ) UNION (SELECT Pname FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNum = Dnumber AND SSN = MgrSSN AND LName = 'Wong'); First sub-querySecond sub-queryOUTPUT Pname ProductY ProductZ Computerization Reorganisation Pname ProductX ProductY ProductZ OUTPUT PName ProductX ProductY ProductZ Computerization Reorganisation

SELECT command (9): nested queries Example 9: Report the name and address of all employees working in the 'Research' department. SELECTFname, Lname, Address FROMEMPLOYEE WHEREDno IN( SELECTDnumber FROMDEPARTMENT WHEREDname = 'Research' ) Result of inner query: Dnumber 5 OUTPUT FnameLnameAddressDno JohnSmith731 Fonden5 FranklinWong638 Voss5 RameshNarayan975 Fire Oak5 JoyceEnglish5631 Rice5 uncorrelated

SELECT command (10): nested queries Example 10: Get the names of all employees who have a dependent with the same first name. SELECT E.Fname, E.Lname FROM EMPLOYEE AS E WHERE E.SSN IN( SELECT ESSN FROM DEPENDENT WHERE ESSN = E.SSN AND E.Fname = DependentName ) OUTPUT E.FnameE.Lname correlated

SELECT command (11): EXISTS operator Example 11: Get names of employees who work for at least one project. SELECTFname, Lname FROM EMPLOYEE WHEREEXISTS( SELECT* FROMWORKS_ON WHERESSN = ESSN ) OUTPUT FnameLname JohnSmith FranklinWong AliciaZeleya RameshNarayan JoyceEnglish AhmadJabbar JamesBorg

SELECT command (12): NOT EXISTS Example 12: Find names of employees who do not work for even one project. SELECTFname, Lname FROM EMPLOYEE WHERENOT EXISTS( SELECT* FROMWORKS_ON WHERESSN = ESSN ) OUTPUT FnameLname JenniferWallace

SELECT command (13): matching CHAR(n) types Example 13: Find names of all Employees who live on Fonden street. SELECTLname FROMEMPLOYEE WHEREAddress LIKE ‘%Fonden%’; matching operator matches zero or more chars OUTPUT Lname Smith NOTES: (1) ‘_’ matches exactly one char (2) RLIKE operator allows REG_EXP

SELECT command (14): aggregates Example 14: Get the minimum, maximum, average and total salaries for employees of the Research department. SELECTsum(Salary), max( Salary), min( Salary), avg( Salary) FROMEMPLOYEE, DEPARTMENT WHEREDno = Dnumber AND Dname = 'Research' OUTPUT SELECT sum(Salary) AS Tot, max( Salary) AS Max, min( Salary) AS Min, avg( Salary) AS Mean FROM EMPLOYEE, DEPARTMENT WHERE Dno = Dnumber AND Dname = 'Research' OUTPUT TotMaxMinMean

SELECT command (15): GROUP BY Example 15: For departments other than Headquarters, get the Dno, the No. of employees in that department, and their average salary. SELECTDno, count(*) AS HeadCount, avg(Salary) AS MeanSalary FROMEMPLOYEE, DEPARTMENT WHEREDno = DnumberANDDname <> 'Headquarters' GROUP BYDno; OUTPUT DnoHeadCountMeanSalary

SELECT command (16): GROUP BY.. HAVING.. Example 16: For ‘Large’ departments other than Headquarters, get the Dno, the No. of employees in that department, and their average salary. SELECTDno, count(*) AS HeadCount, avg(Salary) AS MeanSalary FROMEMPLOYEE, DEPARTMENT WHEREDno = DnumberANDDname <> 'Headquarters' GROUP BYDno HAVINGHeadCount > 3; OUTPUT DnoHeadCountMeanSalary

SELECT command (17): Mathematical operators Example 17: Display the result of a 10% increase in Salary of employees whose Last name starts with "B". SELECTLname, 1.1 * Salary AS IncreasedSalary FROMEMPLOYEE WHERELname LIKE 'B%' OUTPUT LnameIncreasedSalary Borg6050

SELECT command (18): sorting Example 18: Report names and salaries of employees, in descending order by salary SELECTLname, Salary FROMEMPLOYEE ORDER BYSalary DESC OUTPUT LnameSalary Borg5500 Wallace4300 Wong4000 Narayan3800 Smith3000 Zeleya2500 English2500 Jabbar2500

VIEWS VIEW: A virtual table derived from a set of existing tables. Main uses of a view: - Security (selective display of information to different users) - Ease-of-use -- Explicit display of derived attributes -- Explicit display of related information from different tables -- Intermediate table can be used to simplify SQL query

CREATE VIEW command (1) Example 1: Create a view showing the names of employees, which project they work on, and how many hours they spend on each project. CREATE VIEW EMP_WORKS_ON AS SELECT Fname, Lname, Pname, Hours FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN = ESSN AND Pno = Pnumber; SELECT * FROM EMP_WORKS_ON EMP_WORKS_ON FnameLnamePnameHours JohnSmithProductX32.5 JohnSmithProductY7.5 RameshNarayanProductZ40 JoyceEnglishProductX20 JoyceEnglishProductY20 FranklinWongProductY10 FranklinWongProductZ10 FranklinWongComputerization10 FranklinWongReorganization10 AliciaZeleyaNewbenefits30 AliciaZeleyaComputerization10 AhmadJabbarComputerization35 AhmadJabbarNewbenefits5 AhmadJabbarNewbenefits20 AhmadJabbarReorganization15 JamesBorgReorganizationnull

VIEWS: mechanism of storage/updates 1. Only definition of view is stored in memory 2. Data for a view is only generated when the query is processed 3. Update a view attribute  data in the underlying table is updated

VIEWS: mechanism of storage/updates.. Example 2: What happens to employee hours if they work one-shift overtime? UPDATEEMP_WORKS_ON SETHours = Hours * 1.5 SELECT * FROM WORKS_ON WORKS_ON ESSNPnoHours null

VIEWS: mechanism of storage/updates… Example 3: John Smith, currently working on ‘ProductX’ project, is reassigned to ‘ProductY’ project. Example 3 (incorrect): UPDATEEMP_WORKS_ON SETPname = 'ProductY' WHERELname = 'Smith' AND Pname = 'ProductX' Example 3 (correct): UPDATE WORKS_ON SET Pno = (SELECT Pnumber FROM PROJECTS WHERE Pname = 'ProductY') WHERE ESSN = ( SELECT SSN FROM EMPLOYEE WHERE Lname = 'Smith') AND Pno = ( SELECT Pnumber FROM PROJECT WHERE Pname = 'ProductX'); Problem ?

VIEWS: using derived attributes CREATE VIEWDEPT_INFO AS SELECT DName, count(*) AS NumEmps, sum( Salary) AS TotalSalary FROMDEPARTMENT, EMPLOYEE WHEREDNumber = DNo GROUP BYDName; NOTE: - you cannot UPDATE a computed attribute

VIEWS, GRANT: security control Example 5: Allow user U1 to see/modify all Employee data except Salaries. CREATE VIEW EMP_PERSONNEL AS SELECT Fname, Minit, Lname, SSN, BDate, Address, Sex, SuperSSN, Dno FROM EMPLOYEE; GRANT SELECT, UPDATE ON EMP_PERSONNEL to U1; GRANT SELECT, UPDATE ON EMP_PERSONNEL TO U1 WITH GRANT OPTION; OR 1 2 U1 > GRANT SELECT ON EMP_PERSONNEL TO U2;

GRANT, REVOKE commands REVOKE SELECT ON EMP_PERSONNEL FROM U2; Disallow U2 from seeing anything in EMP_PERSONNEL: GRANT UPDATE ON EMPLOYEE( Salary) TO U3; GRANT, REVOKE can refer to individual attributes Allow U3 to change Salary in EMPLOYEE table:

Concluding remarks GRANT on SELECT  use VIEW or TABLE GRANT on INSERT, DELETE, UPDATE  use TABLE Next topic: Indexes