Reference: W3School -

Similar documents
Reference: W3School -

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

CIS 363 MySQL. Chapter 12 Joins Chapter 13 Subqueries

KORA. RDBMS Concepts II

GIFT Department of Computing Science. CS-217/224: Database Systems. Lab-5 Manual. Displaying Data from Multiple Tables - SQL Joins

Database Foundations. 6-9 Joining Tables Using JOIN. Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Join, Sub queries and set operators

Database Programming with PL/SQL

Retrieving Data from Multiple Tables

ÇALIŞMA TEST SORULARI

Intermediate SQL: Aggregated Data, Joins and Set Operators

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

Database Programming with SQL

Database Programming with SQL

Objectives. After completing this lesson, you should be able to do the following:

Working with Columns, Characters and Rows. Copyright 2008, Oracle. All rights reserved.

Handout 9 CS-605 Spring 18 Page 1 of 8. Handout 9. SQL Select -- Multi Table Queries. Joins and Nested Subqueries.

MTA Database Administrator Fundamentals Course

Introductory SQL SQL Joins: Viewing Relationships Pg 1

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

T-SQL Training: T-SQL for SQL Server for Developers

Simple For each base table and order clause

Database Programming with PL/SQL

Exam code: Exam name: Database Fundamentals. Version 16.0

EXISTS NOT EXISTS WITH

Lab # 6. Data Manipulation Language (DML)

Review -Chapter 4. Review -Chapter 5

Introduction to Database Systems CSE 414. Lecture 3: SQL Basics

Retrieving Data Using the SQL SELECT Statement. Copyright 2004, Oracle. All rights reserved.

Introduction to SQL. From Rob and Coronel (2004), Database Systems: Design, Implementation, and Management

Assignment Grading Rubric

Answer: The tables being joined each have two columns with the same name and compatible data types, and you want to join on both of the columns.

Database Programming - Section 3. Instructor Guide

Querying Data with Transact SQL

Creating Other Schema Objects

Alkérdések II. Copyright 2004, Oracle. All rights reserved.

Introduction to Oracle9i: SQL

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Topics. CSCI 403 Database Management DISTINCT. JOIN Clause 2/4/2019 DISTINCT JOINS. 12 Miscellaneous Topics

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Three types of sub queries are supported in SQL are Scalar, Row and Table sub queries.

DEFAULT Values, MERGE, and Multi-Table Inserts. Copyright 2009, Oracle. All rights reserved.

Bsc (Hons) Software Engineering. Examinations for / Semester 1. Resit Examinations for BSE/15A/FT & BSE/16A/FT

Database Programming with SQL

Item: 1 (Ref:Cert-1Z )

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Databases - Classic Models

CS122 Lecture 5 Winter Term,

School of Computing and Information Technology. Examination Paper Autumn Session 2017

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Mobile MOUSe MTA DATABASE ADMINISTRATOR FUNDAMENTALS ONLINE COURSE OUTLINE

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

WEEK 3 TERADATA EXERCISES GUIDE

RDBMS- Day 4. Grouped results Relational algebra Joins Sub queries. In today s session we will discuss about the concept of sub queries.

Corticon Rule Modeling Challenge Jan 2018 Order Promotions

Cartesian Product and the Join Operations. Copyright 2008, Oracle. All rights reserved.

SQL functions fit into two broad categories: Data definition language Data manipulation language

A subquery is a nested query inserted inside a large query Generally occurs with select, from, where Also known as inner query or inner select,

ORACLE VIEWS ORACLE VIEWS. Techgoeasy.com

Oracle Database 10g: Introduction to SQL

OVERVIEW OF RELATIONAL DATABASES: KEYS

COPYRIGHTED MATERIAL. Databases

12. MS Access Tables, Relationships, and Queries

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Relational Database Development

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

Database Management Systems,

ITCertMaster. Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way!

