Chapter 4 Lecture 2 SQL 4.6 – 4.9 Joining Multiple Tables Display book titles and the first and last names of customers who ordered them Traditional method JOIN method Aggregate Functions Display total profit from books sold Display total profit from books sold on order 1007 Display average profit by category Subqueries Display title, retail price, category, and the corresponding category average price for each book that has a higher-than-average price than other books in its category Select title, retail, category, cataverage From books natural join (select category, avg(retail) cataverage From books Group by category); Display categories and average profit values for those categories that have a higher average profit than the Literature category does Select category, avg(retail-price) “Average Profit” From books Group by category Having avg(retail-price) > (select avg(retail-price) From books Where category = “LITERATURE”); Data Manipulation Inserting new records INSERT INTO tablename [(columname, ...)] VALUES (datavalue, ...); Insert a record for yourself into the Customers table. Insert a new book into the Books table Make an order for yourself (insert record into the database) Modifying Existing Rows UPDATE tablename SET columnname = new_datavalue [WHERE condition]; Modify your REFERRED, or ADDRESS info; or Modify the pricing info of the books you entered Deleting Rows DELETE FROM tablename [WHERE condition]; Delete a (few) row(s) you’ve entered. ROLLBACK Views Creating a Simple View A simple view is created from a subquery that only references one table and doesn’t include a group function, or GROUP BY clause. (It’s possible to update through a simple view.) CREATE VIEW inventory AS SELECT isbn, title, price FORM books WITH READ ONLY; The last clause is used to prevent data from being modified by the user of this view. Creating a Complex View A complex view is one that is not simple. CREATE VIEW prices AS SELECT isbn, title, cost, retial, retail-price profit, name FORM books NATURAL JOIN publishers; The following limitations apply to DML operations on the view prices. No changes can be made to - the field profit: a calculated field - the name field: a column from a non key-preserved table In addition, no changes may be made to views with a group function or a group by clause. Top-N Analysis SELECT columnname, ... FORM subquery WHERE ROWNUM <= N; Top five most-profitable books may be retrieved by SELECT title, profit FORM (SELECT title, retail-cost profit FROM books ORDER BY retail-cost DESC) WHERE ROWNUM <= 5;
© Copyright 2026 Paperzz