Upload
elvin-boone
View
225
Download
5
Embed Size (px)
Citation preview
Final Review
Dr. Bernard Chen Ph.D.University of Central Arkansas
Adding a New Column to an Existing Table The general syntax to add a
column to an existing table is
ALTER TABLE tablename
ADD columnname datatype;
SQL> ALTER TABLE student 2 ADD SocialSecurity CHAR(9);Table altered.SQL>
Modifying an Existing Column The general syntax to modify an existing column is
ALTER TABLE tablenameMODIFY columnname newdatatype;
where newdatatype is the new data type or the new size for the column.
SQL> ALTER TABLE student 2 MODIFY SocialSecurity VARCHAR2(11);Table altered.SQL>
Adding a Constraint To add a constraint using ALTER TABLE, the
syntax for table level constraint is used. The general syntax of ALTER TABLE is
ALTER TABLE tablenameADD [CONSTRAINT constraint_name]
constraint_type (column, …),
SQL> ALTER TABLE COURSE 2 ADD CONSTRAINT COURSE_PREREQ_FK FOREIGN KEY (PREREQ) 3 REFERENCES COURSE(COURSEID);Table altered.SQL>
Displaying Table Information When a user creates a table or many
tables in the database, Oracle tracks them using its own data dictionary
Viewing a User’s Table NamesSELECT TABLE_NAME FROM USER_TABLES;
To display all information:SELECT * FROM USER_TABLES;
Dropping a Column The general syntax is
ALTER TABLE tablename DROP COLUMN columnname;
Dropping a Table The general syntax is
DROP TABLE tablename [CASCADE CONSTRAINTS];
For example,DROP TABLE sample;
Oracle displays a “Table dropped” message when a table is successfully dropped.
If you add optional CASCADE CONSTRAINTS clause, it removes foreign key references to the table also.
ADDING A NEW ROW/RECORD There are two methods for inserting a NULL
value in a column.
1. Implicit Method. In the implicit method, the column’s name is omitted from the column list in an INSERT statement. For example,
INSERT INTO dept (DeptId, DeptName)
VALUES (50, ‘Production’);
ADDING A NEW ROW/RECORD
2. Explicit Method. In the explicit method, the value NULL is used as a value for numeric column, and an empty string (‘’) is used for date or character columns. For example,
INSERT INTO dept (DeptId, DeptName, Location, EmployeeId)VALUES (60, ‘Personnel’, ‘Chicago’, NULL);
UPDATING EXISTING ROWS/RECORDS The condition is optional, but it is
necessary
Suppose the student with ID 00103 in the IU college’s database switches major from BS---CS to BS---EE
UPDATE studentSet MajorID = 700Where studentid=‘00103’
DELETING EXISTING ROWS/RECORDS
Example:
DELETE FROM deptWHERE DeptID = 70
Major Outlines
Relational Algebra Relational algebra is the basic set of
operations for the relational model These operations enable a user to
specify basic retrieval requests (or queries)
Data Management and Retrieval Languages
Relational Algebra Overview Relational Algebra consists of several groups of
operations Unary Relational Operations
SELECT (symbol: (sigma)) PROJECT (symbol: (pi)) RENAME (symbol: (rho))
Relational Algebra Operations From Set Theory UNION ( ), INTERSECTION ( ), DIFFERENCE (or MINUS,
– ) CARTESIAN PRODUCT ( x )
Binary Relational Operations JOIN (several variations of JOIN exist) DIVISION
Additional Relational Operations AGGREGATE FUNCTIONS
SELECT
The SELECT operation (denoted by (sigma)) is used to select a subset of the tuples from a relation based on a selection condition
The selection condition acts as a filter Keeps only those tuples that satisfy the
qualifying condition Tuples satisfying the condition are selected
whereas the other tuples are discarded (filtered out)
SELECT
For example, to select the tuples for all employees who either work in department 4 and make over $25000 per year, or work in department 5 and make over $30000, the select operation should be:
(DNO=4 AND Salary>25000 ) OR (DNO=5 AND Salary>30000 ) (EMPLOYEE)
PROJECT PROJECT Operation is denoted by (pi)
If we are interested in only certain attributes of relation, we use PROJECT
This operation keeps certain columns (attributes) from a relation and discards the other columns.
PROJECT
Example: To list each employee’s first and last name and salary, the following is used:
LNAME, FNAME,SALARY(EMPLOYEE)
RENAME The RENAME operator is denoted by
(rho)
In some cases, we may want to rename the attributes of a relation or the relation name or both Useful when a query requires multiple
operations Necessary in some cases (see JOIN
operation later)
RENAME The general RENAME operation can be
expressed by any of the following forms: S(R) changes:
the relation name only to S
(B1, B2, …, Bn )(R) changes: the column (attribute) names only to B1, B1,
…..Bn
S (B1, B2, …, Bn )(R) changes both: the relation name to S, and the column (attribute) names to B1, B1, …..Bn
Relational Algebra Operations from Set Theory
Union
Intersection
Minus
Cartesian Product
UNION
It is a Binary operation, denoted by
The result of R S, is a relation that includes all tuples that are either in R or in S or in both R and S
Duplicate tuples are eliminated
INTERSECTION INTERSECTION is denoted by
The result of the operation R S, is a relation that includes all tuples that are in both R and S The attribute names in the result will be the
same as the attribute names in R
The two operand relations R and S must be “type compatible”
SET DIFFERENCE SET DIFFERENCE (also called MINUS or
EXCEPT) is denoted by –
The result of R – S, is a relation that includes all tuples that are in R but not in S The attribute names in the result will be
the same as the attribute names in R
The two operand relations R and S must be “type compatible”
Example to illustrate the result of UNION, INTERSECT, and DIFFERENCE
CARTESIAN PRODUCT CARTESIAN PRODUCT Operation
This operation is used to combine tuples from two relations in a combinatorial fashion.
Denoted by R(A1, A2, . . ., An) x S(B1, B2, . . ., Bm)
Result is a relation Q with degree n + m attributes: Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
if R has nR tuples (denoted as |R| = nR ), and S has nS tuples, then R x S will have nR * nS tuples.
JOIN JOIN Operation (denoted by )
The sequence of CARTESIAN PRODECT followed by SELECT is used quite commonly to identify and select related tuples from two relations
This operation is very important for any relational database with more than a single relation, because it allows us combine related tuples from various relations
JOIN Consider the following JOIN operation:
If R(A1, A2, . . ., An) and S(B1, B2, . . ., Bm) Think about R.Ai=S.Bj
Result is a relation Q with degree n + m attributes: Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
The resulting relation state has one tuple for each combination of tuples—r from R and s from S, but only if they satisfy the join condition r[Ai]=s[Bj]
Hence, if R has nR tuples, and S has nS tuples, then the join result will generally have less than nR * nS tuples.
EQUIJOIN The most common use of join involves join
conditions with equality comparisons only
Such a join, where the only comparison operator used is =, is called an EQUIJOIN
The JOIN seen in the previous example was an EQUIJOIN
JOIN The general case of JOIN operation is
called a Theta-join: R theta S
The join condition is called theta
Theta can be any general boolean expression on the attributes of R and S; for example: R.Ai<S.Bj AND (R.Ak=S.Bl OR R.Ap<S.Bq)
NATURAL JOIN
Another variation of JOIN called NATURAL JOIN — denoted by *
It was created to get rid of the second (superfluous) attribute in an EQUIJOIN condition.
NATURAL JOIN Another variation of JOIN called NATURAL JOIN —
denoted by *
Example: To apply a natural join on the DNUMBER attributes of DEPARTMENT and DEPT_LOCATIONS, it is sufficient to write:
DEPT_LOCS DEPARTMENT * DEPT_LOCATIONS
Only attribute with the same name is DNUMBER
An implicit join condition is created based on this attribute:
DEPARTMENT.DNUMBER=DEPT_LOCATIONS.DNUMBER
Generalized Projection It extend the projection by allowing
functions of attributes to be included in the projection list.
The general form is: F1, F2, …, Fn (R) where F1, F2,…Fn are functions over the attributes
Generalized Projection For example Consider the relation
Employee (Ssn, salary, Deduction, Year_service)
A report may be required to show:Net_salary = salary – DeductionBonus = 2000 * year_serviceTax = Salary * 25%
Then a generalized projection combined with renaming may be:
Report (Ssn, Net_salary, Bonus, Tax )
( Ssn, salary-deduction, 2000*years_service, salary*25% (R))
Aggregate Functions and Grouping A type of request that cannot be
expressed in the basic relational algebra is to specify mathematical aggregate functions on collections of values from the database.
Examples of such functions include retrieving the average or total salary of all employees or the total number of employee tuples.
Aggregate Functions and Grouping
Common functions applied to collections of numeric values include SUM, AVERAGE, MAXIMUM, and
MINIMUM.
The COUNT function is used for counting tuples or values.
Aggregate Functions and Grouping Grouping can be combined with Aggregate
Functions
Example: For each department, retrieve the DNO, COUNT SSN, and AVERAGE SALARY
A variation of aggregate operation Ʒ allows this:
Grouping attribute placed to left of symbol Aggregate functions to right of symbol
DNO Ʒ COUNT SSN, AVERAGE Salary (EMPLOYEE)
Examples of applying aggregate functions and grouping
Examples of Queries in Relational Algebra Q1: Retrieve the name and address of all employees who work for
the ‘Research’ department. Q2: For every project located in “Stafford”, list the project
number, the controlling department number, and the department manager’s last name, address, and Bdate
Q3: Find the names of employees who work on all the projects controlled by department number 4
Q4: Make a list of project numbers for projects that involve an employee whose last name is “Smith”, either as a worker or as a manager of the department that controls the project
Q5: List the names of all employees with two or more dependents Q6: Retrieve the names of employees who have no dependents. Q7: List the names of managers who have at least one dependent
Major Outlines
Relational Algebra
Data Management and Retrieval Languages
DATA MANIPULATION LANGUAGE (DML)
SQL language’s Data Manipulation Language (DML) consists of three statements: INSERT UPDATE DELETE
ADDING A NEW ROW/RECORD If you do enter column names, they do
not have to be in the same order as they were defined in table’s structure at the time of creation.
INSERT INTO student (StudentID, LAST, FIRST, ZIP, Bdate, FacultyID)
VALUES (‘00100’, ‘Will’, ‘Smith’, ‘72034’, ’12-FEB-80’, 123)
UPDATING EXISTING ROWS/RECORDS The condition is optional, but it is
necessary
Suppose the student with ID 00103 in the IU college’s database switches major from BS---CS to BS---EE
UPDATE studentSet MajorID = 700Where studentid=‘00103’
DELETING EXISTING ROWS/RECORDS Deletion is another data
maintenance operation. In Oracle, the SQL statement
DELETE is used for deleting unwanted rows. Its general syntax is
DELETE FROM deptWHERE DeptID = 70
RETRIEVING DATA FROM A TABLE The main purpose of the SQL language
is for querying the database
The most important statement or query is the SELECT query
The general syntax isSELECT columnlistFROM tablename;
RETRIEVING DATA FROM A TABLERESTRICTING DATA WITH A WHERE CLAUSE A WHERE clause is used with the SELECT
query to restrict rows picked
The general syntax of the WHERE clause is
SELECT columnlistFROM tablename[WHERE condition(s)];
RETRIEVING DATA FROM A TABLE The ORDER BY clause is used with the SELECT query
to sort rows in a table.
The general syntax isSELECT columnlistFROM tablename[WHERE condition(s)][ORDER BY column|expression [ASC|
DESC]];
Grouping Data The GROUP BY clause is used for
grouping data. The general syntax is
SELECT column, groupfunction (column)
FROM tablename[WHERE condition(s)][GROUP BY column|expression][ORDER BY column|expression [ASC|DESC]];
Equijoin
SELECT student.Last STUDENT, faculty.Name
Faculty
FROM student, faculty WHERE student.FacultyID = faculty.FacultyID
Multiple Joins SELECT e.Lname EMPLOYEE,
d.DeptName Department, q.QualDesc QUALIFICATION
FROM EMPLOYEE e, Department d, QUALIFICATION q
WHERE e.DeptID = d.DeptID AND e.QualID = q.QualID
Creating a table using a subquery You can create a table by using a
nested SELECT query. The Query will create a new table and
populated it with the rows selected from the other table.
CREATE TABLE tablenameASSELECT query
Convert
Group Functions
Join
Set Theory Union Intersect Minus
Generally, the syntax would looks like:QuerySet OperationQuery