1 Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 7: SQL, the Structured Query Language Instructor’s name and.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

1 Constraints, Triggers and Active Databases Chapter 9.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 8-1 David M. Kroenke’s Chapter Eight: Database Redesign Database Processing:
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
Greg Riccardi Florida State University. Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements.
Overview Begin 6:00 Quiz15 mins6:15 Review Table Terms25 mins6:40 Short Break10 mins6:50 SQL: Creating Tables60 mins7:50 Break10 mins8:00 Lab – Creating.
Introduction to Structured Query Language (SQL)
Session 4 SQL Structured Query Language. SQL Modes of use –Interactive –Embedded Purpose –Create database –Create, Read, Update, Delete.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Session 5 SQL 2: how to Modify database content with SQL.
Introduction to Structured Query Language (SQL)
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:
CSE 190: Internet E-Commerce Lecture 10: Data Tier.
SQL Basics Based on the relational algebra we just learned. Nonprocedural language – what to be done not how Simple, powerful language Used for both data.
Copyright © 2003 Addison-Wesley Defining Relational Databases What is an Access database? How do you create an Access database? How do you create and modify.
Your name here The lecture notes are based on using Microsoft Access interactively as part of the lecture.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Murali Mani SQL DDL and Oracle utilities. Murali Mani Datatypes in SQL INT (or) INTEGER FLOAT (or) REAL DECIMAL (n, m) CHAR (n) VARCHAR (n) DATE, TIME.
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
Introduction to Structured Query Language (SQL)
SQL DDL constraints Restrictions on the columns and tables 1SQL DDL Constraints.
Relational Algebra. Manipulating Databases To access information in a database we use a query Ex: How many customers have the first name = `John’? Good.
MySql In Action Step by step method to create your own database.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 2: Representing Information with Data Models The lecture notes.
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
SQL Server 7.0 Maintaining Referential Integrity.
Your name here. Improving Schemas and Normalization What are redundancies and anomalies? What are functional dependencies and how are they related to.
Onsdag The concepts in a relation data model SQL DDL DML.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Relational Database. Database Management System (DBMS)
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
Copyright © 2003 Addison-Wesley Sree Nilakanta. Copyright © 2003 Addison-Wesley Developing Relational Models What is the relational model and what is.
© 2009 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 7 (Part a): Introduction to SQL Modern Database Management 9 th Edition Jeffrey A.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
SQL Structured Query Language 1. Data Definition Language (DDL) is used to manage table and define data structure i.e. CREATE, ALTER, DROP Data Control.
1 COP 4710 Databases Fall, 2000 Today’s Topic Chapter 7: SQL David A. Gaitros October 9th, 2000 Department of Computer Science.
DatabaseDatabase cs453 Lab5 1 Ins.Ebtesam AL-Etowi.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
1 COP 4710 Databases Fall, 2000 Today’s Topic Review for Final Exam David A. Gaitros November 6, 2000 Department of Computer Science Copyright by Dr.
SQL Jan 20,2014. DBMS Stores data as records, tables etc. Accepts data and stores that data for later use Uses query languages for searching, sorting,
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 CS 430 Database Theory Winter 2005 Lecture 10: Introduction to SQL.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
SQL. Originally developed by IBM Standardized in 80’s by ANSI and ISO Language to access relational database and English-like non-procedural Predominant.
Query Processing – Implementing Set Operations and Joins Chap. 19.
Chapter 3: Relational Databases
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)
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
 MySQL  DDL ◦ Create ◦ Alter  DML ◦ Insert ◦ Select ◦ Update ◦ Delete  DDL(again) ◦ Drop ◦ Truncate.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Teacher Workshop Database Design Pearson Education © 2014.
Fundamentals of DBMS Notes-1.
Logical DB Design: ER to Relational
CS580 Advanced Database Topics
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
From ER to Relational Model
Teaching slides Chapter 8.
Structured Query Language
CMPT 354: Database System I
Contents Preface I Introduction Lesson Objectives I-2
Presentation transcript:

1 Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 7: SQL, the Structured Query Language Instructor’s name and information goes here Please see the notes pages for more information.

2 Chapter 7: SQL n Standard Query Language –ANSI and ISO standard –SQL2 or SQL-92 is current standard n SQL is a data manipulation language (DML) and a data definition language (DDL) and a programming language n We can use SQL for –Logical database specification (database schema definitions –Physical database specifications (indexes, etc.) –Querying database contents –Modifying database contents

3 Relational Operations in SQL n Select statement –select from where n Projection in SQL using select clause –Select title from Movies n Selection in SQL using where clause –select * from Customer where lastName = 'Doe' –select distinct lastName, firstName from Customer no duplicates with distinct

4 Products and Joins in SQL n Cartesian product in SQL using from clause –Select * from Employee, Timecard n Join using from and where clauses –Select * from Employee, Timecard where Employee.ssn = Timecard.ssn n Join using join and on (non-standard) –Select * from Employee join TimeCard on Employee.ssn = TimeCard.ssn

5 Nested Queries n Nested select query –Select videoId, dateAcquired from Videotape where videoId in ( select videoId from Rental where dateRented=‘1/1/99’) n compare with –Select v.videoId, dateAcquired from Videotape v, Rental r where v.videoId = r.videoId and dateRented=‘1/1/99’) n Same result?

6 Exists and Unique Queries n find employees who have no time cards –Select firstName, lastName from Employee e where not exists (select * from TimeCard t where e.ssn=t.ssn) n Find managers who have exactly one time card –select firstName, lastName from Employee e where unique (select * from TimeCard t where t.ssn=e.ssn) and exists (select * from Store where ssn=manager)

7 Sets and nulls in where clauses n Names of all stores that do not have managers –select name from Store where manager is null n All employees who work on project 1, 2 or 3 –select distinct fname, lname from employee where pno in (1,2,3)

8 Aggregate functions n How many employees work at Store 3> –select count (*) from WorksAt where storeId=3 n What is the average hourly rate of all hourly employees –select average(hourlyRate) from HourlyEmployees n How many different salaries are there? –select count (distinct salary) from SalariedEmployee n What is the average salary in each store? or How many employees work at each store? –must apply average to the salaries of each group of store employees, or count to each group of store employees!

9 Select Using Group by and Having n Group by forms groups of rows with the same column values n What is the average hourly rate by store? –select storeId, avg(hourlyRate) from HourlyEmployee e, WorksAt w where e.ssn = w.ssn group by stroreId n How many employees work at each store? –select storeId, name, count (*) from Store s, WorksAt w where s.storeId = w.storeId group by storeId, name n Having filters the groups –having count (*)>2

10 Substrings, arithmetic and order n Find a movie with ‘Lion’ in the title –select title from Movie where title like ‘%Lion%’ n List the monthly salaries of salaried employees who work in in store 3 –select salary/12 from Employees e, WorksAt w where e.ssn=w.ssn and storeId=3 n Give the list of employees in store 3, ordered by salary –select firstName, lastName from Employees e, WorksAt w where e.ssn=w.ssn and storeId=3

11 Modifying Content with SQL n Insert queries –insert into Customer values (555, 'Yu', 'Jia','540 Magnolia Hall','Tallahassee', 'FL', '32306') –insert into Customer (firstName, lastName, accountId) values ('Jia', 'Yu', 555) n Update queries –update TimeCard set paid = true where paid = false –update HourlyEmployee set hourlyRate = hourlyRate *1.1 where ssn = ' ' n Samples in Access

12 Creating Pay Statements with SQL n Find the number of hours worked for each employee entry –select TimeCard.ssn, sum((endTime- startTime)*24) as hoursWorked from TimeCard where paid=false group by ssn n Create the Pay Statement entries for each Employee –select ssn, hourlyRate, hoursWorked, hoursWorked * hourlyRate as amountPaid, today from … n Insert into the PayStatement table –Insert into PayStatement select … n Look at the Access example in BigHit.mdb

13 Defining queries for the PayStatement n A view is a named query n create view EmployeeHours as –select TimeCard.ssn, sum((endTime- startTime)*24) as hoursWorked from TimeCard where paid=false group by ssn n create view EmployeePay as –select ssn, hourlyRate, hoursWorked, hoursWorked * hourlyRate as amountPaid, today from EmployeeHours h, HourlyEmployee e where h.ssn=e.ssn n insert into PayStatement select * from EmployeePay

14 Marking TimeCards as paid n update TimeCard set paid = true n update TimeCard set paid=true where paid=false n updateTimeCard set paid=true where ssn in (select ssn from EmployeePay) n What happens if time cards added while pay statements are being created?

15 Delete Statements n Delete all time cards for non-hourly employees –delete from Timecard where not exists (select * from HourlyEmployee where TimeCard.ssn = HourlyEmployee.ssn) n More examples in BigHit Video Access database

16 Create Table Statement n create table Customer ( accountId int, lastName varchar(32), firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9) ) n Note that SQL has specific types

17 Data types in SQL

18 Key Constraints in SQL n Key declarations are part of create table –create table Store ( storeId int primary key, –create table Movie ( movieId varchar(10) primary key, –create table Rental ( accountId int, videoId varchar(10), primary key (accountId, videoId)

19 Referential Integrity Constraints n A relationship is implemented by attributes that reference the primary key of the related table –Enforcing referential integrity requires guaranteeing that there is a referenced object –An attempt to modify the relationship (insert, update or delete) is potential violation n Declare foreign key constraints –create table Store ( manager int references Employee –create table Rental ( foreign key (accountId) references Customer(accountId)

20 Maintaining Referential Integrity n What happens when an update violates referential integrity –update foreign key attribute change catalog id of a video –insert new object add a new video –delete related object delete catalog entry –update primary key attribute change catalog id of a video title n Alternatives –propagate changes –set to null

21 Constraints on Values of Attributes n Not null constraints –create table PreviousRental ( accountId int not null references Customer, videoId int not null references Videotape, dateRented datetime not null, dateReturned datetime, cost real, primary key (accountId, videoId, dateRented)) n Check constraints –check (checkOut < dueDate) –check (answer in (‘T’,’F’)) –check (questionId in (select questionId from questions where quizId=…))

22 Strategies for Enforcing Constraints n Enforce always –Never allow a violation of constraint –Suppose 2 rentals are recorded wrong change the customerId of 2 records –some violation will result n Enforce at end of transaction –Allow violations during updates, but check and enforce at the end of the process n Leads us to consider –Chapter 14 Transactions in SQL –Allow cancellation of updates –Support concurrent access