SQL (Chapter 2: Simple queries; Chapter 7 and 8: Nested and DML queries) Many of the examples in this document are based on the tables in the next slide.

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

Ashley Ohmann June 20, * What is Custom SQL? * What can I do with it? * Join conditions * Unions and Self Joins * Ranks * Derived Tables.
Stored procedures and views You can see definitions for stored procedures and views in the demo databases but you can’t change them. For views, expand.
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
Concepts of Database Management Seventh Edition
Concepts of Database Management Sixth Edition
Concepts of Database Management Seventh Edition
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
A Guide to SQL, Seventh Edition. Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in.
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
A Guide to MySQL 3. 2 Objectives Start MySQL and learn how to use the MySQL Reference Manual Create a database Change (activate) a database Create tables.
Concepts of Database Management Sixth Edition
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Microsoft Access 2010 Chapter 7 Using SQL.
Introduction to SQL J.-S. Chou Assistant Professor.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
ASP.NET Programming with C# and SQL Server First Edition
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
Microsoft Access 2010 Chapter 7 Using SQL. Change the font or font size for SQL queries Create SQL queries Include fields in SQL queries Include simple.
Microsoft Access 2010 Building and Using Queries.
Analyzing Data For Effective Decision Making Chapter 3.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Concepts of Database Management Seventh Edition
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Structured Query Language Chris Nelson CS 157B Spring 2008.
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
 Agenda 2/20/13 o Review quiz, answer questions o Review database design exercises from 2/13 o Create relationships through “Lookup tables” o Discuss.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Intro to SQL Management Studio. Please Be Sure!! Make sure that your access is read only. If it isn’t, you have the potential to change data within your.
A Guide to MySQL 3. 2 Introduction  Structured Query Language (SQL): Popular and widely used language for retrieving and manipulating database data Developed.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Information Building and Retrieval Using MySQL Track 3 : Basic Course in Database.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
An Introduction to SQL For CS Overview of SQL  It is the standard language for relational systems, although imperfect  Supports data definition.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
 CONACT UC:  Magnific training   
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.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
COM621: Advanced Interactive Web Development Lecture 11 MySQL – Data Manipulation Language.
Chapter 12 Introducing Databases. Objectives What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and.
Microsoft Office Illustrated Introductory, Windows Vista Edition
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
Database Systems: Design, Implementation, and Management Tenth Edition
Building and Using Queries
Structured Query Language
CIS16 Application Programming with Visual Basic
Chapter 4 Summary Query.
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
CS4222 Principles of Database System
Contents Preface I Introduction Lesson Objectives I-2
Database Systems: Design, Implementation, and Management Tenth Edition
Microsoft Office Illustrated Introductory, Windows XP Edition
Shelly Cashman: Microsoft Access 2016
Presentation transcript:

SQL (Chapter 2: Simple queries; Chapter 7 and 8: Nested and DML queries) Many of the examples in this document are based on the tables in the next slide. These are similar to the tables in the test database CS451 Supplier. Just about any query involving two tables connected by a many-many relationship will be similar to something from the following slides (adapted from a book by C. J. Date).

S#SNAMESTATUSCITYP#PNAMECOLORWEIGHT S1Smith20LondonP1NutBlue12 S2Jones10ParisP2BoltGreen17 S3Blake30ParisP3ScrewBlue17 S4Clark20LondonP4ScrewRed14 S5Adams30AthensP5CamBlue12 P6CogRed19 S#P#QTY S1P1300 S1P2200 S1P3400 S1P4200 S1P5100 S1P6100 S2P1300 S2P3400 S3P2200 S3P3200 S4P2200 S4P3300 S4P5400 S5P3300 S5P5200 S P

SQL: one or more tables  view or logical table. SQL: Query View: Answer or resulting table

