SQL Miscellaneous Topics. Views A database view is: – a virtual or logical table based on a query. – a stored query. CREATE VIEW viewname AS query; –CREATE.

Slides:



Advertisements
Similar presentations
DB glossary (focus on typical SQL RDBMS, not XQuery or SPARQL)
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
SQL Sub (or Nested ) Query. Examples Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student.
SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.
Introduction to Structured Query Language (SQL)
Introduction to Oracle9i: SQL1 Subqueries. Introduction to Oracle9i: SQL2 Chapter Objectives Determine when it is appropriate to use a subquery Identify.
Maintaining Referential Integrity Pertemuan 2 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
SQLPlus Commands. Oracle Account Server: libra.sfsu.edu Telnet: libra.sfsu.edu How to use Oracle: –
Structured Query Language Review ISYS 650. Language Overview Three major components: –Data definition language, DDL Create, Drop and Alter Tables or Views.
Introduction to Structured Query Language (SQL)
SPRING 2004CENG 3521 The Relational Model Chapter 3.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
1 Data Modeling Yanlei Diao UMass Amherst Feb 1, 2007 Slides Courtesy of R. Ramakrishnan and J. Gehrke.
Basic SQL Select Commands. Basic Relational Query Operations Selection Projection Natural Join Sorting Aggregation: Max, Min, Sum, Count, Avg –Total –Sub.
View Sen Zhang. Views are very common in business systems users view of data is simplified a form of security - user sees only the data he/she needs to.
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
View and Materialized view. What is a view? Logically represents subset of data from one or more table. In sql, a view is a virtual relation based on.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
SQL DDL constraints Restrictions on the columns and tables 1SQL DDL Constraints.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
INTEGRITY Enforcing integrity in Oracle. Oracle Tables mrobbert owner granted access.
Relational Operators, SQL, and Access Query ISYS 562.
Introduction to Oracle9i: SQL1 Views. Introduction to Oracle9i: SQL2 Chapter Objectives Create a view, using CREATE VIEW command or the CREATE OR REPLACE.
SQL's Data Definition Language (DDL) – View, Sequence, Index.
1 The Relational Model Chapter 3. 2 Why Study the Relational Model?  Most widely used model  Vendors: IBM, Informix, Microsoft, Oracle, Sybase  Recent.
SQL advanced select using Oracle 1 7. Multiple Tables: Joins and Set Operations 8. Subqueries: Nested Queries.
ITBIS373 Database Development
SQL Server 7.0 Maintaining Referential Integrity.
Advanced SQL for Decision Support ISYS 650. Set Operators Union Intersect Difference Cartesian product.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
11 Copyright © Oracle Corporation, All rights reserved. Creating Views.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Views In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.) In some.
The Relational Model1 ER-to-Relational Mapping and Views.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
CN2180 MS SQL Server Kemtis Kunanuraksapong MSIS with Distinction, A+ MCTS, MCDST, MCP.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Indexes and Views Unit 7.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
Chapter 12 Subqueries and Merge Statements
Lecture 3 Book Chapter 3 (part 2 ) From ER to Relational.
Chapter 13 Views Oracle 10g: SQL. Oracle 10g: SQL2 Objectives Create a view, using CREATE VIEW command or the CREATE OR REPLACE VIEW command Employ the.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
Indexes- What?  Optional structures associated with tables  Provides a quick access path to table data  You can create indexes on one or more columns.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
Chapter 7 Subqueries. Chapter Objectives  Determine when it is appropriate to use a subquery  Identify which clauses can contain subqueries  Distinguish.
Copyright © Curt Hill SQL The Data Manipulation Language.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Introduction to Databases & SQL Ahmet Sacan. What you’ll need Firefox, SQLite plugin Mirdb and Targetscan databases.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Logical DB Design: ER to Relational
COP Introduction to Database Structures
Chapter 12 Subqueries and MERGE Oracle 10g: SQL
Lecture#7: Fun with SQL (Part 2)
Referential Integrity
Referential Integrity
Creating and Maintaining
CSC 453 Database Systems Lecture
Presentation transcript:

SQL Miscellaneous Topics

Views A database view is: – a virtual or logical table based on a query. – a stored query. CREATE VIEW viewname AS query; –CREATE VIEW femalestudent AS – SELECT * FROM student WHERE sex=‘f’; CREATE OR REPLACE VIEW femalestudent AS SELECT * FROM student WHERE sex=‘f’;

Correlated SubQueries A correlated subquery references values of the main query. In a correlated subquery, the main query provides values which are used by subquery’s WHERE clause. The subquery is executed repeatedly, once for each row that might be selected by the main query.

Project Table: –PID, Pname, Budget Expenses Table: –PID, Date, Expense Find projects where total expenses exceeding budget. Method 1: Using view a. Create a TotalExpense view: PID, TotalExpense. b. Then join the Project table with the TotalExpense view. Method 2: Using natural join and subtotal SELECT pid, pname, budget FROM project NATURAL JOIN Expense GROUP BY pid, pname,budget HAVING budget < SUM(expense); Method 3:Can we use sub query? SELECT pid, pname, budget FROM project WHERE budget < (SELECT SUM(expense) FROM Expense);