Instructor: Craig Duckett. Lecture 11: Thursday, May 3 th, Set Operations, Subqueries, Views

Databases and SQL programming overview

Preview. Advanced SQL. In this chapter, you will learn:

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

Writing Analytical Queries for Business Intelligence

HR Database. Sample Output from TechWriter 2007 for Databases

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

Database Programming with SQL

Querying Data with Transact-SQL

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

CS 327E Lecture 2. Shirley Cohen. January 27, 2016

Misc. Triggers Views Roles Sequences - Synonyms. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering

SQL Interview Questions

THE UNIVERSITY OF AUCKLAND

CS W Introduction to Databases Spring Computer Science Department Columbia University

Graphical Joins in More Detail

Slicing and Dicing Data in CF and SQL: Part 2

Sankalchand Patel College of Engineering, Visnagar B.E. Semester III (CE/IT) Database Management System Question Bank / Assignment

Brief History of SQL. Relational Database Management System. Popular Databases

Database Programming with SQL

Data Manipulation Language

A. It executes successfully and displays rows in the descending order of PROMO_CATEGORY.

ETL (Extraction Transformation & Loading) Testing Training Course Content

chapter 2 G ETTING I NFORMATION FROM A TABLE

Joining tables. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

What is SQL? Designed to retrieve data from relational databases, as well as to build and administer those databases.

Oracle Syllabus Course code-r10605 SQL

Teradata SQL Features Overview Version

Transcription:

Language SQL SQL Adv Reference: W3School - http://www.w3schools.com/sql/default.asp http://www.tomjewett.com/dbdesign/dbdesign.php?page=recursive.php Recursive Associations/Relationship A recursive association connects a single table(serving in one role) to itself (serving in another role). Example: In most companies, each employee (except the CEO) is supervised by one manager. Of course, not all employees are managers. This example is used in almost every database textbook, since the association between employees and managers is relatively easy to understand. Perhaps the best way to visualize it is to start with two tables. 1

Recursive Associations/Relationship Incorrect Model The problem with this model is that each manager is also an employee. Building the second (manager) table not only duplicates information from the employee table, it virtually guarantees that there will be mistakes and conflicts in the data. We can fix the problem by eliminating the redundant class and re-drawing the association line. Recursive Associations/Relationship Correct model Normally, we wouldn t show an fk in the class diagram; however, including the manager as an attribute of the employee here (in addition to the association line) can help in understanding the model. In the relation scheme, we can explicitly show the connection between the surrogate pk (employeeid) and the managerid (which is an fk, even though it is in the same scheme). 2

Recursive Associations/Relationship How its looks in a data table Retrieving data from a Recursive Association To produce a list of employees and their managers, we have to join the employees table to itself, using two different aliases for the table name. An outer join is needed to include any employee who is not managed by anyone. SELECT E.lastName AS Employee, M.lastName AS Manager FROM Employees E LEFT OUTER JOIN Employees M ON E.managerID = M.employeeID ORDER BY E.lastName 3

Retrieving data from a Recursive Association In effect, the SQL statement works as if there were two copies of the employees table, as in the first (incorrect) UML diagram. You can visualize rows being joined this way: Disable Foreign Keys To disable all foreign Keys SET FOREIGN_KEY_CHECKS = 0; To enable all foreign Keys SET FOREIGN_KEY_CHECKS = 1; 4

Subqueries Sometimes you don t have enough information available when you design a query to determine which rows you want. In this case, you ll have to find the required information with a subquery. Example: Find the list of buildings that are in Montreal (should use the name Montreal not the Id). We might start writing this query as we would any of the ones that we have already done: SELECT * FROM building WHERE buildingcityid =??; Subqueries We don t know what buildingcityid to put in the WHERE clause. No, we can t look it up manually and type it into the query we have to find the answer based only on the information that we have been given! Fortunately, we also know how to find the cityid by writing another query: SELECT cityid WHERE cityname= 'Montreal'; Notice that this query returns a single column and a single row 5