Nice reference at [ Book has numerous examples in Chapter 2. Book also shows how to use SQL in Access, Oracle, and MySQL; just go through them for the SQL examples; we’ll describe how to use SQL in SQL-Server.

General format: Select stuff From table(s) Where conditions stuff can be specific attributes or the character * to indicate all attributes. The result is a list of all rows that satisfy the conditions.

Using SQL Server to see result of SQL commands Using Management Studio, select the desired database Right click on it and select new Query Type your SQL command into the resulting text window Click on the “! Execute” option just above the window’s tab.

Row subsets List all suppliers with a status larger than 20 Select * From S Where status > 20

NOTE: if status is NULL then status > 20; status = 20; and status < 20 are all false!! However, an SQL query could ask whether status is equal to NULL and, if it was, would return True.

Column Subsets combined with row subsets: List the name and status of each London supplier Select Sname, Status From S Where City = ‘London’ (may have to retype the quote marks if copying the above and pasting into SQL Server)

All SQL commands generate a logical table. The table may be displayed immediately or buffered internally depending on the context in which it is used.

Results may contain duplicate rows – it’s time consuming to remove them Select city From S Where status = 40 Can put distinct after the Select to eliminate the duplicate rows.

Compound conditions: List the numbers of Paris suppliers with a status bigger than 20 Select S# From S Where city = ‘Paris’ and Status > 20; Could use OR also

Ordering: List the number and status of Paris suppliers in descending order of status. Select S#, status From S Where city = ‘Paris’ Order by Status Desc Could also use ASC or just leave out.

Aggregates: How many suppliers supply part ‘P2’ Select count(*) From SP Where P# = ‘P2’ If we left out the Where clause, we get a count of ALL entries.

What is the average quantity supplied by ‘P2’ suppliers Select avg(qty) From SP Where P# = ‘P2’ Could use sum, max, min also, among others How can we get the average quantity for all parts?

Group by options Select P#, avg(Qty) From SP Group by P# Gets an average for each P# and display each in table format.

Results of the previous query displays no column name for the avg. Can change this using Select P#, avg(Qty) as 'average Quantity' From SP Group by P# ‘average Quantity’ becomes a column name in the result

Find the supplier with the largest status value Select S# From S Where status = ( Select MAX (Status) from S) This is an example of a nested query – a select within a select.

Having Clause The HAVING clause was added to SQL because the WHERE keyword is limited in its use with aggregate functions. [ ving.asp] ving.asp

SELECT attribute, function(attribute) FROM table WHERE condition GROUP BY attribute HAVING function(attribute) operator value

List suppliers with an average quantity above 200 SELECT S#, avg(qty) as average FROM SP group by S# having avg(qty) >200

List suppliers with above average quantity SELECT S#, avg(qty) as ‘average’ FROM SP group by S# having avg(qty) > (SELECT avg(qty) FROM SP)

Like keyword: allows queries to look for strings similar to (but not equal to) a specified criterion Select stuff from tables where attribute like somestring

Common use similar to that below Select * from S where Sname like 'Ada%‘ % is a wildcard. Looks for any name that starts with ‘Ada’ Can use % prior to or after a string

Can replace ‘%’ with ‘_’ ‘_’ is a wildcard for just ONE character. Select * from S where Sname like 'Ada_‘ Looks for a string that starts with ‘Ada’ and contains just one more character NOTE: different DBMS’s may use different symbols!

Multitable queries: Find the names of suppliers who supply part ‘P2’ Select Sname From S, SP Where S.S# = SP.S# and SP.P# = ‘P2’

How do you negate this? That is: Find the names of suppliers who do NOT supply part ‘P2’.

Nested queries: Select Sname From S Where S# IN ( Select S# From SP Where P# = ‘P2’)

Or Select Sname From S Where EXISTS ( Select * From SP Where S# = S.S# and P# = ‘P2’)

EXISTS is an existential qualifier NOTE: queries involving IN can be converted to queries involving EXISTS but not necessarily vice-versa.

NOTE: In theory there’s no inherent advantage to any of the above nested queries or the previous JOIN-type query. A good optimizer will treat all equally. HOWEVER not all database systems have comparable or good optimizers!! Some report poor performance with nested queries on mySQL [ subquery-restrictions.html] subquery-restrictions.html

Find the names of suppliers who do NOT supply part ‘P2’. You can negate nested queries by using NOT IN or NOT EXISTS

Find the names of suppliers who do NOT supply part ‘P2’. Select Sname From S Where S# Not IN ( Select S# From SP Where P# = ‘P2’)

Select Sname From S Where not EXISTS ( Select * From SP Where S# = S.S# and P# = ‘P2’)

List suppliers who supply at least one red part. Select Sname from S, SP, P where S.S#=SP.S# and SP.P#=P.P# and P.color=‘Red’

Multiple nested queries: List suppliers who supply at least one red part. Select Sname From S Where S# IN ( Select S# from SP where P# IN ( Select P# from P where color = ‘Red’))

Which is better? The former is probably more clear – but maybe not to all. The latter allows variations more easily.

Negating multiple nested queries: NOT prior to first IN: List suppliers who do NOT supply a red part. NOT prior to second IN: List suppliers who supply parts that are NOT red (non- red parts). NOT prior to both: List suppliers who do NOT supply parts that are NOT red i.e. ONLY red parts. NOTE: Two negations do NOT cancel

Select Sname From S Where EXISTS ( Select * from P where color=’Red’ and EXISTS ( Select * from SP where SP.S#=S.S# and P.P#=SP.P#))

Negating multiple nested queries: NOT prior to first EXISTS: List suppliers who do NOT supply a red part. NOT prior to second EXISTS: List suppliers for which there is a red part they don’t supply. NOT prior to both: List suppliers for which there is no red part they do not supply (i.e. supply ALL red parts). NOTE: Two negations do NOT cancel

List supplier names of those who supply all parts: An alternative form is: List supplier names of those for whom there is no part they do not supply.

Select Sname From S Where NOT EXISTS ( Select * from P where NOT EXISTS ( Select * from SP where SP.S# = S.S# and SP.P# = P.P#))

Nested queries and multiple queries on the same table: Find supplier numbers for suppliers who supply at least all those part supplied by S2. NOTE: Nothing outside of SP is needed. Create view Temp as ( Select P# from SP where S# = ‘S2’)

Find numbers of suppliers who supply all parts in temp Select Distinct S# From SP SPX Where NOT EXISTS ( Select * from Temp where NOT EXISTS ( Select * from SP SPY where SPY.S# = SPX.S# and SPY.P# = Temp.P#))

NOTE: if both of the previous SQL commands are in the same SQL Server window, place the word go between then. It’s a syntax thing.

Alternative with NO temp table: Select Distinct S# From SP SPX Where NOT EXISTS ( select * from SP SPY where S# = ‘S2’ and NOT EXISTS ( Select * from SP where S# = SPX.S# and P# = SPY.P#))

This uses aliases SPX and SPY to be able to state conditions related to a specific selection when there is more than one selection on the same table.

Alternative syntax for SQL and join operations A join operation combines two entries from two (or more) tables based on a condition, typically involving the equality of a common attribute from each table. See examples starting on page 261. Sometimes these are called inner joins.

A join or inner join operation concatenates two entries when a common attribute from each has the same value. However consider: select * from S, SP where S.S# = SP.S#

Where is S8? If there is an S8 that supplies NO parts, then S8 is not listed. If there is NO S8 then S8 is not listed. Should these be distinguished? Perhaps with an indication that S8 supplies NO parts if there IS an S8?

If not, what we have is OK. If a distinction is needed, we need an outer join. See author’s note on page 265 for the significance of the difference.

There are two types of outer joins – a left outer join and a right outer join. A left outer join is as follows. Suppose the connecting attribute from the left table matches NONE of the connecting attributes from the right table. Then the entry from the left table is included in the result, with NULLS filling in positions that would have been occupied from a matching entry of the right table

select * from S left outer join SP on S.S# = SP.S# Will show ALL suppliers – even those who supply no parts.

A right outer join is defined analogously

Views You can create a view, which defines the results of a query. The view’s definition is stored in the data dictionary so that you don’t have to reenter the SQL each time you need it. Create view view_name as select statement……..

To create a view in SQL Server Right click on the views folder and select New View. Select the tables or other views you want to include in your view definition. Click the Add button. You can enter the sql in the text area shown or you can use the gui interface to select your attributes and conditions.

See views from the demo databases for examples. You can right click on a view and select Design to see its definition. You just can’t change the view’s definitions

Importing views from other databases You must first download base tables using the instructions from the previous SQL server powerpoint file The next powerpoint file will discuss how to import views using script generation.

A view can be updated ---sometimes Views represent data from underlying base tables. Question: can an update to a view be applied unambiguously to the underlying base table.

In CS451 Supplier you could change the city of a row in the Good Supplier view. Usually cannot update views that contain aggregate functions or distinct clauses or one in which a single row represents several rows in a base table. Example: can’t change the name of an entry in the view aboveaveragesupplier.

SQL DML (Data Manipulation Language): Chapter 7 Can use SQL to insert data into tables, modify data in tables, or remove entries from tables. Some examples follow. This is extremely useful when writing stored procedures (later).

Insert a record into the S table insert into S (S#, Sname, City, Status) values ('S8', 'zyzzy', 'Chicago', 10)

Modify an existing record in the S table Update S set status=40 where S# = 'S8'

Delete an existing record from S delete from S where S# = 'S8'

SQL is also used to create tables The DBMS uses the gui with which you work to generate code. You CAN write your own code to create tables. Right click on a table and select (for example) Script table as  Create to  New Query Editor Window