SQL. Solutions to Practice Exercises

Similar documents
Introduction to SQL C H A P T E R3. Exercises

Exercises. a. Find the total number of people who owned cars that were involved in accidents

Figure 4.12.Insurancedatabase.

Intermediate SQL C H A P T E R4. Practice Exercises. 4.1 Write the following queries in SQL:

Exercise 1: Relational Model

Relational Algebra. Query Languages Review. Operators. Select (σ), Project (π), Union ( ), Difference (-), Join: Natural (*) and Theta ( )

Answer Key. UNIVERSITY OF CALIFORNIA College of Engineering Department of EECS, Computer Science Division

1 Structured Query Language: Again. 2 Joining Tables

Introduction to SQL ( )

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

SQL Nested & Complex Queries. CS 377: Database Systems

Query-by-Example (QBE)

CHAPTER 8: SQL-99: SCHEMA DEFINITION, BASIC CONSTRAINTS, AND QUERIES

Information Systems SQL. Nikolaj Popov

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Lecture 6. SQL, Logical DB Design

Chapter 13: Query Optimization

Simple SQL Queries (3)

Join Example. Join Example Cart Prod Comprehensive Consulting Solutions, Inc.All rights reserved.

Comp 5311 Database Management Systems. 3. Structured Query Language 1

Introduction to database design

In this Lecture SQL SELECT. Example Tables. SQL SELECT Overview. WHERE Clauses. DISTINCT and ALL SQL SELECT. For more information

Define terms Write single and multiple table SQL queries Write noncorrelated and correlated subqueries Define and use three types of joins

Effective Use of SQL in SAS Programming

Advanced SQL. Lecture 3. Outline. Unions, intersections, differences Subqueries, Aggregations, NULLs Modifying databases, Indexes, Views

Structured Query Language (SQL)

Using SQL Queries to Insert, Update, Delete, and View Data: Joining Multiple Tables. Lesson C Objectives. Joining Multiple Tables

A basic create statement for a simple student table would look like the following.

There are five fields or columns, with names and types as shown above.

Introduction to Microsoft Jet SQL

Chapter 14: Query Optimization

SQL: QUERIES, CONSTRAINTS, TRIGGERS

Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views

SQL Query Evaluation. Winter Lecture 23

Where? Originating Table Employees Departments

Part 4: Database Language - SQL

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

Chapter 5. SQL: Queries, Constraints, Triggers

The Structured Query Language. De facto standard used to interact with relational DB management systems Two major branches

Review: Participation Constraints

New York University Computer Science Department Courant Institute of Mathematical Sciences

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

1.204 Lecture 3. SQL: Basics, Joins SQL

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

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

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3

SQL: Queries, Programming, Triggers

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

Advance DBMS. Structured Query Language (SQL)

SQL: Queries, Programming, Triggers

Chapter 6: Integrity Constraints

Lecture 4: More SQL and Relational Algebra

AN INTRODUCTION TO THE SQL PROCEDURE Chris Yindra, C. Y. Associates

Relational Databases

Databases 2011 The Relational Model and SQL

Unit 10: Microsoft Access Queries

Relationele Databases 2002/2003

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

CS 338 Join, Aggregate and Group SQL Queries

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

CSC 443 Data Base Management Systems. Basic SQL

Week 4 & 5: SQL. SQL as a Query Language

Chapter 1 Overview of the SQL Procedure

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

CIS 631 Database Management Systems Sample Final Exam

CS143 Notes: Views & Authorization

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

Advanced SQL - Subqueries and Complex Joins

Objectives of SQL. Terminology for Relational Model. Introduction to SQL

Microsoft Access Lesson 5: Structured Query Language (SQL)

Temporal Features in SQL standard

Oracle Database: SQL and PL/SQL Fundamentals

Database Security. The Need for Database Security

Data Structure: Relational Model. Programming Interface: JDBC/ODBC. SQL Queries: The Basic From

VARRAY AND NESTED TABLE

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Theory of Relational Database Design and Normalization

IT2305 Database Systems I (Compulsory)

Chapter 10 Functional Dependencies and Normalization for Relational Databases

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Relational Database: Additional Operations on Relations; SQL

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Oracle SQL. Course Summary. Duration. Objectives

Oracle Database: SQL and PL/SQL Fundamentals

The SQL Query Language. Creating Relations in SQL. Referential Integrity in SQL. Basic SQL Query. Primary and Candidate Keys in SQL

Writing Control Structures

Outline. SAS-seminar Proc SQL, the pass-through facility. What is SQL? What is a database? What is Proc SQL? What is SQL and what is a database

Introduction to Structured Query Language

Relational Database Design

The process of database development. Logical model: relational DBMS. Relation

Introduction to tuple calculus Tore Risch

WRITING EFFICIENT SQL. By Selene Bainum

3. Relational Model and Relational Algebra

Transcription:

