Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2007 by Prentice Hall 1 Chapter 7: Introduction to SQL SELECT Statement Modern Database Management 8 th Edition Jeffrey A. Hoffer, Mary B. Prescott,

Similar presentations


Presentation on theme: "© 2007 by Prentice Hall 1 Chapter 7: Introduction to SQL SELECT Statement Modern Database Management 8 th Edition Jeffrey A. Hoffer, Mary B. Prescott,"— Presentation transcript:

1 © 2007 by Prentice Hall 1 Chapter 7: Introduction to SQL SELECT Statement Modern Database Management 8 th Edition Jeffrey A. Hoffer, Mary B. Prescott, Fred R. McFadden

2 Chapter 7 © 2007 by Prentice Hall 2 SELECT Statement Used for queries on single or multiple tables Used for queries on single or multiple tables Clauses of the SELECT statement: Clauses of the SELECT statement: SELECT SELECT List the columns (and expressions) that should be returned from the query List the columns (and expressions) that should be returned from the query FROM FROM Indicate the table(s) or view(s) from which data will be obtained Indicate the table(s) or view(s) from which data will be obtained WHERE WHERE Indicate the conditions under which a row will be included in the result Indicate the conditions under which a row will be included in the result GROUP BY GROUP BY Indicate categorization of results Indicate categorization of results HAVING HAVING Indicate the conditions under which a category (group) will be included Indicate the conditions under which a category (group) will be included ORDER BY ORDER BY Sorts the result according to specified criteria Sorts the result according to specified criteria

3 Chapter 7 © 2007 by Prentice Hall 3 Figure 7-10 SQL statement processing order (adapted from van der Lans, p.100)

4 Chapter 7 © 2007 by Prentice Hall 4 SELECT Example Find products with standard price less than $275 Find products with standard price less than $275 SELECT PRODUCT_NAME, STANDARD_PRICE FROM PRODUCT_V WHERE STANDARD_PRICE < 275; Table 7-3: Comparison Operators in SQL

5 Chapter 7 © 2007 by Prentice Hall 5 SELECT Example Using Alias Alias is an alternative column or table name Alias is an alternative column or table name SELECT CUST.CUSTOMER AS NAME, CUST.CUSTOMER_ADDRESS FROM CUSTOMER_V CUST WHERE NAME = ‘Home Furnishings’;

6 Chapter 7 © 2007 by Prentice Hall 6 SELECT Example Using a Function Using the COUNT aggregate function to find totals Using the COUNT aggregate function to find totals SELECT COUNT(*) FROM ORDER_LINE_V WHERE ORDER_ID = 1004; Note: with aggregate functions you can’t have single-valued columns included in the SELECT clause

7 Chapter 7 © 2007 by Prentice Hall 7 SELECT Example–Boolean Operators AND, OR, and NOT Operators for customizing conditions in WHERE clause AND, OR, and NOT Operators for customizing conditions in WHERE clause SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE FROM PRODUCT_V WHERE (PRODUCT_DESCRIPTION LIKE ‘%Desk’ OR PRODUCT_DESCRIPTION LIKE ‘%Table’) AND UNIT_PRICE > 300; Note: the LIKE operator allows you to compare strings using wildcards. For example, the % wildcard in ‘%Desk’ indicates that all strings that have any number of characters preceding the word “Desk” will be allowed

8 Chapter 7 © 2007 by Prentice Hall 8 Venn Diagram from Previous Query

9 Chapter 7 © 2007 by Prentice Hall 9 SELECT Example – Sorting Results with the ORDER BY Clause Sort the results first by STATE, and within a state by CUSTOMER_NAME Sort the results first by STATE, and within a state by CUSTOMER_NAME SELECT CUSTOMER_NAME, CITY, STATE FROM CUSTOMER_V WHERE STATE IN (‘FL’, ‘TX’, ‘CA’, ‘HI’) ORDER BY STATE, CUSTOMER_NAME; Note: the IN operator in this example allows you to include rows whose STATE value is either FL, TX, CA, or HI. It is more efficient than separate OR conditions

