1 Ch4 Summary Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University.

Slides:



Advertisements
Similar presentations
Concepts of Database Management Sixth Edition
Advertisements

5 Chapter 5 Structured Query Language (SQL2) Revision.
Introduction to Structured Query Language (SQL)
1 SQL-Structured Query Language SQL is the most common language used for creating and querying relational databases. Many users can access a database applications.
Structured Query Language Part I Chapter Three CIS 218.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Jerry Post Copyright © Database Management Systems Chapter 4 Queries.
Concepts of Database Management, Fifth Edition
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
Chapter 4 Querying Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of Business 3500 DBMS Bob Travica.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
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
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
1 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Queries: Part 2 of 2 IS240 – DBMS Lecture # 7 – M. E. Kabay, PhD, CISSP-ISSMP.
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.
1/18/00CSE 711 data mining1 What is SQL? Query language for structural databases (esp. RDB) Structured Query Language Originated from Sequel 2 by Chamberlin.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
1 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Queries: Part 1 of 2 IS240 – DBMS Lecture # 6 – M. E. Kabay, PhD, CISSP-ISSMP.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
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.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
Fundamentals of DBMS Notes-1.
CHAPTER 7 DATABASE ACCESS THROUGH WEB
Retrieving Data Using the SQL SELECT Statement
SQL Query Getting to the data ……..
CS3220 Web and Internet Programming More SQL
Queries: Part 1 of 2 IS240 – DBMS Lecture # 6 –
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Relational Database Design
Writing Basic SQL SELECT Statements
M. E. Kabay, PhD, CISSP-ISSMP V:
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
Advanced Queries in MS Access
The Database Exercises Fall, 2009.
Structured Query Language – The Basics
Writing Basic SQL SELECT Statements
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Chapter 7 Introduction to Structured Query Language (SQL)
CS4222 Principles of Database System
Structured Query Language – The Fundamentals
M1G Introduction to Database Development
CSC 453 Database Systems Lecture
Manipulating Data Lesson 3.
Shelly Cashman: Microsoft Access 2016
Presentation transcript:

1 Ch4 Summary Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University

2 SQL in Brief SQL is a query system (ask questions, get answers system) SQL is the standard ask questions, get answers for Database management systems SQL means Structured Query Language SQL was established through ISO SQL is updated every few years Current versions : SQL-99 or SQL-92

3 QBE (query by example) QBE is a visual tool for selecting items from lists instead of typing statements to get results results In ACCESS QBE is called Filter

4 Link Queries to Ch3 normalization CH3 shows how to split data into tables to be stored efficiently (Normalization) CH4 Queries put the tables back together to get results & produce reports Example (colors refer to each table): StudentsInfo(StID, SName, SDOB, SMobile) “table” CoursesInfo(CID, CName, CFee, CHours) “table” Registeration(StID, CID, RegDate, RegNo.) “table” RegQuery(RegNo., StID, SName, SMobile, CID, CName, CFee, CHours, RegDate) “query on 3 tables”

5 Three Tasks of a Query Language DDL : Data Definition Language (Chapter 5) –Alter –Create –Drop, etc… DML : Data Manipulation Language (Chapter 5) –Delete –Insert –Update, etc… Retrieve data : SELECT (Chapter 4)

6 Select Statement SELECT command is used to retrieve specified columns of data for rows that meet some criteria Example : SELECT Category, AnimalID, Name FROM Animal WHERE (Category="reptile"); Query result

7 Query Basics 1.Queries on single table 2.Queries with constraints 3.Queries with computations 4.Queries with aggregation 5.Groups and subtotals 6.Queries on more than one table 7.Table Alias, Create View

8 Complete form of SELECT Statement SELECT Columns What do you want to see FROM Tables What tables are involved JOIN Keys How are the tables joined WHERE Criteria What are the constraints GROUP BY Columns How you want the data grouped HAVING Criteria Condition on the group Order BY Columns Sorting the results

9 1. Queries on single table Ex1: SELECT Name, ListPrice, AnimalID FROM Animal; Result: 1.Note that columns names don’t have to be in the same order they are in inside the table, you can put Name before AnimalID, bring ListPrice in the middle 2.The same statement can be written with table name before columns: Select Animal.Name, Animal.ListPrice, Animal.AnimalID From Animal; 3. Statement must end with semi-colon ;

10 1. Queries on single table Ex2: SELECT Name, ListPrice, AnimalID FROM Animal Order By Name; Result: 1.Note that sorting the records can be on more than one column, the column listed first will be sorted first, e.g. Order by Name, ListPrice 2. Order is Ascending by default (a  z). If you want to sort records descending (z  a), change the statement to : Order by Name DESC; A Z 

11 1. Queries on single table Ex3: SELECT DISTINCT Color FROM Animal; Result: 1.Use DISTINCT to prevent duplicates in columns with repeating information, e.g. Category, Registered, Genre

