You are on page 1of 10

CHAPTER 7

Part04

More SQL: Complex Queries,


Triggers, Views, and Schema
Modification

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 1


Example of WITH

◼ Q28’: WITH BIGDEPTS (Dno) AS


( SELECT Dno
FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN BIGDEPTS
GROUP BY Dno;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 2


EXAMPLE of use of CASE
◼ The following example shows that employees are
receiving different raises in different departments
(A variation of the update U6)

◼ U6’: UPDATE EMPLOYEE


SET Salary =
CASE WHEN Dno = 5THEN Salary + 2000
WHEN Dno = 4THEN Salary + 1500
WHEN Dno = 1THEN Salary + 3000

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 3


An EXAMPLE of RECURSIVE Query
WITH RECURSIVE Addition(num) AS (

SELECT 1

UNION

SELECT num + 1
FROM Addition
WHERE num < 5
)

SELECT * FROM Addition;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 4


Views (Virtual Tables) in SQL
◼ Table derived from other tables(defining tables)

◼ SQL queries can use the View in the FROM


clause

◼ Can be used to restrict access of


users/applications to data

◼ Always up-to-date, responsibility of the DBMS

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7-5


Specification of Views in SQL
◼ CREATE VIEW command
◼ In V1, attributes retain the names from base tables. In
V2, attributes are assigned names

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 6


The DROP Command
◼ DROP command
◼ Used to drop named schema elements, such as
tables, domains, or constraint
◼ DROP TABLE/VIEW/SCHEMA/TRIGGER….

◼ DROP SCHMEA behavior options:


◼ CASCADE and RESTRICT

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 7


The ALTER Command
◼ ALTER command
◼ Used to modify the definition of schema elements
◼ Different sub commands and syntax variations
depending on the nature of the object

◼ Alter table actions include:


◼ Adding/dropping/changing a column (attribute)
◼ Adding/dropping constraints

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 8


The ALTER table command
◼ Example:
◼ ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job
VARCHAR(12);

◼ ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN


Mgr_ssn DROP DEFAULT;

◼ ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN


Mgr_ssn SET DEFAULT ‘333445555’;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 9


Dropping Columns, Default Values
◼ CASCADE or RESTRICT in drop column

◼ CASCADE would drop the column from views etc.

◼ RESTRICT is possible if no views, constraints


refer to it.

ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN


Address CASCADE;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 10

You might also like