Greg Riccardi Florida State University. Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements.

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

Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Introduction to Structured Query Language (SQL)
Chapter Information Systems Database Management.
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:
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.
1 Query Languages: How to build or interrogate a relational database Structured Query Language (SQL)
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.
SQL – Part II Yong Choi School of Business CSU, Bakersfield.
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)
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Relational Algebra. Manipulating Databases To access information in a database we use a query Ex: How many customers have the first name = `John’? Good.
Chapter 7: SQL, the Structured Query Language Soid Quintero & Ervi Bongso CS157B.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
Introduction to SQL J.-S. Chou Assistant Professor.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Your Name Here See Page Notes for Info about Hyperlinks.
Rensselaer Polytechnic Institute CSCI-4380 – Database Systems David Goldschmidt, Ph.D.
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
Your name here. Improving Schemas and Normalization What are redundancies and anomalies? What are functional dependencies and how are they related to.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
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.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Copyright © 2003 Addison-Wesley Sree Nilakanta. Copyright © 2003 Addison-Wesley Developing Relational Models What is the relational model and what is.
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.
CIS 375—Web App Dev II SQL. 2 Introduction SQL (Structured _______ Language) is an ANSI standard language for accessing databases.ANSI SQL can execute.
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.
1 COP 4710 Databases Fall, 2000 Today’s Topic Chapter 7: SQL David A. Gaitros October 9th, 2000 Department of Computer Science.
1 Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 7: SQL, the Structured Query Language Instructor’s name and.
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.
CIS 375—Web App Dev II SQL. 2 Introduction SQL (Structured _______ Language) is an ANSI standard language for accessing databases.ANSI SQL can execute.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
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 
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
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)
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
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.
SQL, the Structured Query Language
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CHAPTER 7 DATABASE ACCESS THROUGH WEB
More SQL: Complex Queries,
Chapter 5 Introduction to SQL.
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
Information Systems Database Management
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Contents Preface I Introduction Lesson Objectives I-2
Presentation transcript:

Greg Riccardi Florida State University

Using SQL to Manipulate Database Content and Structure How to create queries in SQL –Simple select statements –Simple join queries –Outer join queries –Queries with multiple relational operators –String pattern matching and ordering results –Expressions, literals, and aggregates –Group by and having clauses –Nested select statements –Set operations How to Modify database content with SQL –Insert statements –Update statements –Delete statements How to Create and manipulate table definitions with SQL –Creating tables and defining attributes –Key and foreign key constraint specifications –Default values, nulls, and constraints –Adding, removing, and modifying attributes –Schemas and user ids –Drop statements SQL statements for bighit online video sales

How to create queries in SQL SQL is a language with –Syntax: the form of statements –Semantics: the meaning of statements This chapter demonstrates syntax –Examples of all types of statements –Shows how each query of Chapter 8 is represented in SQL –Shows additional SQL capabilities This chapter demonstrates semantics –Relates SQL statements to result tables –Shows what each statement means

Simple select statements Select statement in SQL combines many relational operations –select from where select clause –specifies the attributes that go in the results table. from clause –specifies the source tables that the database will access in order to execute the query. where clause –specifies the selection conditions, including the join condition

Examples of Simple Select Statements Examples –Project Customer on lastName, firstName with duplicates select lastName, firstName from Customer –Project Customer on lastName, firstName without duplicates select distinct lastName, firstName from Customer –select from Customer where lastName = ‘Doe’ select * from Customer where lastName = 'Doe' Notice the use of string literals with single quotes –‘Doe’

Simple join queries Example join operation –join Employee and TimeCard where Employee.ssn = TimeCard.ssn Two forms of join –select * from Employee, TimeCard where Employee.ssn = TimeCard.ssn –select * from Employee join TimeCard on Employee.ssn = TimeCard.ssn

Outer Joins Outer joins add rows that have no match –Left join adds all rows from left input table that do not match any row of right table –select * from Employee left outer join TimeCard on Employee.ssn = TimeCard.ssn Employee.SsnlastNameFirstNameTimeCard.ssndatestartTimestoreIdpaidEnd Time UnoJane /14/20028:153no12: UnoJane /16/20028:153no12: ToulouseJie /14/20028:153no12: ThreatAyisha /23/200214:005no22: ThreatAyisha /21/200214:005no22: ThreatAyisha /23/200214:005no22: ThreatAyisha /03/200210:005no14: ThreatAyisha /03/200215:005no19: FortuneJulian FivozinskyBruce

Outer join queries in Access Join properties dialog Left join symbol Left join option

Queries with multiple relational operators Example of SQL statement with 3 joins, projection and selection select lastName, firstName, title, dateRentedProjection from Movie, Video, PreviousRental, CustomerSource tables where Movie.movieId = Video.movieId Join condition and Customer.accountId = PreviousRental.accountId Join condition and Video.videoId = PreviousRental.videoIdJoin condition and dateRented > '2001-dec-1' Selection condition Single SQL statement combines many operations

String pattern matching and ordering results Pattern matching in where clause –select * from Movie where title like '%alligator%' –select * from Movie where title not like 'The %' –select * from Employee where ssn like '___-44-____‘ Ordering results in SQL –select * from Customer order by lastName, firstName –select * from Customer order by accountId desc –select * from Customer order by lastName desc, zipcode asc Ordering is part of SQL –Relational model declares table rows are unordered –SQL and Access treat tables as lists of rows in some order Unordered queries return a list of rows in no particular order –The server can produce rows in any order –Generally produces rows in the order that is easiest or fastest to create

Expressions, literals, and aggregates Expressions and literals in select clause –select lastName, firstName, Employee.ssn, date, (endTime-startTime)*24 as hoursWorked from Employee, TimeCard where Employee.ssn = TimeCard.ssn Creates a table with 5 attributes 5 th attribute of an output row is calculated from the endTime and startTime attributes of the input row –Select lastName, ‘George’ from Emplyee Creates a 2 attribute table with all employees’ last names as first attribute, and literal ‘George’ as second attribute Aggregates: putting many input rows into 1 output row –select count(*) from Rental where accountId = 101 –select count(distinct lastName) from Customer

Aggregating with group by Group by is used to –divide input rows into groups and –Produce one output row per group –select videoId, avg(cost) as averageCost, sum(cost) as totalCost, count(*) as numRentals from PreviousRental group by videoId

Having clause to restrict outputs Having clause selects groups to produce output rows –A group produces an output row only if having condition is true –select title, genre, count(*) as numRentals, avg(cost) as average, sum(cost) as sum from Movie, Video, PreviousRental where Movie.movieId = Video.movieId and Video.videoId = PreviousRental.videoId group by Movie.movieId, title, genre having count(*)>1 A group with count(*) [number of rows in group] <=1 does not produce an output row

Group by and having in access having count(*)>1 group by title average: avg(cost) sum: sum(cost) group by movieId don’t show movieId Total row numRentals: count(*) group by genre

Nested select statements More complex SQL queries may be easier to understand if divided –select * from Customer where accountId in (select accountId from PreviousRental where dateRented >=’dec/1/2001’ and dateRented<’1/1/2002’))) –select * from Customer C where not exists (select * from PreviousRental P where C.accountId = P.accountId)

Nested select in Access nested select statement in text false for not exists

Set operations Set operations in SQL with union Union operation: rentals and previous rentals with marker attribute –(select *, ’Rental’ as sourceTable from Rental) union (select *, ’PreviousRental’ as sourceTable from PreviousRental) Partial result table Rows from Rental Rows from PreviousRental Marker attribute

Set operations Set operations in SQL with intersect and except Intersection operation: videotapes that are rented now, but not for the first time –(select videoId from Rental) intersect (select videoId from PreviousRental) Difference operation: videotapes that currently rented for the first time, and those that have been rented but are not currently rented –(select videoId from Rental) except (select videoId from PreviousRental) –(select videoId from PreviousRental) except (select videoId from Rental)

How to Modify database content with SQL Modify content with insert statements –insert into Customer values (555, 'Yu', 'Jia','540 Magnolia Hall', 'Tallahassee', 'FL', '32306', 0.00) –insert into Customer (firstName, lastName, accountId) values ('Jia', 'Yu', 555) Insert from select statement –insert into Fields of select must match fields of insert in order and type –insert into PayStatement (ssn, hourlyRate, numHours, amountPaid, datePaid) select TimeCard.ssn, hourlyRate, sum((endTime-startTime)*24), sum((endTime-startTime)*24*hourlyRate), today from TimeCard, HourlyEmployee where TimeCard.ssn=HourlyEmployee.ssn and paid = false group by TimeCard.ssn, hourlyRate

Update statements General form of update statement –update set =... where Update to mark every timecard as paid –update TimeCard set paid = true where paid = false Update to give every hourly employee a 10% raise –update HourlyEmployee set hourlyRate = hourlyRate * 1.1 where ssn = ’ ’ Update to give every hourly employee a raise of 10% of the average hourly rate: every gets same amount –update HourlyEmployee set hourlyRate = hourlyRate * (select avg(hourlyRate) from HourlyEmployee)

Delete statements Each delete statement deletes from one table according to some selection clause Delete every row from table –delete from Employee Delete all time cards that have no corresponding hourly employee –delete from Timecard where not exists (select * from HourlyEmployee where TimeCard.ssn = HourlyEmployee.ssn)

How to Create and manipulate table definitions with SQL A create table statement specifies a table name and a list of attributes and constraints for a new table Example with no contraints –create table Customer (accountId int, lastName varchar(32), firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real) Some example attribute types

How to Create and manipulate table definitions with SQL A create table statement specifies a table name and a list of attributes and constraints for a new table Example with no contraints –create table Customer (accountId int, lastName varchar(32), firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real) Add a primary key constraint –create table Customer (accountId int primary key, lastName varchar(32), firstName varchar(32), street varchar(100), city varchar(32), state char(2), zipcode varchar(9), balance real)

Creating tables and defining attributes Add primary key constraint as separate clause –create table Store (storeId int, street varchar(100), city varchar(32), state char(2), zipcode varchar(9), primary key storeId, manager int references Employee) Add primary key constraint as characteristic of attribute –create table Movie (movieId varchar(10) primary key, title varchar(100) unique, genre varchar(32), rating varchar(5), accountId int) Add foreign key constraints –create table Rental (accountId int, videoId varchar(10) unique, dateRented datetime, dateDue datetime, cost real, primary key (accountId, videoId), foreign key (accountId)references Customer(accountId) foreign key (videoId)references Video(videoId))

Default values, nulls, and constraints Creating a table with non-null constraints and default values –create table Video ( videoId varchar(10) primary key, movieId varchar(10) not null references Movie, storeId int references Store default 1 )

Adding, removing, and modifying attributes An alter table statement change the definition of a table Add an attribute with a value –alter table Video add (dateAcquired date = Today) Modify and drop table constraints and drop an attribute –alter table Video modify (storeId not null) drop constraint (primary key videoId) drop (movieId)

Drop statements Drop a table: completely destroys table and all contents –drop table Employee What happens when table contains keys and foreign keys Cascade characteristic tells server to delete all rows of other tables that have foreign keys to the dropped table –drop table Employee cascade Restrict characteristic tells server to block the delete operation if additional rows would have to be deleted –drop table Employee restrict

SQL statements for bighit online video sales See Web site for examples