10 Chapter 7 © 2007 by Prentice Hall 10 SELECT Example– Categorizing Results Using the GROUP BY Clause For use with aggregate functions For use with aggregate functions Scalar aggregate: single value returned from SQL query with aggregate function Scalar aggregate: single value returned from SQL query with aggregate function Vector aggregate: multiple values returned from SQL query with aggregate function (via GROUP BY) Vector aggregate: multiple values returned from SQL query with aggregate function (via GROUP BY) SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE) FROM CUSTOMER_V GROUP BY CUSTOMER_STATE; Note: you can use single-value fields with aggregate functions if they are included in the GROUP BY clause

11 Chapter 7 © 2007 by Prentice Hall 11 SELECT Example– Qualifying Results by Categories Using the HAVING Clause For use with GROUP BY For use with GROUP BY SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE) FROM CUSTOMER_V GROUP BY CUSTOMER_STATE HAVING COUNT(CUSTOMER_STATE) > 1; Like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those groups with total numbers greater than 1 will be included in final result Here, only those groups with total numbers greater than 1 will be included in final result

12 تعليمات SQL SQL Statement SELECT

13 Chapter 7 © 2007 by Prentice Hall الشكل العام لتعليمة SELECT SELECT[DISTINCT] ColumnName(s) FROM Table(s) FROM Table(s) [WHERECondition] [WHERECondition] [GROUPBY ColumnName(s)] [GROUPBY ColumnName(s)] [HAVINGCondition] [HAVINGCondition] [ORDERBY ColumnName(s)] ; [ORDERBY ColumnName(s)] ;

14 Chapter 7 © 2007 by Prentice Hall اختيار أعمدة محددة من جدول اختيار كل أعمدة جدول (*) مثال1: عرض أرقام وأسماء جميع البرامج التدريبية المتاحة SELECT CRS#, CTITLE FROM COURSE ; FROM COURSE ; مثال2: عرض تفاصيل جميع البرامج التدريبية المتاحة SELECT * FROM COURSE ; FROM COURSE ;

15 Chapter 7 © 2007 by Prentice Hall حذف الصفوف المتكررة - DISTINCT مثـال 3 : عرض أسماء أماكن تنفيذ الدورات التدريبية مع حذف الصفوف المتكررة من النتيجة مثـال 3 : عرض أسماء أماكن تنفيذ الدورات التدريبية مع حذف الصفوف المتكررة من النتيجة SELECTDISTINCT LOCATION FROMOFFER ;

16 Chapter 7 © 2007 by Prentice Hall الاسترجـاع المشروط Conditional Retrieval عبارة WHERE SELECT... FROM... FROM... WHERE [ NOT ] ColumnName WHERE [ NOT ] ColumnName ComparisonOperator Literal ComparisonOperator Literal عوامل المقارنة Comparison Operators عوامل المقارنة Comparison Operators = تساوي<> لا يساوي لا يساوي< أكبر من = أقل من => أقل من أو يساوي

17 Chapter 7 © 2007 by Prentice Hall الاسترجـاع المشروط Conditional Retrieval عبارة WHERE مثال 1: أسماء الموظفين الذين يعملون في القاهرة SELECT FNAME, LNAME FROMEMP WHERE LOCATION = ‘Cairo’ ; مثال 2: أسماء الموظفين ومرتباتهم >= 35000 SELECTFNAME, LNAME, SALARY FROMEMP WHERESALARY >= 35000 ;

18 Chapter 7 © 2007 by Prentice Hall القيم غير المعروفة NULLs WHERE ColumnName IS [NOT] NULL مثال 3 : أرقام وأسماء الموظفين الذين لم يحدد لهم معدل أداء RAT SELECT EMP#, FNAME, LNAME FROM EMP WHERE RAT IS NULL;

