Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin

Similar presentations


Presentation on theme: "SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin"— Presentation transcript:

1 SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin

2 Plan for Adv. Options, Updates and Views
Advanced options of the query language Joined tables, Outer join, Aggregate functions Grouping Update commands: Insert, Delete, and Update SQL views Additional features of SQL Readings: Chapters 4 and 5

3 Joined Tables To avoid mixing conditional expressions and join conditions in the WHERE clause, it is possible to define join in the FROM clause Retrieve first name, course id and corresponding grades of the student with Student Id = SELECT FName, CourId, Grade FROM Student NATURAL JOIN Grades WHERE StudId = ; (…FROM Student s JOIN Grades g ON s.StudId = g.StudId … (equi join)) It can also be any kind of a theta join, or any kind of an outer join Student Natural JOIN Grades is just one joined table. There can be more joined tables defined in the FROM clause.

4 Outer Join Outer join has been defined to overcome problems with null values and tuples of the referenced table being not referenced A conventional join: SELECT * FROM R1 JOIN R2 ON R1.B = R2.B; R1 R2 R1 JOIN R2 A B C a1 ω b1 c1 a2 b2 b3

5 Left Outer Join A a left outer join:
SELECT * FROM R1 LEFT JOIN R2 ON R1.B = R2.B; R1 R2 R1 LEFT JOIN R2 A B C a1 ω b1 c1 a2 b2 b3

6 Right Outer Join A right outer join:
SELECT * FROM R1 RIGHT JOIN R2 ON R1.B = R2.B; R1 R2 R1 RIGHT JOIN R2 A B C a1 ω b1 c1 a2 b2 b3

7 Full Outer Join A full outer join:
SELECT * FROM R1 FULL JOIN R2 ON R1.B = R2.B; R1 R2 R1 RIGHT JOIN R2 A B C a1 ω b1 c1 a2 b2 b3

8 Aggregate Functions SQL supports COUNT, SUM, AVG, MIN, MAX and some other aggregate functions that can be used in a SELECT clause e.g. What is the total point value of the courses in the COMP dept? SELECT SUM(Points ) FROM Course WHERE Dept = 'Comp'; How many different first names do COMP majors have? SELECT COUNT(DISTINCT FName ) AS NoOfNames FROM Student WHERE Major = 'Comp'; sum_Points 52 COUNT(*) returns the number of tuples in the query result, COUNT(〈atribute_list〉) returns the number of rows having not null values in the columns of the attribute list, while COUNT(DISTINCT〈atribute_list〉) returns the number rows having distinct values that are not null SUM and AVERAGE can be applied to numeric attributes, only. MIN and MAX can be applied on the attributes with a total ordering. It is a question what happens if a SUM (or AVERAGE) attribute contains a null value. NoOfNames 1

9 Grouping GROUP BY clause is used to apply an aggregate function to groups of tuples Groups are determined by means of a grouping attribute list and all attributes from that list have to appear in the query result e.g. For each student, retrieve the number of courses passed SELECT StudId, COUNT(*) FROM Grades WHERE Grade IS NOT NULL GROUP BY StudId ; StudId COUNT(*) 007007 4 131313 1 555555

10 HAVING Clause HAVING clause is used to choose from groups according to a condition specified on aggregate function values Whereas a conditional expression in the WHERE clause filters individual tuples, the HAVING clause filters groups of tuples e.g. Retrieve the number of courses passed for students that passed at least two courses SELECT StudId, COUNT(*) FROM Student s NATURAL JOIN Grades g WHERE Grades IS NOT NULL GROUP BY s.StudId HAVING COUNT(*) > 1; Whereas selection condition in the WHERE clause chooses between tuples, condition in the HAVING clause chooses between groups of tuples StudId COUNT(*) 007007 4

11 Summary of SQL queries SELECT 〈attribute_and_function_list〉
FROM 〈table_list〉 [WHERE 〈condition〉] [GROUP BY 〈grouping_attribute_list〉] [HAVING 〈group_condition〉] [ORDER BY 〈attribute_list〉] In principle, we can say the following (although a query optimizer performs it differently): The FROM clause is executed first to identify all relations involved and, to materialize any join table, this materialization is done by executing a Cartesian product of the tables listed in the FROM clause, Then is WHERE clause evaluated for every tuple from the Cartesian product, the tuples that evaluate true are inserted into temporary query result, Tuples from temporary query result are projected onto attributes from SELECT clause, Then is GROUP BY applied, Follows HAVING, and Finally ORDER BY clause.

12 Database Update Commands
INSERT command to insert new tuples in the relation, But, DBMS checks for duplicates first DELETE command to find and delete tuples from relation, and UPDATE command to find, modify and store again tuples in the relation

