Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Ch4 Summary Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University."— Presentation transcript:

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

2 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 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 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 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 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 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 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 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 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 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 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 >’1-6-2004’) );

13 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 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 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 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 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 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 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 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 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. 9764 have been sold –Select Sum(Quantity) As SumQty From OrderItem Where ItemNo=9764

22 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 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 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 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 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 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 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 29 Types of Joins Inner Join Outer Join –Right outer join –Left outer join –Full outer join Cross Join

30 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 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 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 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 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 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 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 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 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 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 40 SQL Syntax Refer to appendix pp.179-181 in textbook for more SQL statements syntax

41 41 End of chapter exercises Answer all end of chapter exercises You can download answers from CS490 Cyberclass http://arabcampus.arabou.org.sa/fall07/mod/res ource/view.php?id=2721 Best of Luck


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

Similar presentations


Ads by Google