19 Chapter 7 © 2007 by Prentice Hall ترتيب جدول النتائج ORDER BY SELECT... FROM … WHERE... ORDER BY ColumnName [ DESC ] ORDER BY ColumnName [ DESC ] [,ColumnName [ DESC ]...]; [,ColumnName [ DESC ]...]; مثال 1: اسم العائلة والاسم الأول للموظفين الذين يعملون في القاهرة مرتبة تصاعديا باسم العائلة SELECT LNAME, FNAME FROM EMP WHERE LOCATION = ‘Cairo' ORDER BY LNAME;

20 Chapter 7 © 2007 by Prentice Hall ترتيب جدول النتائج بالرقم النسبي لعمود ترتيب جدول النتائج بالرقم النسبي لحقل بيان (عمود) SELECT ColumnName, colunmName,... FROM... WHERE... ORDER BY columnNbr [ DESC ] [,columnNbr [ DESC ]...]; [,columnNbr [ DESC ]...]; مثال 2:اسم العائلة والعمل والمرتب للموظفين الذين يعملون في الجيزة مثال 2:اسم العائلة والعمل والمرتب للموظفين الذين يعملون في الجيزة - رتب الجدول تنازليا بالمرتب وتصاعديا بالعمل - رتب الجدول تنازليا بالمرتب وتصاعديا بالعمل SELECT LNAME, JOB, SALARY FROMEMP WHERE LOCATION = ‘Giza’ ORDER BY 3 DESC, 2; ORDER BY 3 DESC, 2;

21 Chapter 7 © 2007 by Prentice Hall تعدد الشروط Multiple Conditions ربط شروط البحث AND & OR مثال 1: أرقام وأسماء الموظفين الذين يعملون كمبرمجين ومرتباتهم أقل من 32000 SELECT EMP#, FNAME, JOB, SALARY FROM EMP WHERE JOB = 'PRG' AND SALARY < 32000; مثال 2: أرقام وأسماء الموظفين الذين يعملون كمبرمجين أو مرتباتهم أقل من 32000 SELECT EMP#, FNAME, JOB, SALARY FROMEMP WHERE JOB = 'PRG' OR SALARY < 32000;

22 Chapter 7 © 2007 by Prentice Hall تابع تعدد الشروط Multiple Conditions ربط شروط البحث AND & OR مثال 3 : الدورات التي حصل عليها المتدربان 16 و 17 وسُجِّلت تقديراتها SELECT * FROM TRAINEE WHERE EMP# = 16 OR EMP# = 17 AND GRADE IS NOT NULL; يجب استخدام الأقواس يجب استخدام الأقواس SELECT * FROM TRAINEE WHERE (EMP# = 016 OR EMP# = 017) AND GRADE IS NOT NULL;