Subqueries Syntactically, all we have to do is to enclose the subquery in parenthses, in the same place where we would normally use a constant in the WHERE clause. We ll include the cityid in the SELECT line to verify that the answer is what we want: SELECT cityid WHERE cityname= ( SELECT cityid WHERE cityname= Montreal ); Exercises 1. Using a subquery write a query to display all buildings in Montreal ; 2. Using a subquery write a query to display all Buildings in Montreal and Laval ; 3. Using a subquery write a query to display all cities in Canada ; 4. Using a subquery write a query to increase the rent price in 10% for all apartments in Montreal; 6

Answer 1) SELECT * FROM building WHERE buildingcityid=(select cityid WHERE cityname='montreal'); 2) SELECT * FROM building WHERE buildingcityid IN (SELECT cityid WHERE cityname IN ('Montreal, Laval'); 3) SELECT * WHERE citycountryid = (SELECT countryid FROM country WHERE countryname = 'Canada'); Answer 4) UPDATE apartment SET apartmentrentprice = (apartmentrentprice*1.1) WHERE apartmentbuildingid IN (SELECT buildingid FROM buildinginner INNER JOIN city ON (buildingcityid = cityid) WHERE cityname = 'Montreal'); 7

Views A view is simply any SELECT query that has been given a name and saved in the database. For this reason, a view is sometimes called a named query or a stored query. To create a view, you use the SQL syntax: CREATE OR REPLACE VIEW <view_name> AS SELECT <any valid select query>; Views The view query itself is saved in the database, but it is not actually run until it is called with another SELECT statement. For this reason, the view does not take up any disk space for data storage, and it does not create any redundant copies of data that is already stored in the tables that it references The keywords OR REPLACE in the syntax shown above are optional. Although you don t need to use them the first time that you create a view, including them will overwrite an older version of the view with your latest one, without giving you an error message. The syntax to remove a view from your schema is exactly what you would expect: DROP VIEW <view_name> 8

Using Views A view name may be used in exactly the same way as a table name in any SELECT query. Once stored, the view can be used again and again, rather than re-writing the same query many times. The most basic use of a view would be to simply SELECT * from it, but it also might represent a pre-written subquery or a simplified way to write part of a FROM clause. In many systems, views are stored in a pre-compiled form. This might save some execution time for the query, but usually not enough for a human user to notice. One of the most important uses of views is in large multi-user systems, where they make it easy to control access to data for different types of users. As a very simple example, suppose that you have a table of employee information on the scheme Employees = {employeeid, empfname, emplname, empphone, jobtitle, payrate, managerid}. Obviously, you can t let everyone in the company look at all of this information, let alone make changes to it. Your database administrator (DBA) can define roles to represent different groups of users, and then grant membership in one or more roles to any specific user account (schema). In turn, you can grant table-level or view-level permissions to a role as well as to a specific user. Suppose that the DBA has created the roles managers and payroll for people who occupy those positions. In Oracle, there is also a pre-defined role named public, which means every user of the database Exercises 1. Create a view to produce a list with the contract number, tenant name, contract rent price, building address and city name; 2. Using the view that you created before dispaly all datas; 3. Using the view that you created before display all columns for the registers that the contract rent price is bigger than 1000.00 and lower than 1200.00; 9

Answer 1) CREATE VIEW apartlist AS SELECT contractid, contractrentprice, tenantname, buildingaddress, cityname FROM apartment apartment INNER JOIN building building ON apartmentbuildingid = buildingid INNER JOIN contract ON contracapartmentnumber = apartmentnumber AND contracapartmentbuildingid = apartmentbuildingid INNER JOIN tenant tenant ON contractenantid = tenantid INNER JOIN city ON buildingcityid = cityid; 2) SELECT * FROM apartlist; 3) SELECT * FROM apartlist WHERE contractrentprice BETWEEN 1000 AND 1200; 10