Presentation is loading. Please wait.

Presentation is loading. Please wait.

Final Review Dr. Bernard Chen Ph.D. University of Central Arkansas.

Similar presentations


Presentation on theme: "Final Review Dr. Bernard Chen Ph.D. University of Central Arkansas."— Presentation transcript:

1 Final Review Dr. Bernard Chen Ph.D. University of Central Arkansas

2 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>

3 Modifying an Existing Column The general syntax to modify an existing column is ALTER TABLE tablename MODIFY 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>

4 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 tablename ADD [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>

5 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 Names SELECT TABLE_NAME FROM USER_TABLES; To display all information: SELECT * FROM USER_TABLES;

6 Dropping a Column The general syntax is ALTER TABLE tablename DROP COLUMN columnname;

7 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.

8 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’);

9 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);

10 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 student Set MajorID = 700 Where studentid=‘00103’

11 DELETING EXISTING ROWS/RECORDS Example: DELETE FROM dept WHERE DeptID = 70

12 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

13 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

14 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)

15 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)

16 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.

17 PROJECT Example: To list each employee’s first and last name and salary, the following is used:  LNAME, FNAME,SALARY (EMPLOYEE)

18 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)

19 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

20 Relational Algebra Operations from Set Theory Union Intersection Minus Cartesian Product

21 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

22 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”

23 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”

24 Example to illustrate the result of UNION, INTERSECT, and DIFFERENCE

25 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 n R tuples (denoted as |R| = n R ), and S has n S tuples, then R x S will have n R * n S tuples.

26 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

27 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 n R tuples, and S has n S tuples, then the join result will generally have less than n R * n S tuples.

28 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

29 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)

30 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.

31 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

32 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

33 Generalized Projection For example Consider the relation Employee (Ssn, salary, Deduction, Year_service) A report may be required to show: Net_salary = salary – Deduction Bonus = 2000 * year_service Tax = 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))

34 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.

35 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.

36 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)

37 Examples of applying aggregate functions and grouping

38 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

39 Major Outlines Relational Algebra Data Management and Retrieval Languages

40 DATA MANIPULATION LANGUAGE (DML) SQL language’s Data Manipulation Language (DML) consists of three statements: INSERT UPDATE DELETE

41 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)

42 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 student Set MajorID = 700 Where studentid=‘00103’

43 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 dept WHERE DeptID = 70

44 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 is SELECT columnlist FROM tablename;

45 RETRIEVING DATA FROM A TABLE RESTRICTING 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 columnlist FROM tablename [WHERE condition(s)];

46 RETRIEVING DATA FROM A TABLE The ORDER BY clause is used with the SELECT query to sort rows in a table. The general syntax is SELECT columnlist FROM tablename [WHERE condition(s)] [ORDER BY column|expression [ASC|DESC]];

47 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]];

48 Equijoin SELECT student.Last STUDENT, faculty.Name Faculty FROM student, faculty WHERE student.FacultyID = faculty.FacultyID

49 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

50 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 tablename AS SELECT query

51 Convert

52 Group Functions

53 Join

54 Set Theory Union Intersect Minus Generally, the syntax would looks like: Query Set Operation Query


Download ppt "Final Review Dr. Bernard Chen Ph.D. University of Central Arkansas."

Similar presentations


Ads by Google