23 Chapter 7 © 2007 by Prentice Hall مثال 4: تفاصيل البرامج المتطلبة لجميع البرامج التدريبية عدا البرنامجين 704 و 706 SELECT * FROMPREREQ WHERE NOT (SUPCRS# = 704 OR SUPCRS# = 706); OR SUPCRS# = 706); تابع تعدد الشروط Multiple Conditions نفي الشروط Negation Of Conditions

24 Chapter 7 © 2007 by Prentice Hall العوامل العلاقية BETWEEN, IN, LIKE اختيار صفوف بقيم في مدى محدد BETWEEN... AND SELECT... FROM... WHERE ColumnName [NOT] BETWEEN LowValue AND HighValue ; مثـال 1: أرقام الموظفين وأسماؤهم الأولى التي تبدأ بالحروف A, B, C, D, E, F A, B, C, D, E, F SELECT EMP#, FNAME FROM EMP WHERE FNAME BETWEEN 'A%' AND 'F%';

25 Chapter 7 © 2007 by Prentice Hall العوامل العلاقية BETWEEN, IN, LIKE اختيار صفوف بقيم محددة بقائمة IN SELECT … FROM... WHERE ColumnName [NOT] IN (List-of-values) ; ColumnName [NOT] IN (List-of-values) ; مثال 2: الدورات التي يقوم بتنفيذها المدربان 1 و 10 SELECT * FROM TRAINER WHERE EMP# IN (1, 10) ;

26 Chapter 7 © 2007 by Prentice Hall العوامل العلاقية BETWEEN, IN, LIKE اختيار صفوف طبقا لتركيبة حروف LIKE SELECT … FROM... WHERE ColumnName [NOT] LIKE (Searching-String) ; ColumnName [NOT] LIKE (Searching-String) ; مثال 3: أسماء الموظفين الأولى التي بها الحروف AH في الموقع الثاني والثالث من الاسم SELECT FNAME, LNAME FROM EMP WHERE FNAME LIKE '_AH%' ;

27 Chapter 7 © 2007 by Prentice Hall القيم المحسوبة Computed Values التعبيرات الحسابية في SELECT SELECT ColumnName, Expression, ColumnName,... Expression, ColumnName,... FROM … WHERE... ORDER BY ColumnNbr ; مثال 1: تقرير بأرقام وأسماء البرامج ومدة كل برنامج بالأسبوع مرتبا بعدد الأسابيع SELECT CRS#, CTITLE, C#HRS/C#HRSW FROM COURSE ORDER BY 3 ;

28 Chapter 7 © 2007 by Prentice Hall القيم المحسوبة Computed Values التعبيرات الحسابية في WHERE SELECT ColumnName, Expression, ColumnName,... FROM … WHERE … ORDER BY ColumnNbr ; مثال 2: تقرير بأرقام وأسماء البرامج ومدة كل منها بالأسبوع مرتبا بعدد الأسابيع للبرامج التي مدتها أكثر من 4 أسابيع ووضع عنوان لعدد الأسابيع # OF WEEKS =“ SELECT CTITLE, '# OF WEEKS =', C#HRS/C#HRSW FROM COURSE WHERE C#HRS/C#HRSW > 4 ORDER BY 3 ;

29 Chapter 7 © 2007 by Prentice Hall SELECT AVG ([ DISTINCT ] ColumnName) FROM... WHERE... ; مثال 1 : القيمة المتوسطة لمعدل الموظفين العاملين بالقاهرة SELECT AVG (RAT) FROM EMP FROM EMP WHERE LOCATION = ‘Cairo’ ; WHERE LOCATION = ‘Cairo’ ; دوال الأعمدة Column Functions القيمة المتوسطة لقيم عمود AVG

30 Chapter 7 © 2007 by Prentice Hall SELECT SUM ([ DISTINCT ] ColumnName) FROM... WHERE... ; مثال 2: مجموع مرتبات أخصائيي ومبرمجي قواعد البيانات بالقاهرة SELECT SUM (SALARY) FROM EMP FROM EMP WHERE (JOB = 'DBA' OR JOB = 'DBP') WHERE (JOB = 'DBA' OR JOB = 'DBP') AND LOCATION = ‘Cairo’ ; AND LOCATION = ‘Cairo’ ; دوال الأعمدة Column Functions مجموع قيم عمود SUM

31 Chapter 7 © 2007 by Prentice Hall SELECT MIN ([ DISTINCT ] ColumnName) FROM... WHERE... ; SELECT MAX ([ DISTINCT ] ColumnName) FROM... WHERE... ; مثال 3: تاريخ ميلاد أكبر وأصغر مبرمج SELECT MAX(DOB), MIN(DOB) FROM EMP FROM EMP WHERE JOB = ’PRG' ; WHERE JOB = ’PRG' ; دوال الأعمدة Column Functions أقل قيمة في قيم عمود MIN وأكبر قيمة في قيم عمود MAX

32 Chapter 7 © 2007 by Prentice Hall SELECT COUNT(*) FROM... WHERE... ; مثال 4: عدد موظفي ”الجيزة“ ومتوسط مرتباتهم SELECT COUNT(*), AVG(SALARY) FROM EMP FROM EMP WHERE LOCATION = ’Giza' ; WHERE LOCATION = ’Giza' ; دوال الأعمدة Column Functions عدد صفوف جدول النتائج COUNT

33 Chapter 7 © 2007 by Prentice Hall SELECT COUNT(DISTINCT ColumnName) FROM... WHERE... ; مثال 5: عدد الأعمال غير المتكررة التي يقوم بها الموظفون SELECT COUNT(DISTINCT JOB) FROM EMP ; FROM EMP ; دوال الأعمدة Column Functions عدد صفوف جدول النتائج بدون القيم المتكررة أو NULLs

34 Chapter 7 © 2007 by Prentice Hall SELECT ColumnName[,ColumnName][,ColumnFunction],... FROM … WHERE... WHERE... GROUP BY ColumnName[,ColumnName...] ORDER BY ColumnName [DESC][,ColumnName [DESC]...] SequenceNumber [DESC] [,SequenceNumber [DESC]...] ; المجموعـات Grouping تجميع الصفوف في مجموعات فرعية GROUP BY

35 Chapter 7 © 2007 by Prentice Hall مثال 1: ما مجموع مرتبات الموظفين بكل موقع عمل Location عدا مرتبات المبرمجين؟ رتب النتيجة طبقا للمجموع SELECT LOCATION, SUM (SALARY) FROM EMP WHERE NOT JOB = 'PRG' GROUP BY LOCATION ORDER BY 2 ; المجموعـات Grouping تجميع الصفوف في مجموعات فرعية GROUP BY

36 Chapter 7 © 2007 by Prentice Hall مثال 2: متوسط مرتبات كل عمل JOB عدا DBA بكل موقع عمل Location للأعمال التي يقوم بها أكثر من موظف. رتب النتيجة تنازليا بمتوسط المرتبات تصاعديا داخل العمل داخل موقع العمل. SELECT LOCATION, 'JOB NAME IS', JOB, AVG (SALARY) AVG (SALARY) FROM EMP WHERE JOB <> 'DBA' GROUP BY LOCATION, JOB HAVING COUNT (*) > 1 HAVING COUNT (*) > 1 ORDER BY LOCATION, JOB, 4 DESC ; ORDER BY LOCATION, JOB, 4 DESC ; المجموعـات Grouping ترشيح المجموعات الفرعية GROUP BY... HAVING

37 Chapter 7 © 2007 by Prentice Hall تسلسل تنفيذ SELECT اختيار صفوف الجدول التي تحقق شروط WHERE اختيار صفوف الجدول التي تحقق شروط WHERE تُكوِّن GROUP BY مجموعات فرعية من الصفوف المختارة تُكوِّن GROUP BY مجموعات فرعية من الصفوف المختارة حذف المجموعات الفرعية التي لا يتوافر فيها شروط HAVING حذف المجموعات الفرعية التي لا يتوافر فيها شروط HAVING تنفيذ دوال العمود أو التعبيرات الحسابية في SELECT على المجموعات الفرعية الناتجة في الخطوة السابقة تنفيذ دوال العمود أو التعبيرات الحسابية في SELECT على المجموعات الفرعية الناتجة في الخطوة السابقة ترتيب ناتج الخطوة السابقة طبقا لعبارة ORDER BY. ترتيب ناتج الخطوة السابقة طبقا لعبارة ORDER BY. المجموعـات Grouping ترشيح المجموعات الفرعية GROUP BY... HAVING

38 Chapter 7 © 2007 by Prentice Hall 38 Using and Defining Views Views provide users controlled access to tables Views provide users controlled access to tables Base Table –table containing the raw data Base Table –table containing the raw data Dynamic View Dynamic View A “virtual table” created dynamically upon request by a user A “virtual table” created dynamically upon request by a user No data actually stored; instead data from base table made available to user No data actually stored; instead data from base table made available to user Based on SQL SELECT statement on base tables or other views Based on SQL SELECT statement on base tables or other views Materialized View Materialized View Copy or replication of data Copy or replication of data Data actually stored Data actually stored Must be refreshed periodically to match the corresponding base tables Must be refreshed periodically to match the corresponding base tables

39 Chapter 7 © 2007 by Prentice Hall 39 Sample CREATE VIEW CREATE VIEW EXPENSIVE_STUFF_V AS SELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICE FROM PRODUCT_T WHERE UNIT_PRICE >300 WITH CHECK_OPTION;  View has a name  View is based on a SELECT statement  CHECK_OPTION works only for updateable views and prevents updates that would create rows not included in the view

40 Chapter 7 © 2007 by Prentice Hall 40 Advantages of Views Simplify query commands Simplify query commands Assist with data security (but don't rely on views for security, there are more important security measures) Assist with data security (but don't rely on views for security, there are more important security measures) Enhance programming productivity Enhance programming productivity Contain most current base table data Contain most current base table data Use little storage space Use little storage space Provide customized view for user Provide customized view for user Establish physical data independence Establish physical data independence

41 Chapter 7 © 2007 by Prentice Hall 41 Disadvantages of Views Use processing time each time view is referenced Use processing time each time view is referenced May or may not be directly updateable May or may not be directly updateable

42 Chapter 7 © 2007 by Prentice Hall 42 Schema Definition Control processing/storage efficiency Control processing/storage efficiency Some techniques used to tune dbase performance: Some techniques used to tune dbase performance: Choosing to index keys to increase the speed of row selection, table joining, and row ordering. Choosing to index keys to increase the speed of row selection, table joining, and row ordering. Selecting File organizations for base tables that match type of processing (keeping table physically sorted by a frequently used sort key) Selecting File organizations for base tables that match type of processing (keeping table physically sorted by a frequently used sort key) Selecting File organizations for indexes appropriate to the way the indexes are used. Selecting File organizations for indexes appropriate to the way the indexes are used. Data clustering so that related rows of frequently joined tables are stored close together in secondary storage Data clustering so that related rows of frequently joined tables are stored close together in secondary storage Statistics maintenance about tables and their indexes so that DBMS can find the most efficient ways to perform various database operations. Statistics maintenance about tables and their indexes so that DBMS can find the most efficient ways to perform various database operations.

43 Chapter 7 © 2007 by Prentice Hall Creating indexes Creating indexes DBMS uses Indexes to Speed up random/sequential access to base table data DBMS uses Indexes to Speed up random/sequential access to base table data Although users do not directly refer to indexes when writing any SQL command, the DBMS recognizes which existing indexes would improve query performance Although users do not directly refer to indexes when writing any SQL command, the DBMS recognizes which existing indexes would improve query performance Indexes are usually created for both primary and foreign keys and both single and compound keys Indexes are usually created for both primary and foreign keys and both single and compound keys Indexes could be in ascending or descending sequence Indexes could be in ascending or descending sequence Example Example CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMER_NAME) CREATE INDEX NAME_IDX ON CUSTOMER_T(CUSTOMER_NAME) This makes an index for the CUSTOMER_NAME field of the CUSTOMER_T table This makes an index for the CUSTOMER_NAME field of the CUSTOMER_T table To remove the index To remove the index Drop INDEX NAME_IDX Drop INDEX NAME_IDX 43


Download ppt "© 2007 by Prentice Hall 1 Chapter 7: Introduction to SQL SELECT Statement Modern Database Management 8 th Edition Jeffrey A. Hoffer, Mary B. Prescott,"

Similar presentations


Ads by Google