C H A P T E R 3 SQL Solutions to Practice Exercises 3.1 Note: The participated relation relates drivers, cars, and accidents. a. Note: this is not the same as the total number of accidents in 1989. We must count people with several accidents only once. select count (distinct name) from accident, participated, person where accident.report number = participated.report number and participated.driver id = person.driver id and date between date 1989-00-00 and date 1989-12-31 b. We assume the driver was Jones, although it could be someone else. Also, we assume Jones owns one Toyota. First we must find the license of the given car. Thenthe participated andaccident relations must be updated in order to both record the accident and tie it to the given car. We assume values Berkeley for location, 2001-09-01 for date and date, 4007 for report number and 3000 for damage amount. insert into accident values (4007, 2001-09-01, Berkeley ) insert into participated select o.driver id, c.license, 4007, 3000 from person p, owns o, car c where p.name = Jones and p.driver id = o.driver id and o.license = c.license and c.model = Toyota c. Since model is not a key of the car relation, we can either assume that only one of John Smith s cars is a Mazda, or delete all of John Smith s Mazdas (the query is the same). Again assume name is a key for person. 5

6 Chapter 3 SQL delete car where model = Mazda and license in (select license from person p, owns o where p.name = John Smith and p.driver id = o.driver id) Note: The owns, accident and participated records associated with the Mazda still exist. 3.2 a. Query: select e.employee name, city from employee e, works w where w.company name = First Bank Corporation and w.employee name = e.employee name b. If people may work for several companies, the following solution will only list those who earn more than $10,000 per annum from First Bank Corporation alone. select * from employee where employee name in ( where company name = First Bank Corporation and salary 10000) As in the solution to the previous query, we can use a join to solve this one also. c. The following solution assumes that all people work for exactly one company. where company name First Bank Corporation If one allows people to appear in the database (e.g. in employee) butnot appear in works, or if people may have jobs with more than one company, the solution is slightly more complicated. from employee where employee name not in ( where company name = First Bank Corporation ) d. The following solution assumes that all people work for at most one company.

Exercises 7 where salary > all (select salary where company name = Small Bank Corporation ) If people may work for several companies and we wish to consider the total earnings of each person, the problem is more complex. It can be solved by using a nested subquery, but we illustrate below how to solve it using the with clause. with emp total salary as (, sum(salary) as total salary group by employee name ) from emp total salary where total salary > all (select total salary from emp total salary, works where works.company name = Small Bank Corporation and emp total salary.employee name = works.employee name ) e. The simplest solution uses the contains comparison which was included in the original System R Sequel language but is not present in the subsequent SQL versions. select T.company name from company T where (select R.city from company R where R.company name = T.company name) contains (select S.city from company S where S.company name = Small Bank Corporation ) Below is a solution using standard SQL.

8 Chapter 3 SQL f. Query: g. Query: select S.company name from company S where not exists ((select city from company where company name = Small Bank Corporation ) except (select city from company T where S.company name = T.company name)) select company name group by company name having count (distinct employee name) >= all (select count (distinct employee name) group by company name) select company name group by company name having avg (salary) > (select avg (salary) where company name = First Bank Corporation ) 3.3 a. The solution assumes that each person has only one tuple in the employee relation. b. Query: update employee set city = Newton where person name = Jones

Exercises 9 update works T set T.salary = T.salary * 1.03 where T.employee name in (select manager name from manages) and T.salary * 1.1 > 100000 and T.company name = First Bank Corporation update works T set T.salary = T.salary * 1.1 where T.employee name in (select manager name from manages) and T.salary * 1.1 <= 100000 and T.company name = First Bank Corporation 3.4 Query: SQL-92 provides a case operation (see Exercise 3.5), using which we give a more concise solution: update works T set T.salary = T.salary (case when (T.salary 1.1 > 100000) then 1.03 else 1.1 ) where T.employee name in (select manager name from manages) and T.company name = First Bank Corporation select coalesce(a.name, b.name) as name, coalesce(a.address, b.address) as address, a.title, b.salary from a full outer join b on a.name = b.name and a.address = b.address 3.5 We use the case operation provided by SQL-92: a. To display the grade for each student: select student id, (case when score < 40 then F, when score < 60 then C, when score < 80 then B, else A end) as grade from marks

10 Chapter 3 SQL b. To find the number of students with each grade we use the following query, where grades is the result of the query given as the solution to part 0.a. select grade, count(student id) from grades group by grade 3.6 The query selects those values of p.a1 that are equal to some value of r1.a1 or r2.a1 if and only if both r1 and r2 are non-empty. If one or both of r1 and r2 are empty, the cartesian product of p, r1 and r2 is empty, hence the result of the query is empty. Of course if p itself is empty, the result is as expected, i.e. empty. 3.7 To insert the tuple ( Johnson, 1900) into the view loan info, wecandothefollowing: borrower ( Johnson, k ) borrower loan ( k,, 1900) loan such that k is a new marked null not already existing in the database.