Professional Documents
Culture Documents
SQL: Updates (DML) and Views (DDL) : Murali Mani
SQL: Updates (DML) and Views (DDL) : Murali Mani
Murali Mani
SQL DML (Updating the Data)
• Insert
• Delete
• Update
Murali Mani
Inserting tuples
INSERT INTO Student VALUES
(6, ‘Emily’, ‘324 FL’, NULL);
Murali Mani
Delete and Update
Deleting tuples
DELETE FROM Student
WHERE sNumber=‘6’;
Updating tuples
UPDATE Student SET professor=‘ER’
WHERE sNumer=‘6’
Murali Mani
Views
NOTE: You can present logical subsets or combinations of the data by creating
views of tables. A view is a virtual table based on a table or another view. A view
contains no data of its own but is like a window through which data from tables can
be viewed or changed. The tables on which a view is based are called base tables.
The view is stored as a SELECT statement in the data dictionary.
Murali Mani
Views
View is a virtual relation
Convenience: Queries on base relations might be
“complex”
Logical Data Independence: “base tables” may
change, but still queries using views need not
change.
Provide different views of the same data.
Security: Expose only necessary data to users
Views can be queried like any “base” relation.
Murali Mani
Views
CREATE VIEW <viewName> as <query>
DROP VIEW <viewName>
Murali Mani
Views - Example
Student Professor
sNumber sName address professor
pNumber pName address
1 Dave 320FL 1
1 MM 235FL
2 Greg 320FL 1
2 ER 241FL
3 Matt 320FL 2
Murali Mani
Updating Views
Consider views defined with only one
relation in the FROM clause such as:
Murali Mani
Updating Single relation views
If the SELECT clause specifies DISTINCT,
then the view is not updatable.
Murali Mani
Updating Single Relation
Views
Note that the WHERE clause may specify
subqueries. Let us consider an extreme
example.
CREATE VIEW MyStudent3 (num, name) AS
SELECT sNumber, sName FROM Student
WHERE sNumber NOT IN (SELECT sNumber FROM
Student);
-- this view will always have 0 tuples.
Insert into this view will still insert
into student table, though that tuple does
not appear in the view.
Murali Mani
Multiple relation views: Delete
Consider a multi-relation view such as
CREATE VIEW studentProf(student, professor)
AS SELECT sName, pName
FROM Student, Professor
WHERE professor=pNumber;
Murali Mani
Deleting from multi-relation
views
Try the following update statements:
Murali Mani
Deleting from multirelation
views
Suppose we drop the key constraint on the
professor table for the same view.
Murali Mani
Inserting into multi-relation
views
Consider the following slightly modified view
definition
CREATE VIEW studentProf(student, professor)
AS SELECT sNumber, pName FROM Student, Professor
WHERE professor=pNumber;
Murali Mani
Inserting into multi-relation
views
Insert will succeed only if
The insert translates to insert into only one table.
The key for the table to be inserted will also be a
key for the view.
Murali Mani