Passing Values from Main Query to SubQuery SELECT pid, pname, budget FROM project WHERE budget < (SELECT SUM(expense) FROM Expense WHERE pid=project.pid);

Find students taking at least 3 courses. 1. Join: –SELECT sid, sname –FROM student NATURAL JOIN registration –GROUP BY sid, sname –HAVING COUNT(cid) >=3; 2. Subquery: –SELECT sid, sname FROM student –WHERE sid IN (SELECT sid FROM registration GROUP BY sid –HAVING COUNT(cid) >=3); 3. Correlated query: –SELECT sid, sname FROM student –WHERE 3 <= (SELECT COUNT(cid) FROM registration WHERE sid = student.sid);

EXISTS, NOT EXISTS Test whether a subquery returns any rows. It returns True/False

Find faculty who advise at least one student. 1. Subquery: –SELECT fid,fname FROM faculty –WHERE fid in (SELECT DISTINCT fid FROM student); 2. Correlated query: –SELECT fid,fname FROM faculty –WHERE EXISTS (SELECT * FROM student –WHERE fid = faculty.fid);

Find students taking 3 courses 1. Sub query: –SELECT sid, sname FROM student –WHERE sid IN (SELECT sid FROM registration GROUP BY sid –HAVING COUNT(cid) = 3); 2. Correlated query: –SELECT sid, sname FROM student –WHERE 3 = (SELECT COUNT(cid) FROM registration WHERE sid=student.sid);

SELECT List Containing Nested Query SELECT sid, sname, (SELECT COUNT(cid) FROM registration WHERE sid=student.sid) AS courses FROM student;

Self Join Recursive relationship: –Employee supervise Employee Ex: EmpFile: empID, empName, superID Find employees’ supervisor name: –SELECT e1.empid, e1.empname,e2.empname as sueprname –FROM empfile e1, empfile e2 –WHERE e1.superid=e2.empid;

Multiple Levels of Nesting Find student who are taking 5-units course. SELECT * FROM student WHERE sid IN ( –SELECT sid FROM registration WHERE cid IN (SELECT cid FROM course WHERE units = 5));

Nesting Aggregates SELECT MAX(AVG(gpa)) FROM student GROUP BY major;

Views A database view is: – a virtual or logical table based on a query. – a stored query. CREATE VIEW viewname AS query; –CREATE VIEW femalestudent AS – SELECT * FROM student WHERE sex=‘f’; CREATE OR REPLACE VIEW femalestudent AS SELECT * FROM student WHERE sex=‘f’;

READ ONLY Views CREATE VIEW viewname AS query –WITH READ ONLY; Ex: –CREATE VIEW readEmp –AS (SELECT * FROM emp) –WITH READ ONLY;

Materialized Views Database snapshot A physical copy – CREATE MATERIALIZED VIEW mvOrders – REFRESH COMPLETE – START WITH SYSDATE NEXT SYSDATE+7 – AS SELECT * FROM Orders; DROP MATERIALIZED VIEW viewname;

Updating Through Views A view is updatable if –the update command does not violate database constraints; –The view is not read only.

DROP VIEW viewname

ROWNUM Field ROWNUM field is a pseudocolumn that applies to every table and view. Use ROWNUM to do Top n Analysis: –Select students with the best 3 GPA Create a view order by GPA, then select from view with rownum <=3. Or using InLineView

InLine View When a multiple-column subquery is used in the FROM clause of an outer query, it basically creates a temporary table that can be referenced by other clauses of the outer query. The temporary table is called InLine view. Ex 1: –SELECT sid, sname FROM –(SELECT * FROM student NATURAL JOIN registration) –WHERE cid=‘isys263’; Note: This is different from: –SELECT sid, sname FROM –student NATURAL JOIN registration –WHERE cid=‘isys263’; Ex 2: –SELECT * FROM (SELECT * FROM student ORDER BY GPA DESC);

Top (Last) n Analysis Find students with the top 3 GPA. Can we do: –SELECT * FROM student ORDER BY GPA desc WHERE ROWNUM<=3; ? --- No! SELECT * FROM (SELECT * FROM student ORDER BY GPA DESC) WHERE ROWNUM<=3; Note: Use the ROWNUM of the InLineView.

Indexes Field declared as PRIMARY KEY will have an index. CREATE INDEX indexname –ON tablename (column names separated by commas); –Ex: CREATE INDEX fkFID ON student (fid); DROP INDEX indexname;

Bitmap Index Useful for improving queries on columns that have a small number of distinct values. CREATE BITMAPINDEX indexname –ON tablename (column names separated by commas);

Maintaining Referential Integrity FOREIGN KEY (field) REFREENCES parentable DROP TABLE parent; CREATE TABLE parent ( pid char(3) not null, pname varchar(20), PRIMARY KEY (pid) ); drop table child; CREATE TABLE child ( cid char(3) not null, cname varchar(20), pid char(3), PRIMARY KEY (cid), FOREIGN KEY (pid) REFERENCES parent ON DELETE SET NULL ); Insert into parent values ('p1','peter'); Insert into parent values ('p2','paul'); Insert into child values ('c1','mary','p1'); Insert into child values ('c2','john','p1'); Insert into child values ('c3','mary','p2');

ON DELETE ON DELETE SET NULL ON DELETE CASCADE