Download presentation
Presentation is loading. Please wait.
1
Structured Query Language Agenda: - SQL commands for DB definition - SQL DML commands - VIEWS and security control using SQL
2
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
3
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
4
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
5
CREATE TABLE, example 3 CREATE TABLE Person ( lnameVARCHAR(35)NOT NULL, fnamesVARCHAR(50)NOT NULL, emailVARCHAR(60)NOT NULLUNIQUE CHECK ( email LIKE ‘%@%’), idCHAR(8)NOT NULL, phoneCHAR(12)NULL, PRIMARY KEY (id) ) Domain constraint Key (but not PK)
6
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)
7
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 lnamefnamesemailidphone Person lnamefnamesemailidphonefines Initial design ALTER-ed design
8
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?
9
INSERT INTO command, populating a DB Example 1: INSERT INTO Person VALUES ( ‘Bush’, ‘George W.’, ‘dubya@white.house’, ‘09112001’, NULL, 0); Person lnamefnamesemailidphonefines Example 2: INSERT INTO Book VALUES ( ‘0321122267’, ‘Fundamentals of Database Systems’, ‘QA76.9.D3’, 1, ‘Databases’, ‘2004-09-25’); Book isbntitlecatalog_nocopy_nokeywordsPurchase_date
10
DELETE FROM command - to delete one or more rows of data from a table Example 1: DELETE FROM Person WHERE id= ‘09112001’; Example 2: DELETE FROM Person WHERE lname=’Bush’; Example 3: DELETE FROM Borrows WHERE 1
11
DELETE FROM command … Example 4: DELETE FROM Borrows WHERE person_id IN (“09112001”, “55554444”, “12345678”); Example 5: DELETE FROM Borrows WHERE person_id IN ( SELECT id FROM Person WHERE lname= ‘Bush’);
12
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=’09112001’; Borrows catalog_numcopy_numissue_dateperson_id Example 2: UPDATE Person SET fines= fines*2.0 WHERE id=’09112001’; Function provided by SQL SQL allows the use of arithmetic expressions Person lnamefnamesemailidphonefines
13
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
14
SELECT command (1) Example 1: Report the birth date and address of employee named "John Smith" OUTPUT BDateAddress 9-Jan-55731 Fonden SELECTBDate, Address FROMEMPLOYEE WHEREFname = ‘John’ AND Lname = ‘Smith’;
15
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 123456789 666884444 453453453 999887777 987987987 OUTPUT ESSN 123456789 666884444 453453453 999887777 987987987
16
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
17
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
18
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
19
SELECT command (5, 6): no WHERE Example 5: Print SSN of all employees. SELECTSSN FROMEMPLOYEE OUTPUT SSN 123456789 333445555 999887777 987654321 666884444 453453453 987987987 888665555 SELECTSSN, Dname FROMEMPLOYEE, DEPARTMENT How many rows in output ?
20
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
21
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
22
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
23
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
24
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
25
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
26
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
27
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 13300400025003325 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 13300400025003325
28
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 543325 433100
29
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 543325
30
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
31
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
32
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
33
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
34
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
35
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 123456789148.75 123456789211.25 666884444360 453453453130 453453453230 333445555215 333445555315 3334455551015 3334455552015 9998877773045 9998877771015 9879879871052.5 987987987307.5 98765432130 9879879872022.5 88866555520null
36
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 ?
37
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
38
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;
39
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:
40
Concluding remarks GRANT on SELECT use VIEW or TABLE GRANT on INSERT, DELETE, UPDATE use TABLE Next topic: Indexes
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.