12 2. Queries with constraints Ex4: Criteria List all dogs with yellow in their color born after 1/6/04 1.Underline all required criteria 2.Identify where is the information found (which column) 3.Are all information to be TRUE at the same time (AND), or some might be FALSE(OR) 4.If you think that writing each criteria on one line is easier, you can do that, it is doesn’t make a difference Category ColorDateBorn SELECT Category, Color, DateBorn FROM Animal Where ( (Category=‘dog’) And (Color like ‘%yellow%’) And (Dateborn >’ ’) );

13 ‘ – % - _- When to use each ‘Character strings’ and ‘date values’ are enclosed in single quotation marks. To match any number of unknown characters, use LIKE ‘J%’ will get : Jones, Jane, Jennifer, etc. Note that %j will get : Areej, Borj. To match one unknown character only, use underscore LIKE ‘J_ne’ will get : Jone, Jane only Numbers are written without anything

14 Evaluating Multiple Clauses It is important to understand how multiple clauses are going to be evaluated in order to get the required results. DBMS uses Boolean algebra to evaluate conditions that consist of multiple clauses The clauses are connected by : AND, OR, NOT Each individual clause is either : TRUE or FALSE

15 Examples on 2 Clauses Yellow fish: must be color=‘yellow’ AND category=‘fish’. (color =‘yellow’ is clause 1, category=‘fish’ is clause 2, AND operator) The above condition can be true only if both of the clauses 1 and 2 are true. (only yellow fish) Yellow or fish: must be color=‘yellow’ OR category=‘fish’. (color =‘yellow’ is clause 1, category=‘fish’ is clause 2, OR operator) The above condition can be true as long as any of clauses 1 or 2 are true. (all fish any color, all yellow animals even if they are not fish)

16 More clauses with AND, OR In this situation the resulting truth value depends on the order in which the clauses are evaluated You should always use parentheses to specify the desired order Innermost parentheses are evaluated first If you don’t use parentheses, the operators are evaluated from left to right

17 DeMorgan’s Law : Negating Conditions To negate a condition with AND, OR operator, you : –Negate each clause –Switch the connector Example :“A cat that is not registered or that has red in its hair” NOT((Registered is NOT NULL) OR (Color LIKE %red%)) Using DeMorgan’s Law : (Registered is NULL) AND NOT (Color LIKE %red%) NOT NOT = isOR switched to ANDNOT added to Color

18 Comparison Operators ComparisonsExamples Operators, <>, BETWEEN, LIKE, IN NumbersAccountBalance > 200 Text Simple Pattern match one Pattern match any Name > ‘Jones’ License LIKE ‘A_ _82_’ Name LIKE ‘J%’ DatesSaleDate BETWEEN ’15-Aug-2004’ AND ’31-Aug-2004’ Missing DataCity IS NULL NegationName IS NOT NULL SetsCategory IN (‘Cat’, ‘Dog’, ‘Hamster’)

19 3. Queries with computations Basic Arithmetic Operators are used: on numeric data to automate basic tasks to reduce amount of data storage Important: Computations are performed for each row in the query Example: Select OrderID, ItemID, UnitPrice, Quantity, UnitPrice*Quantity AS Total computationnew column to show result

20 4. Queries with aggregations Common Aggregation Functions are used: to compute totals, subtotals, counts, averages, etc.. Common functions : sum, avg, min, max, count Important: Aggregations operate across several rows of data and return ONE value Example: Select avg(UnitPrice) AS AveragePrice Aggregated column * Note that UnitPrice will not be displayed new column to show result as ONE value

21 Count vs. Sum Count simply counts the number of rows –E.g. How many employees does Sally have? –Select Count(*) From Employee Sum totals the value in a numeric column –E.g. How many units of Item no have been sold –Select Sum(Quantity) As SumQty From OrderItem Where ItemNo=9764

22 Combining Computations & Aggregations In many cases you will combine row-by-row computations with an aggregate function E.g. OrderItem(PONumber, ItemID, Quantity, Cost) What is the Total Value of order no. 22? First you have to get the value of each row : Quantity*Cost Use SUM to get total value of order Select Sum(Quantity*Cost) As OrderTotal From OrderItem Where PONumber=22;

23 Important points on aggregation You cannot display detail lines (row by row) at the same time you display totals since aggregation groups data into ONE result only. You can compute several aggregation functions at the same time, e.g. SELECT Sum(Quantity), Avg(Quantity), Count(Quantity) From OrderItem; You can use Count with Distinct Operator to count the number of different categories for example and ignore duplicates SELECT COUNT (DISTINCT Category) From Animal;

24 5. Group By and Subtotals The Group By statement can be used ONLY with one of the aggregate functions (sum, avg, count, max, etc..) Note that Group By can only be used on columns with duplicate data, otherwise it will not have any effect. E.g. –Use group by with : Category, Color, Gender –Don’t use group by with : AnimalID, Name

25 Conditions on Totals (HAVING) The HAVING clause is a condition that applies to the GROUP BY output –E.g. Count the animals in each category listing it only when count is greater than 10 SELECT Category, Count(AnimalID) AS CA From Animal Group By Category Having Count(AnimalID) >10; Condition on the group by result

