Instructor: Craig Duckett Lecture 11: Thursday, November 5 th, 2015 Assignment 2 DUE, Set Operations, Subqueries, Views 1 BIT275: Database Design (Fall.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

What is a Database By: Cristian Dubon.
The Relational Model and Relational Algebra Nothing is so practical as a good theory Kurt Lewin, 1945.
Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.
Structure Query Language (SQL) COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Introduction to Structured Query Language (SQL)
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making.
Introduction to Structured Query Language (SQL)
1 Query Languages: How to build or interrogate a relational database Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL - part 2 - Database Management Systems I Alex Coman, Winter 2006.
Database Systems More SQL Database Design -- More SQL1.
A Guide to MySQL 7. 2 Objectives Understand, define, and drop views Recognize the benefits of using views Use a view to update data Grant and revoke users’
Introduction to Structured Query Language (SQL)
Chapter 4 Relational Databases Copyright © 2012 Pearson Education, Inc. publishing as Prentice Hall 4-1.
A Guide to SQL, Seventh Edition. Objectives Understand, create, and drop views Recognize the benefits of using views Grant and revoke user’s database.
Concepts of Database Management Sixth Edition
Chapter 4 Relational Databases Copyright © 2012 Pearson Education 4-1.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
INFORMATION TECHNOLOGY IN BUSINESS AND SOCIETY SESSION 16 – SQL SEAN J. TAYLOR.
Lecture 2 The Relational Model. Objectives Terminology of relational model. How tables are used to represent data. Connection between mathematical relations.
ASP.NET Programming with C# and SQL Server First Edition
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Concepts of Database Management, Fifth Edition Chapter 4: The Relational Model 3: Advanced Topics.
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
Views: Limiting Access to Data A view is a named select statement that is stored in a database as an object. It allows you to view a subset of rows or.
MIS 301 Information Systems in Organizations Dave Salisbury ( )
Analyzing Data For Effective Decision Making Chapter 3.
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Views Lesson 7.
CpSc 3220 The Language of SQL The Language of SQL Chapters
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BACS 287 Structured Query Language 1. BACS 287 Visual Basic Table Access Visual Basic provides 2 mechanisms to access data in tables: – Record-at-a-time.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Instructor: Craig Duckett Lecture 08: Thursday, October 22 nd, 2015 Patterns, Order of Evaluation, Concatenation, Substrings, Trim, Position 1 BIT275:
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
 CONACT UC:  Magnific training   
SQL Basics Review Reviewing what we’ve learned so far…….
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
LEC-8 SQL. Indexes The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
SQL IMPLEMENTATION & ADMINISTRATION Indexing & Views.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Instructor: Craig Duckett Lecture 11: Thursday, May 4th, 2017
More SQL: Complex Queries,
CpSc 3220 The Language of SQL
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
Database Systems: Design, Implementation, and Management Tenth Edition
More SQL: Complex Queries, Triggers, Views, and Schema Modification
A Guide to SQL, Eighth Edition
Chapter 2 Views.
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Database Systems: Design, Implementation, and Management Tenth Edition
IST 318 Database Administration
Presentation transcript:

Instructor: Craig Duckett Lecture 11: Thursday, November 5 th, 2015 Assignment 2 DUE, Set Operations, Subqueries, Views 1 BIT275: Database Design (Fall 2015)

2 TONIGHT Assignment 2 due TONIGHT Thursday, November 5 th, In StudentTracker by MIDNIGHT Assignment 3 is due LECTURE 19, Tuesday, December 8 th, in StudentTracker by MIDNIGHT Final Exam is LECTURE 20, Thursday, December 10 th

3 Tuesday (LECTURE 10) Database Design for Mere Mortals: Chapter 7 Thursday (LECTURE 11) The Language of SQL: Chapters 9, 10

4 Mid-Term Post-Mortem Set Operations Subqueries Views

5 Mid-Term Post-Mortem MID-TERM

Mid-Term Post-Mortem Answers Ideal Field, Ideal Table Ideal Table: “It represents a single subject which can be an object or an event” Purpose of database is threefold: A repository of data The gathering of data (interface, multiple users) The collection of information from the data Extra Credit 100% + Extra Credit (my idea was that the extra credit was meant to supplement points towards 100) 100% + Extra Credit (less points available) 100% + extra credit truncated to 100 points possible 100% + “Bonus” question (with no possible points advertised) Bansenauer No extra credit

7 Set Operations

Set theory is fundamental to the relational model. But whereas mathematical sets are unchanging, database sets are dynamic—they grow, shrink, and otherwise change over time. This chapter covers the following SQL set operators, which combine the results of two SELECT statements into one result: UNION returns all the rows returned by both queries, with duplicates removed. INTERSECT returns all rows common to both queries (that is, all distinct rows retrieved by both queries). EXCEPT returns all rows from the first query without the rows that appear in the second query, with duplicates removed. These set operations aren’t joins, but you can mix and chain them to combine two or more tables.

Set Operations: UNION Operator The SQL UNION operator is used to combine the result sets of two or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION must have the same number of column fields in the result sets and all with similar data types. UNION can be useful in data warehouse applications where tables aren't perfectly normalized. A simple example would be a database having tables sales2005 and sales2006 that have identical structures but are separated because of performance considerations. A UNION query could combine results from both tables. Note that UNION does not guarantee the order of rows. Rows from the second operand may appear before, after, or mixed with rows from the first operand. In situations where a specific order is desired, ORDER BY must be used. Note that UNION ALL may be much faster than plain UNION

Set Operations: UNION Operator Difference between SQL JOIN and a UNION The columns of joining tables may be different in JOIN but in UNION the number of columns and order of columns of all queries must be same.

Set Operations: UNION Operator Example: Note that there are two rows for Joe because those rows are distinct across their columns. There is only one row for Alex because those rows are not distinct for both columns. UNION ALL gives different results, because it will not eliminate duplicates. Executing this statement… …would give these results, again allowing variance for the lack of an ORDER BY statement:

Set Operations: INTERSECT Operator MySQL does not support the INTERSECT operator The SQL INTERSECT operator is used to return the results of two or more SELECT statements. However, it only returns the rows selected by all queries. If a record exists in one query and not in the other, it will be omitted from the INTERSECT results. Each SQL statement within the SQL INTERSECT must have the same number of fields in the result sets with similar data types. For purposes of duplicate removal the INTERSECT operator does not distinguish between NULLs. The INTERSECT operator removes duplicate rows from the final result set. The INTERSECT ALL operator does not remove duplicate rows from the final result set. Example : The following example INTERSECT query returns all rows from the Orders table where Quantity is between 50 and and-except-clauses/ and-except-clauses/

Set Operations: EXCEPT Operator MySQL does not support the EXCEPT operator The EXCEPT operator is used to return all rows in the first SELECT statement that are not returned in the second SELECT statement. Each SELECT statement must have the same number of fields in the result sets with similar data types. The EXCEPT ALL operator (not supported in MS SQL) does not remove duplicates. For purposes of row elimination and duplicate removal, the EXCEPT operator does not distinguish between NULLs. Example The following example EXCEPT query returns all rows from the Orders table where Quantity is between 1 and 49, and those with a Quantity between 76 and 100. Worded another way: the query returns all rows where the Quantity is between 1 and 100, except from rows where the quantity is between 50 and and-except-clauses/ and-except-clauses/

Set Operations: EXCEPT Operator The following example is equivalent to the above example but without using the EXCEPT operator.

15 Subqueries

SQL Subqueries SELECT * FROM Toys WHERE numberLegs = (SELECT MAX(numberLegs) FROM Toys) Subqueries are query statements tucked inside of query statements. Like the order of operations from Algebra class, order of operations also come into play when you start to embed SQL commands inside of other SQL commands (subqueries). Let's take a look at an example involving the toys table and figure out how to select only toys with the greatest number of legs. To accomplish this, we are first going to introduce a built-in SQL function, MAX(). This function wraps around a table column and quickly returns the current maximum (max) value for the specified column. We are going to use this function to return the names of all those toys that possess the current "max" number of legs.

SQL Subqueries SELECT * FROM Toys WHERE numberLegs = (SELECT MAX(numberLegs) FROM Toys) A subquery is a SQL query nested inside a larger query. A subquery may occur in a: SELECT clause FROM clause WHERE clause The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery. A subquery is usually added within the WHERE Clause of another SQL SELECT statement. You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row operator, such as IN, ANY, or ALL. A subquery is treated as an inner query, which is a query placed as part of an outer query. The inner query executes first before its parent query so that the results of inner query can be passed to the outer query.

SQL Subqueries

This is what is returned by the subquery

SQL Subqueries

SELECT CompanyName FROM Customers WHERE CustomerID = ? SELECT CustomerID FROM Orders WHERE OrderID = 10290; [ RESULT: COMMI ] SELECT CompanyName FROM Customers WHERE CustomerID = ‘COMMI’ [ RESULT: Comércio Mineiro ] SELECT CompanyName FROM Customers WHERE CustomerID = (SELECT CustomerID FROM Orders WHERE OrderID = 10290); [RESULT: Comércio Mineiro] Northwind Database Example Without Subquery With Subquery

SQL Subqueries W3Resource

34 Views

SQL Views SQL VIEWS are data objects, and like SQL Tables, they can be queried, updated, and dropped. A SQL VIEW is a virtual table containing columns and rows except that the data contained inside a view is generated dynamically from SQL tables and does not physically exist inside the view itself. You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table

SQL Views Creating a View with CREATE VIEW Think of a view as being a tailored presentation that provides a tabular window into one or more base tables. The window can display an entire base table, part of a base table, or a combination of base tables (or parts thereof). A view also can reflect the data in base tables through other views—windows into windows. Generally, SQL programmers use views to present data to end-users in database applications. Views offer these advantages: Simplified data access. Views hide data complexity and simplify statements, so users can perform operations on a view more easily than on the base tables directly. If you create a complex view— one that involves, say, multiple base tables, joins, and subqueries—users can query this view without having to understand complex relational concepts or even knowing that multiple tables are involved. Automatic updating. When a base table is updated, all views that reference the table reflect the change automatically. If you insert a row representing a new author into the table authors, for example, all views defined over authors will reflect the new author automatically. This scheme saves disk space and prevents redundancy because, without views, the DBMS would have to store derived data to keep it synchronized.

SQL Views Creating a View with CREATE VIEW (CONTINUED) Increased security. One of the most common uses of views is to hide data from users by filtering the underlying tables. Suppose that the table employees contains the columns salary and commission. If you create a view on employees that omits these two columns but contains other innocuous columns (such as _address), the database administrator can grant users permission to see the view but not see the underlying table, thereby hiding compensation data from the curious. Logical data independence. Base tables provide a real view of a database. But when you use SQL to build a database application, you want to present end users not the real view, but a virtual view specific to the application. The virtual view hides the parts of the database (entire tables or specific rows or columns) that aren’t relevant to the application. Thus, users interact with the virtual view, which is derived from—though independent of—the real view presented by the base tables.

SQL Views -- TO CREATE A VIEW CREATE VIEW view [(view_columns)] AS select_statement; view is the name of the view to create. The view name must be unique within the database. view_columns is an optional, parenthesized list of one or more comma-separated names to be used for the columns in view. The number of columns in view_columns must match the number of columns in the SELECT clause of select_statement. (If you name one column this way, you must name them all this way.) If view_columns is omitted, view inherits column names from select_statement. Column names also can be assigned in select_statement via AS clauses. Each column name must be unique within the view. select_statement is a SELECT statement that identifies the columns and rows of the table(s) that the view is based on. select_statement can be arbitrarily complex and use more than one table or other views. An ORDER BY clause usually is prohibited. - - TO CREATE A VIEW CREATE VIEW CurrentBiddersID AS SELECT Bidders.name FROM Bidders WHERE Bidders.BidderID IN (SELECT Bidders.bidderID FROM CurrentBids); - - TO QUERY A VIEW SELECT * FROM CurrentBiddersID

SQL Views When you’re creating a view, some important considerations are: View names follow the same rules that table names do. View names must be unique within a schema (or database). They can’t have the same name as any other table or view. The columns in a view inherit the default column names from the underlying tables. You can give view columns different names by using AS You must specify a new name for a column in a view that would have the same name as another column in the view (usually because the view definition includes a join and the columns from two or more different underlying tables have the same name). A column defined in a view can be a simple column reference, a literal, or an expression that involves calculations or aggregate functions. In some DBMSs, you must specify explicitly the name of a column in a view if the column is derived from an arithmetic expression, a built-in function, or a literal. A view column inherits the data type of the column or expression from which it is derived. You have no practical limit on the number of views that you can create. Generally, you want to create views on subsets of data that are of interest to many users. Almost any valid SELECT statement can define a view, though an ORDER BY clause usually is prohibited.

SQL Views (CONTINUED) You can nest views—that is, a view’s SELECT statement can retrieve data from another view. Nested views eventually must resolve to base tables (otherwise, you’d be viewing nothing) The maximum number of nesting levels varies by DBMS. You can use views as a convenience to save complex queries. By saving a query that performs extensive calculations as a view, you can recalculate each time the view is queried. A view can express a query that you’d otherwise be unable to run. You can define a view that joins a GROUP BY view with a base table, for example, or define a view that joins a UNION view with a base table. A view definition can’t reference itself, because it doesn’t exist yet. Views can display data formatted differently from those in the underlying tables. Unlike a base table, a view does not support constraints. When you define a view by using SELECT *, SQL converts the * to a list of all columns internally. This conversion occurs only once, at view creation (not at execution), so the definition of your view will not change if someone adds a column to an underlying table (by using ALTER TABLE). Because views store no data, the DBMS must execute them every time they’re referenced.

SQL Views: Examples Create a view that hides the authors’ personal information (telephone numbers and addresses). Create a view that lists the authors who live in a city in which a publisher is located. Note that I use the column names au_city and pub_city in the view. Renaming these columns resolves the ambiguity that would arise if both columns inherited the same column name city from the underlying tables.

SQL Views: Examples Create a view that lists total revenue (= price × sales) grouped by book type within publisher. This view will be easy to query later because I name the result of an arithmetic expression explicitly rather than let the DBMS assign a default name.

SQL Views: Examples Create a view that lists the last names of authors A02 and A05, and the books that each one wrote (or cowrote). Note that this statement uses a nested view: It references the view au_names created earlier.

44 NO ICE TODAY ASSIGNMENT 2 Work Day