Deletion
A delete request can only delete whole tuples; deleting values on only particular attributes is not allowed.
r
: Relationp
: Predicate
The DELETE
statement first finds all tuples t
in r
for which P(t)
is true, and then deletes them from r
.
Note that DELETE
command operates on only one relation.
Examples
- Delete all tuples from
instructor
table
- Delete all tuples in the instructor relation for those instructors associated with a department located in the Watson building
- Delete all instructors whose salary is less than the average salary of all instructors
SQL first computes the average salary and find all tuples to delete, then delete all corresponding tuples from the relation (without recomputing or retesting the tuples).
Insertion
To insert data into a relation, either a tuple to be inserted, or the query whose result is a set of tuples to be inserted, must be specified.
r
: Relation
Examples
- Insert a new tuple to
course
- Make each student in the Music department who has earned more than 144 credit as an instructor in the Music department with a salary of 18000
The SELECT
- FROM
- WHERE
statement is evaluated fully before any of its results are inserted into the relation.
Update
A value in a tuple can be changed without changing all values in the tuple with the UPDATE
statement.
r
: RelationA
: Attributep
: Predicate
Examples
- Give a 5% salary raise to those instructors who earn less than 70000
- Give a 5% salary raise to instructors whose salary is less than the average of all instructors
Note that the order of UPDATE
statements is very important.
Consider the following query.
If the order of the two updates are changed, the results whould not be as desired.
To prevent order related problems, CASE
construct is provided by SQL.
CASE
construct
CASE
construct can be used in any place where a value is expected.
P_i
: PredicatesR_i
: Resulting value
The error-prone query above can be re-written using CASE
construct.
Updates with scalar subqueries
Scalar subqueries are also useful in SQL update statements, where they can be used in SET
clause.
Example
- Recompute and update
tot_credit
for all students to the credits of courses successfully completed by the student (successfully completed meansgrade
is notF
norNULL
)