13 INSERT Command INSERT INTO 〈table_name〉 [〈attribute_list〉]
( VALUES (〈value_list〉) | SELECT …) INSERT INTO Student VALUES (111111, 'Bole', 'Ann', Math); The values in VALUES have to appear in the same order as the attributes in the corresponding CREATE TABLE command, INSERT INTO Student (FName, LName, StudId ) VALUES('Ann', 'Bole', ); Useful when values of attributes: Declared as NULL, or Having DEFAULT value are missing Not allowed if the missing attribute is declared NOT NULL

14 INSERT Command (continued)
A form of INSERT command that is suitable for creation of materialized vies and temporary tables CREATE TABLE StudentInfo ( StudId INT PRIMARY KEY, LName CHAR(15) NOT NULL, NoOfCourses INT); INSERT INTO StudentInfo SELECT s.StudId, LName, COUNT(*) AS NoOfCourses FROM Student s, Grades g WHERE s.StudId = g.StudId GROUP BY StudId, LName ; The table we wont to populate by data If a query is to complex, it is advisable to implement it step by step by creating and populating a series of tables with intermediate results. If DBMS doesn't support nested queries, the above approach is the only available to simulate nested queries.

15 DELETE Command DELETE FROM 〈table_name〉 [WHERE 〈condition〉]
DELETE FROM Student WHERE FName = 'Susan'; WHERE StudId IN (SELECT s.StudId FROM Student s, Grades g WHERE s.StudId = g.StudId AND CourId = 'C302'); DELETE FROM Student ; First DELETE command deletes all Student tuples where the FName is 'Susan'. Second DELETE command deletes all students that enrolled or passed Comp302 The third DELETE command deletes all Student tuples, but lives the table itself in the Catalog.

16 UPDATE Command UPDATE〈table_name〉
SET 〈attribute_name〉=〈value_expression〉 {, 〈attribute_name〉=〈value_expression〉} [WHERE 〈condition〉] e.g. UPDATE Grades SET Grade = 'A+' WHERE CourId = 'C302'; Again, it is possible to update a set of tuples by one command, if all the tuples should be modified by the same value Again, the condition of the WHERE clause can be simple, or may contain nested query. If the WHERE clause is omitted, all the relation tuples are updated

17 Views in SQL A SQL view is a virtual table that is derived from other base or virtual tables Base tables are defined by CREATE TABLE command and are permanently stored in a database Virtual tables are defined by the CREATE VIEW command to avoid defining complex SQL retrieval expressions repeatedly The definition of a view is stored in the Catalog, but its data are not stored in the database itself, so it is computed every time it is used in a query Contrast the up to date status of a temporary table and the corresponding view

18 SQL Views Assume the course table contains the attribute Hours (number of lecture and tutorial hours per week) A view definition CREATE VIEW StudOccupied AS SELECT g.StudId, SUM(Hours ) AS Occupied FROM Grades g, Course p WHERE g.CourId = p.CourId AND Grade IS NULL GROUP BY StudId ; Deleting a view DROP VIEW StudOccupied ; It is supposed that Grades relation contains null values in Grade column for student – course pairs if the student currently attends classes for courses, and accordingly hasn't any grade

19 Additional Features of SQL
Assertions as general constraints (CREATE ASSERTION – a DDL command that may use DML SELECT command) Triggers as procedures stored with tables GRANT and REVOKE commands to deal with database user privileges Embedded SQL and CURSOR SQL transaction control commands (COMMIT, ROLLBACK) User Defined Functions (UDF): SQL Functions Procedural Language (C, PL/pgSQL, Java) Functions Assertions as general constraints Complex database constraints are declared by means of CREATE ASSERTION statement Triggers as procedures stored with tables Trigger contains specification of an event and corresponding action Event can be constraint violation or a pre specified database state Action is either to prevent constraint violation, or to inform user about the database state The concept of the trigger is crucial for active databases GRANT and REVOKE commands to deal with database user privileges Embedded SQL and CURSOR SQL statements are embedded into "host language" program, so that all the traffic between program and the database is accomplished via SQL Cursor is the result of a SQL query that is considered by the host program as a file with sequential access mode

20 Summary The relational database language has commands to define:
Database structure (schema, domain, table, and constraints) (CREATE SCHEMA, CREATE DOMAIN, CREATE TABLE) Queries (SELECT… FROM… WHERE… GROUP BY…HAVING… ORDER BY…) Update operations (INSERT, DELETE, UPDATE) views (CREATE VIEW) Additional features (ASSERTION, TRIGGER, CURSOR, GRANT, REVOKE, COMMIT, ROLLBACK, DEFINE FUNCTION) Although SQL is defined by a standard, implementations have some dialects and exceptions

21 Next Lecture Relational Algebra


Download ppt "SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin"

Similar presentations


Ads by Google