26 Where vs. Having WHERE statement applies to every single row in the original table HAVING statement applies only to subtotal output from a Group By query. Where and Having can be combined in one SELECT statement E.g. Calculate average ListPrice of fish or dog category, and display the result only when greater than 100$ SELECT Avg(ListPrice) AS AveragePrice FROM Animal WHERE (Category="fish“) OR (Category="dog") GROUP BY Category HAVING (Avg(ListPrice))>100; Result after WHERE Result after HAVING

27 6. Queries on Multiple Tables Sale SaleID SaleDate EmployeeID CustomerID SalesTax Sale table lists all Sale details, but if you would like to see the customers’ names instead of their IDs only, you will need to get the information from Customer Table Customer CustomerID FirstName LastName Phone Address ZipCode CityID In SQL, tables are connected with the JOIN statement. Joining tables causes the rows to be matched based on the columns in the JOIN statement. You can then use data from either table. To create a join you must: 1. Specify the tables involved in the join 2. Specify which columns contain matching data

28 Joining many tables A query can use data from several different tables Each table you add must be joined to one other table through a data column If you cannot find a common column, either the normalization is wrong or you need to find a third table that contains links to both tables Joining tables is closely related to data normalization. Normalization splits data into tables that can be stored and searched efficiently Joins do the reverse, it combines data from tables Columns used in joins are often key columns, but you can join tables on any column Joined columns may have different names Joined columns must contain the SAME type of data

29 Types of Joins Inner Join Outer Join –Right outer join –Left outer join –Full outer join Cross Join

30 Inner Joins : Displays only matching rows from the two tables based on the specified columns Null values are not included Example: SELECT AnimalOrderItem.AnimalID, Animal.DateBorn FROM Animal INNER JOIN AnimalOrderItem ON Animal.AnimalID = AnimalOrderItem.AnimalID ;

31 Outer Joins : Right outer Join Displays matching rows from joined tables based on the specified columns, PLUS all rows on the RIGHT side of the join Example: SELECT Sale.EmployeeID, Employee.LastName, Employee.FirstName FROM Employee RIGHT OUTER JOIN Sale ON Employee.EmployeeID = Sale.EmployeeID

32 Outer Joins : Left outer Join Displays matching rows from joined tables based on the specified columns, PLUS all rows on the LEFT side of the join Example SELECT Sale.EmployeeID, Employee.LastName, Employee.FirstName FROM Employee LEFT OUTER JOIN Sale ON Employee.EmployeeID = Sale.EmployeeID

33 Outer Joins : Full outer Join Displays matching rows from joined classes based on the specified attribute, PLUS ALL OTHER rows from both classes Example SELECT Sale.EmployeeID, Employee.LastName, Employee.FirstName FROM Employee FULL OUTER JOIN Sale ON Employee.EmployeeID = Sale.EmployeeID

34 Cross Joins Where every row in one table is paired with every row in the other table Example SELECT * FROM Animals CROSS JOIN Sale

35 7. Table Alias One of the reasons to use table Alias is the need to create a join between multiple tables. Example: Table City is joined to table Employee ON CityID Table City is joined to table Supplier ON CityID To put this in a single Select Statement you need to name City as City2, so you have multiple instances of the same table

36 Example SELECT Supplier.SID, Supplier.CityID, City.City, Employee.EID, Employee.LastName, Employee.CityID, City2.City FROM (City INNER JOIN Supplier ON City.CityID = Supplier.CityID) INNER JOIN ((City AS City2 INNER JOIN Employee ON City2.CityID = Employee.CityID) INNER JOIN AnimalOrder ON Employee.EmployeeID = AnimalOrder.EmployeeID) ON Supplier.SupplierID = AnimalOrder.SupplierID; EmployeeID LastName ZipCode CityID Employee CityID ZipCode City State City2 SupplierID Address ZipCode CityID Supplier CityID ZipCode City State City OrderDate SupplierID ShippingCost EmployeeID AnimalOrder

37 Create View Views are saved queries that can be run at any time They improve performance because they are entered only once DBMS analyzes Views only once Use views to display some of the data and hide another The most powerful feature of a view is that it can be used within another query If the view will only be used to view data, there is usually no difficulties, but if the view is going to be used to update data, you must be careful.

38 Create View & use View in query CREATE VIEW Kittens AS SELECT * FROM Animal WHERE (Category = ‘Cat’) AND (Today - DateBorn < 180); New query using saved Kitten View SELECT Avg(ListPrice) FROM Kittens WHERE (Color LIKE ‘%Black%’);

39 Updatable & non-updatable views To ensure that a view can be updated, it must be designed to change data in only ONE table Never include primary key columns from more than one table in a view. To remain updatable, a view cannot use : –DISTINCT Keyword –Contain Group By –Contain Having By keeping views updatable, you may never need to use the underlying raw table

40 SQL Syntax Refer to appendix pp in textbook for more SQL statements syntax

41 End of chapter exercises Answer all end of chapter exercises You can download answers from CS490 Cyberclass ource/view.php?id=2721 Best of Luck