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 (
isbn VARCHAR(15) NOT NULL,
title VARCHAR(200) NOT NULL,
catalog_no VARCHAR(15) NOT NULL,
copy_no INT NOT NULL DEFAULT 1,
keywords CHAR(100) NULL,
purchase_date DATE NULL,
PRIMARY KEY CLUSTERED(catalog_no, copy_no))
Attribute nameTable name
Data type Domain constraint
Default
PK composed of two attributes
CREATE TABLE, example 2
CREATE TABLE Borrows ( catalog_num VARCHAR(15) NOT NULL, copy_num INT NOT NULL, issue_date DATE NOT NULL, person_id CHAR(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) )R
efer
enti
al c
onst
rain
ts
CREATE TABLE, example 3
CREATE TABLE Person (
lname VARCHAR(35) NOT NULL,
fnames VARCHAR(50) NOT NULL,
email VARCHAR(60) NOT NULL UNIQUE
CHECK ( email LIKE ‘%@%’),
id CHAR(8) NOT NULL,
phone CHAR(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;
Personlname fnames email id phone
Personlname fnames email id phone fines
Initial design
ALTER-ed design
ALTER TABLE command…
Example 2: add a new attributeALTER TABLE Book ADD category VARCHAR(10) NOT NULL DEFAULT “normal” CHECK (category in (“normal”, “reserve”, “media”));
Example 3: drop a constraintALTER TABLE Borrows DROP CONSTRIANT fk_borrows_person;
Example 4: add a constraintALTER 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 PersonVALUES ( ‘Bush’, ‘George W.’, ‘[email protected]’, ‘09112001’, NULL, 0);
Person
lname fnames email id phone fines
Example 2:
INSERT INTO BookVALUES ( ‘0321122267’, ‘Fundamentals of Database Systems’, ‘QA76.9.D3’, 1, ‘Databases’, ‘2004-09-25’);
Book
isbn title catalog_no copy_no keywords Purchase_date
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
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’);
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_num copy_num issue_date person_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
lname fnames email id phone fines
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
BDate Address
9-Jan-55 731 Fonden
SELECT BDate, AddressFROM EMPLOYEEWHERE Fname = ‘John’ AND
Lname = ‘Smith’;
SELECT command (1a)
Example 1a:Report the SSN of Employees who spend more than 15 hourson some project.
SELECT DISTINCT ESSNFROM WORKS_ONWHERE Hours > 15;
SELECT ESSNFROM WORKS_ONWHERE Hours > 15;
OUTPUT
ESSN
123456789
666884444
453453453
999887777
987987987
OUTPUT
ESSN
123456789
666884444
453453453
453453453
999887777
987987987
987987987
SELECT command (2)
Example 2:Report the Name and address of employees workingin the “Research” department.
OUTPUT
Fname Lname Address
John Smith 731 Fonden
Franklin Wong 638 Voss
Ramesh Narayan 975 Fire Oak
Joyce English 5631 Rice
SELECT Fname, Lname, AddressFROM EMPLOYEE, DEPARTMENTWHERE Dname = ‘Research’ AND
Dnumber = Dno
SELECT command (3)
Example 3: For each project located in Stafford,list the project number, the controlling department, andthe department manager's last name and address.
SELECT Pnumber, Dnum, Lname, AddressFROM PROJECT, DEPARTMENT, EMPLOYEEWHERE Dnum = Dnumber AND
MgrSSN = SSN ANDPlocation = ‘Stafford’;
OUTPUT
Pnumber Dnum Lname Address
10 4 Wallace 291 Berry
30 4 Wallace 291 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.
SELECT E.Lname, S.LnameFROM EMPLOYEE AS E, EMPLOYEE AS SWHERE E.SuperSSN = S.SSN
OUTPUT
E.Lname S.Lname
Smith Wong
Wong Borg
Zeleya Wallace
Wallace Borg
Narayan Wong
English Wong
Jabbar Wallace
SELECT command (5, 6): no WHERE
Example 5: Print SSN of all employees.
SELECT SSNFROM EMPLOYEE
OUTPUT
SSN
123456789
333445555
999887777
987654321
666884444
453453453
987987987
888665555
SELECT SSN, DnameFROM EMPLOYEE, DEPARTMENT
How many rows in output ?
SELECT command (7): wildcard
Example 7: Show the EMPLOYEE table
SELECT * FROM EMPLOYEE
SELECT DEPT_LOCATION.*, DEPARTMENT.DnameFROM DEPT_LOCATION, DEPARTMENTWHERE DEPT_LOCATION.Dnumber = DEPARTMENT.Dnumber
Example 7a: Report Department information including locations
OUTPUT
Dnumber Dlocation Dname
1 Houston Headquarters
4 Stafford Administration
5 Bellaire Research
5 Sugarland Research
5 Houston Research
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-query Second sub-query OUTPUT
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.
SELECT Fname, Lname, AddressFROM EMPLOYEEWHERE Dno IN ( SELECT Dnumber
FROM DEPARTMENT WHERE Dname = 'Research' )
Result of inner query:
Dnumber
5
OUTPUT
Fname Lname Address Dno
John Smith 731 Fonden 5
Franklin Wong 638 Voss 5
Ramesh Narayan 975 Fire Oak 5
Joyce English 5631 Rice 5
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.LnameFROM EMPLOYEE AS EWHERE E.SSN IN ( SELECT ESSN
FROM DEPENDENT WHERE ESSN = E.SSN
AND E.Fname = DependentName )
OUTPUT
E.Fname E.Lname
correlated
SELECT command (11): EXISTS operator
Example 11:Get names of employees who work for at least one project.
SELECT Fname, LnameFROM EMPLOYEEWHERE EXISTS ( SELECT *
FROM WORKS_ON WHERE SSN = ESSN )
OUTPUT
Fname Lname
John Smith
Franklin Wong
Alicia Zeleya
Ramesh Narayan
Joyce English
Ahmad Jabbar
James Borg
SELECT command (12): NOT EXISTSExample 12:Find names of employees who do not work for even one project.
SELECT Fname, LnameFROM EMPLOYEEWHERE NOT EXISTS ( SELECT *
FROM WORKS_ON WHERE SSN = ESSN )
OUTPUT
Fname Lname
Jennifer Wallace
SELECT command (13): matching CHAR(n) types
Example 13:Find names of all Employees who live on Fonden street.
SELECT LnameFROM EMPLOYEEWHERE Address LIKE ‘%Fonden%’;
matchingoperator
matcheszero 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 salariesfor employees of the Research department.
SELECT sum(Salary), max( Salary), min( Salary), avg( Salary)FROM EMPLOYEE, DEPARTMENTWHERE Dno = Dnumber AND Dname = 'Research'
OUTPUT
13300 4000 2500 3325
SELECT sum(Salary) AS Tot, max( Salary) AS Max, min( Salary) AS Min, avg( Salary) AS MeanFROM EMPLOYEE, DEPARTMENTWHERE Dno = Dnumber AND Dname = 'Research'
OUTPUT
Tot Max Min Mean
13300 4000 2500 3325
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.
SELECT Dno, count(*) AS HeadCount, avg(Salary) AS MeanSalaryFROM EMPLOYEE, DEPARTMENTWHERE Dno = Dnumber AND Dname <> 'Headquarters'GROUP BY Dno;
OUTPUT
Dno HeadCount MeanSalary
5 4 3325
4 3 3100
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.
SELECT Dno, count(*) AS HeadCount, avg(Salary) AS MeanSalaryFROM EMPLOYEE, DEPARTMENTWHERE Dno = Dnumber AND Dname <> 'Headquarters'GROUP BY DnoHAVING HeadCount > 3;
OUTPUT
Dno HeadCount MeanSalary
5 4 3325
SELECT command (17): Mathematical operators
Example 17:Display the result of a 10% increase in Salary of employeeswhose Last name starts with "B".
SELECT Lname, 1.1 * Salary AS IncreasedSalaryFROM EMPLOYEEWHERE Lname LIKE 'B%'
OUTPUT
Lname IncreasedSalary
Borg 6050
SELECT command (18): sorting
Example 18:Report names and salaries of employees, in descending order by salary
SELECT Lname, SalaryFROM EMPLOYEEORDER BY Salary DESC OUTPUT
Lname Salary
Borg 5500
Wallace 4300
Wong 4000
Narayan 3800
Smith 3000
Zeleya 2500
English 2500
Jabbar 2500
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
Fname Lname Pname Hours
John Smith ProductX 32.5
John Smith ProductY 7.5
Ramesh Narayan ProductZ 40
Joyce English ProductX 20
Joyce English ProductY 20
Franklin Wong ProductY 10
Franklin Wong ProductZ 10
Franklin Wong Computerization 10
Franklin Wong Reorganization 10
Alicia Zeleya Newbenefits 30
Alicia Zeleya Computerization 10
Ahmad Jabbar Computerization 35
Ahmad Jabbar Newbenefits 5
Ahmad Jabbar Newbenefits 20
Ahmad Jabbar Reorganization 15
James Borg Reorganization null
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?
UPDATE EMP_WORKS_ONSET Hours = Hours * 1.5
SELECT * FROM WORKS_ON
WORKS_ON
ESSN Pno Hours
123456789 1 48.75
123456789 2 11.25
666884444 3 60
453453453 1 30
453453453 2 30
333445555 2 15
333445555 3 15
333445555 10 15
333445555 20 15
999887777 30 45
999887777 10 15
987987987 10 52.5
987987987 30 7.5
987654321 30 30
987987987 20 22.5
888665555 20 null
VIEWS: mechanism of storage/updates…
Example 3:John Smith, currently working on ‘ProductX’ project,is reassigned to ‘ProductY’ project.
Example 3 (incorrect): UPDATE EMP_WORKS_ONSET Pname = 'ProductY'WHERE Lname = 'Smith' AND
Pname = 'ProductX'
Example 3 (correct):UPDATE WORKS_ONSET 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 VIEW DEPT_INFO AS SELECT DName, count(*) AS NumEmps, sum( Salary) AS TotalSalary FROM DEPARTMENT, EMPLOYEE WHERE DNumber = DNo GROUP BY DName;
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 ASSELECT Fname, Minit, Lname, SSN, BDate, Address, Sex, SuperSSN, DnoFROM EMPLOYEE;
GRANT SELECT, UPDATE ON EMP_PERSONNEL to U1;
GRANT SELECT, UPDATE ON EMP_PERSONNEL TO U1WITH 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:
Top Related