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

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

Jan 02, 2016

Download

Documents

Polly Young
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 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,

© 2007 by Prentice Hall© 2007 by Prentice Hall 11

Chapter 7:Chapter 7:Introduction to SQLIntroduction to SQLSELECTSELECT Statement Statement

Modern Database Modern Database ManagementManagement

88thth Edition EditionJeffrey A. Hoffer, Mary B. Prescott, Jeffrey A. Hoffer, Mary B. Prescott,

Fred R. McFaddenFred R. McFadden

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 22

SELECT StatementSELECT Statement Used for Used for queriesqueries on on singlesingle or or multiplemultiple tablestables Clauses of the SELECT statement:Clauses of the SELECT statement:

SELECTSELECT List the List the columnscolumns (and (and expressionsexpressions) that should be returned from the ) that should be returned from the

queryquery FROMFROM

Indicate the Indicate the table(stable(s) or ) or view(sview(s) from which data will be obtained) from which data will be obtained WHEREWHERE

Indicate the Indicate the conditionsconditions under which a under which a rowrow will be will be includedincluded in the in the resultresult

GROUP BYGROUP BY Indicate Indicate categorizationcategorization of of results results

HAVINGHAVING Indicate the Indicate the conditionsconditions under which a under which a categorycategory ( (groupgroup) will be ) will be

includedincluded ORDER BYORDER BY

SortsSorts the the resultresult according to specified criteria according to specified criteria

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 33

Figure 7-10 SQL statement processing order (adapted from van der Lans, p.100)

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 44

SELECT ExampleSELECT Example

Find products with standard price less Find products with standard price less than $275than $275

SELECTSELECT PRODUCT_NAME, STANDARD_PRICE PRODUCT_NAME, STANDARD_PRICE

FROMFROM PRODUCT_V PRODUCT_V

WHEREWHERE STANDARD_PRICE < 275; STANDARD_PRICE < 275;

Table 7-3: Comparison Operators in SQL

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 55

SELECT Example Using AliasSELECT Example Using Alias

AliasAlias is an is an alternativealternative columncolumn or or tabletable namename

SELECT SELECT CUSTCUST.CUSTOMER AS .CUSTOMER AS NAMENAME, , CUST.CUSTOMER_ADDRESS CUST.CUSTOMER_ADDRESS

FROM CUSTOMER_V FROM CUSTOMER_V CUSTCUST

WHERE WHERE NAMENAME = ‘Home = ‘Home Furnishings’;Furnishings’;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 66

SELECT Example Using a SELECT Example Using a FunctionFunction

Using the Using the COUNTCOUNT aggregate functionaggregate function to find totalsto find totals

SELECT SELECT COUNT(*)COUNT(*) FROM ORDER_LINE_V FROM ORDER_LINE_VWHERE ORDER_ID = 1004;WHERE ORDER_ID = 1004;

Note: with aggregate functions you can’t Note: with aggregate functions you can’t have single-valued columns included in have single-valued columns included in the SELECT clausethe SELECT clause

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 77

SELECT Example–Boolean SELECT Example–Boolean OperatorsOperators

ANDAND, , OROR, and , and NOTNOT Operators for customizing Operators for customizing conditions in conditions in WHEREWHERE clause clause

SELECTSELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICESTANDARD_PRICE

FROMFROM PRODUCT_V PRODUCT_V

WHEREWHERE (PRODUCT_DESCRIPTION (PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Desk’Desk’

OROR PRODUCT_DESCRIPTION PRODUCT_DESCRIPTION LIKELIKE ‘ ‘%%Table’) Table’)

ANDAND UNIT_PRICE > 300; 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

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 88

Venn Diagram from Previous Venn Diagram from Previous QueryQuery

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 99

SELECT Example – SELECT Example – Sorting Results with the ORDER BY Sorting Results with the ORDER BY

ClauseClause SortSort the results first by the results first by STATESTATE, and , and

within a state by within a state by CUSTOMER_NAMECUSTOMER_NAME

SELECTSELECT CUSTOMER_NAME, CITY, STATE CUSTOMER_NAME, CITY, STATE

FROMFROM CUSTOMER_V CUSTOMER_V

WHEREWHERE STATE STATE ININ (‘FL’, ‘TX’, ‘CA’, ‘HI’) (‘FL’, ‘TX’, ‘CA’, ‘HI’)

ORDER BYORDER BY STATE, CUSTOMER_NAME; 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

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 1010

SELECT Example– SELECT Example– Categorizing Results Using the GROUP BY Categorizing Results Using the GROUP BY

ClauseClause For For useuse with aggregate with aggregate functionsfunctions

ScalarScalar aggregate aggregate: : singlesingle valuevalue returnedreturned from SQL query with from SQL query with aggregate functionaggregate function

VectorVector aggregate aggregate: : multiplemultiple valuesvalues returnedreturned from SQL query from SQL query with aggregate function (via with aggregate function (via GROUPGROUP BYBY))

SELECTSELECT CUSTOMER_STATE, CUSTOMER_STATE, COUNTCOUNT(CUSTOMER_STATE) (CUSTOMER_STATE)

FROMFROM CUSTOMER_V CUSTOMER_V

GROUP BYGROUP BY CUSTOMER_STATE; CUSTOMER_STATE;

Note: you can use single-value fields with aggregate Note: you can use single-value fields with aggregate functions if they are included in the GROUP BY clausefunctions if they are included in the GROUP BY clause

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 1111

SELECT Example– SELECT Example– Qualifying Results by Categories Qualifying Results by Categories

Using the HAVING ClauseUsing the HAVING Clause For For useuse with with GROUPGROUP BYBY

SELECTSELECT CUSTOMER_STATE, CUSTOMER_STATE, COUNTCOUNT(CUSTOMER_STATE) (CUSTOMER_STATE)

FROMFROM CUSTOMER_V CUSTOMER_V

GROUPGROUP BYBY CUSTOMER_STATE CUSTOMER_STATE

HAVINGHAVING COUNTCOUNT(CUSTOMER_STATE) > 1;(CUSTOMER_STATE) > 1;

Like a WHERE clause, but it operates on groups (categories), not Like a WHERE clause, but it operates on groups (categories), not on individual rows.on individual rows.

Here, only those groups with total numbers greater than 1 will be Here, only those groups with total numbers greater than 1 will be included in final resultincluded in final result

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

SQL SQL تعليماتتعليماتSQL StatementSQL Statement

SELECTSELECT

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECTSELECT الشكل العام لتعليمةالشكل العام لتعليمة

SELECTSELECT [DISTINCT] ColumnName(s)[DISTINCT] ColumnName(s)

FROM Table(s)FROM Table(s)

[WHERE[WHERE Condition]Condition]

[GROUP[GROUP BY ColumnName(s)]BY ColumnName(s)]

[HAVING[HAVING Condition]Condition]

[ORDER[ORDER BY ColumnName(s)]BY ColumnName(s)] ; ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

اختيار أعمدة محددة من جدول اختيار أعمدة محددة من جدول (*)(*) اختيار كل أعمدة جدولاختيار كل أعمدة جدول

: عرض أرقام وأسماء جميع البرامج : عرض أرقام وأسماء جميع البرامج 11مثالمثالالتدريبية المتاحةالتدريبية المتاحة

SELECT CRS#, CTITLESELECT CRS#, CTITLE

FROM COURSE ;FROM COURSE ;

عرض تفاصيل جميع البرامج التدريبية عرض تفاصيل جميع البرامج التدريبية : : 22مثالمثالالمتاحةالمتاحة

SELECT *SELECT *

FROM COURSE ;FROM COURSE ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

DISTINCT- DISTINCT - حذف الصفوف المتكررةحذف الصفوف المتكررة

عرض أسماء أماكن تنفيذ الدورات عرض أسماء أماكن تنفيذ الدورات : : 33مثـال مثـالالتدريبية مع حذف الصفوف المتكررة من التدريبية مع حذف الصفوف المتكررة من

النتيجةالنتيجة

SELECTSELECT DISTINCT LOCATIONDISTINCT LOCATION

FROMFROM OFFER ;OFFER ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Conditional RetrievalConditional Retrieval االسترجـاع المشروطاالسترجـاع المشروطWHEREWHERE عبارةعبارة

SELECT . . .SELECT . . .

FROM . . .FROM . . .

WHERE [ NOT ] ColumnName WHERE [ NOT ] ColumnName

ComparisonOperator LiteralComparisonOperator Literal

Comparison Operators Comparison Operators عوامل المقارنةعوامل المقارنة

تساويتساوي = = ال يساويال يساوي>< >< أكبر منأكبر من> >

أكبر من أو يساويأكبر من أو يساوي <= <= أقل من أقل من < < أقل أقل =< =< من أو يساويمن أو يساوي

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Conditional RetrievalConditional Retrieval االسترجـاع المشروطاالسترجـاع المشروطWHEREWHERE عبارةعبارة

أسماء الموظفين الذين يعملون في أسماء الموظفين الذين يعملون في : : 11مثال مثال القاهرةالقاهرة

SELECT FNAME, LNAMESELECT FNAME, LNAMEFROMFROM EMPEMPWHERE LOCATION = ‘Cairo’WHERE LOCATION = ‘Cairo’;;

3500035000أسماء الموظفين ومرتباتهم <= أسماء الموظفين ومرتباتهم <= : : 22مثال مثال SELECTSELECT FNAME, LNAME, SALARYFNAME, LNAME, SALARYFROMFROM EMPEMPWHEREWHERE SALARY <= 35000SALARY <= 35000 ; ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

NULLsNULLs القيم غير المعروفةالقيم غير المعروفة

WHERE ColumnName IS [NOT] NULLWHERE ColumnName IS [NOT] NULL

أرقام وأسماء الموظفين الذين لم أرقام وأسماء الموظفين الذين لم : : 33مثال مثال RATRAT يحدد لهم معدل أداءيحدد لهم معدل أداء

SELECT EMP#, FNAME, LNAMESELECT EMP#, FNAME, LNAMEFROM EMPFROM EMPWHERE RAT IS NULL;WHERE RAT IS NULL;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

ORDER BYORDER BY ترتيب جدول النتائجترتيب جدول النتائج

SELECT . . . SELECT . . . FROM FROM …… WHERE ... WHERE ... ORDER BY ColumnName [ DESC ] ORDER BY ColumnName [ DESC ] [,ColumnName [ DESC ] ...];[,ColumnName [ DESC ] ...];

اسم العائلة واالسم األول للموظفين الذين يعملون اسم العائلة واالسم األول للموظفين الذين يعملون ::11مثال مثال مرتبة تصاعديا باسم العائلة مرتبة تصاعديا باسم العائلة القاهرة القاهرةفيفي

SELECT LNAME, FNAMESELECT LNAME, FNAMEFROM EMPFROM EMPWHERE LOCATION = ‘Cairo'WHERE LOCATION = ‘Cairo'ORDER BY LNAME;ORDER BY LNAME;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

ترتيب جدول النتائج بالرقم النسبي لعمودترتيب جدول النتائج بالرقم النسبي لعمود

لحقل بيان (عمود)لحقل بيان (عمود)ترتيب جدول النتائج بالرقم النسبي ترتيب جدول النتائج بالرقم النسبي SELECT ColumnName, colunmName, ...SELECT ColumnName, colunmName, ...FROMFROM ... ... WHERE ...WHERE ...ORDER BY columnNbr [ DESC ]ORDER BY columnNbr [ DESC ] [,columnNbr [ DESC ] ...];[,columnNbr [ DESC ] ...];

:اسم العائلة والعمل والمرتب للموظفين الذين يعملون :اسم العائلة والعمل والمرتب للموظفين الذين يعملون 22مثال مثال الجيزةالجيزة فيفي رتب الجدول تنازليا بالمرتب وتصاعديا بالعملرتب الجدول تنازليا بالمرتب وتصاعديا بالعمل - -

SELECT LNAME, JOB, SALARYSELECT LNAME, JOB, SALARYFROMFROM EMPEMPWHERE LOCATION = ‘Giza’WHERE LOCATION = ‘Giza’ ORDER BY 3 DESC, 2;ORDER BY 3 DESC, 2;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Multiple ConditionsMultiple Conditions تعدد الشروطتعدد الشروطAND & ORAND & OR ربط شروط البحثربط شروط البحث

أرقام وأسماء الموظفين الذين يعملون أرقام وأسماء الموظفين الذين يعملون : : 11مثال مثال 3200032000كمبرمجين ومرتباتهم أقل من كمبرمجين ومرتباتهم أقل من

SELECT EMP#, FNAME, JOB, SALARYSELECT EMP#, FNAME, JOB, SALARYFROMFROM EMP EMPWHERE JOB = 'PRG' AND SALARY < 32000;WHERE JOB = 'PRG' AND SALARY < 32000;

أرقام وأسماء الموظفين الذين يعملون أرقام وأسماء الموظفين الذين يعملون : : 22مثال مثال 3200032000 مرتباتهم أقل من مرتباتهم أقل من أوأوكمبرمجين كمبرمجين

SELECT EMP#, FNAME, JOB, SALARYSELECT EMP#, FNAME, JOB, SALARYFROMFROM EMPEMPWHERE JOB = 'PRG' OR SALARY < 32000;WHERE JOB = 'PRG' OR SALARY < 32000;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Multiple ConditionsMultiple Conditions تابع تعدد الشروطتابع تعدد الشروطAND & ORAND & OR ربط شروط البحثربط شروط البحث

1717 و و 1616الدورات التي حصل عليها المتدربان الدورات التي حصل عليها المتدربان : : 33مثال مثال لت تقديراتها ج� لت تقديراتهاوس� ج� وس�

SELECT *SELECT *FROM TRAINEEFROM TRAINEEWHERE EMP# = 16 OR EMP# = 17 WHERE EMP# = 16 OR EMP# = 17 AND GRADE IS NOT NULL;AND GRADE IS NOT NULL;

يجب استخدام األقواسيجب استخدام األقواس

SELECT *SELECT *

FROM TRAINEEFROM TRAINEEWHERE WHERE (EMP# = 016 OR EMP# = 017)(EMP# = 016 OR EMP# = 017)AND GRADE IS NOT NULL;AND GRADE IS NOT NULL;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

تفاصيل البرامج المتطلبة لجميع تفاصيل البرامج المتطلبة لجميع : : 44مثال مثال 706706 و و 704704البرامج التدريبية عدا البرنامجين البرامج التدريبية عدا البرنامجين

SELECT *SELECT *FROMFROM PREREQPREREQWHERE WHERE NOTNOT (SUPCRS# = 704 (SUPCRS# = 704 OR SUPCRS# = 706);OR SUPCRS# = 706);

Multiple ConditionsMultiple Conditions تابع تعدد الشروطتابع تعدد الشروطNegation Of ConditionsNegation Of Conditions نفي الشروطنفي الشروط

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

BETWEEN, IN, LIKEBETWEEN, IN, LIKE العوامل العالقيةالعوامل العالقيةاختيار صفوف بقيم في مدى محدداختيار صفوف بقيم في مدى محدد

BETWEEN ... ANDBETWEEN ... AND

SELECT ...SELECT ...FROM ...FROM ...WHERE ColumnName [NOT] BETWEENWHERE ColumnName [NOT] BETWEEN

LowValue AND HighValueLowValue AND HighValue;;أرقام الموظفين وأسماؤهم األولى التي تبدأ أرقام الموظفين وأسماؤهم األولى التي تبدأ : : 11مثـال مثـال

بالحروفبالحروف A, B, C, D, E, FA, B, C, D, E, FSELECT EMP#, FNAMESELECT EMP#, FNAMEFROMFROM EMP EMPWHERE FNAMEWHERE FNAME BETWEEN 'A%' AND 'F%';BETWEEN 'A%' AND 'F%';

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

BETWEEN, IN, LIKEBETWEEN, IN, LIKE العوامل العالقيةالعوامل العالقية

ININ اختيار صفوف بقيم محددة بقائمةاختيار صفوف بقيم محددة بقائمة

SELECT … FROM ...SELECT … FROM ...WHERE WHERE ColumnName [NOT] IN (List-of-values) ;ColumnName [NOT] IN (List-of-values) ;

1010 و و 11الدورات التي يقوم بتنفيذها المدربان الدورات التي يقوم بتنفيذها المدربان : : 22مثال مثال

SELECT *SELECT *FROMFROM TRAINER TRAINERWHERE EMP# IN (1, 10) ;WHERE EMP# IN (1, 10) ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

BETWEEN, IN, LIKEBETWEEN, IN, LIKE العوامل العالقيةالعوامل العالقية

LIKELIKE اختيار صفوف طبقا لتركيبة حروفاختيار صفوف طبقا لتركيبة حروف

SELECT … FROM ...SELECT … FROM ...WHERE WHERE ColumnName [NOT] LIKE (Searching-ColumnName [NOT] LIKE (Searching-

String) String) ;; AHAH أسماء الموظفين األولى التي بها الحروفأسماء الموظفين األولى التي بها الحروف: : 33مثال مثال

في الموقع الثاني والثالث من االسمفي الموقع الثاني والثالث من االسمSELECT FNAME, LNAME SELECT FNAME, LNAME FROMFROM EMP EMPWHERE FNAME WHERE FNAME LIKE '_AH%' ;LIKE '_AH%' ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Computed ValuesComputed Values القيم المحسوبةالقيم المحسوبةSELECTSELECT التعبيرات الحسابية فيالتعبيرات الحسابية في

SELECT ColumnName, SELECT ColumnName,

Expression, ColumnName, ...Expression, ColumnName, ...

FROM … WHERE ...FROM … WHERE ...

ORDER BY ColumnNbr ;ORDER BY ColumnNbr ;تقرير بأرقام وأسماء البرامج ومدة كل برنامج تقرير بأرقام وأسماء البرامج ومدة كل برنامج : : 11مثال مثال

باألسبوع مرتبا بعدد األسابيعباألسبوع مرتبا بعدد األسابيع

SELECT CRS#, CTITLE, SELECT CRS#, CTITLE, C#HRS/C#HRSWC#HRS/C#HRSW

FROMFROM COURSE COURSE

ORDER BY ORDER BY 33 ; ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Computed ValuesComputed Values القيم المحسوبةالقيم المحسوبةWHEREWHERE التعبيرات الحسابية فيالتعبيرات الحسابية في

SELECT ColumnName, Expression, ColumnName,...SELECT ColumnName, Expression, ColumnName,...

FROM …FROM …

WHERE … ORDER BY ColumnNbr ;WHERE … ORDER BY ColumnNbr ;تقرير بأرقام وأسماء البرامج ومدة كل منها باألسبوع تقرير بأرقام وأسماء البرامج ومدة كل منها باألسبوع : : 22مثال مثال

أسابيع ووضع أسابيع ووضع 44مرتبا بعدد األسابيع للبرامج التي مدتها أكثر من مرتبا بعدد األسابيع للبرامج التي مدتها أكثر من

=“ =“OF WEEKSOF WEEKS # # عنوان لعدد األسابيععنوان لعدد األسابيعSELECT CTITLE, SELECT CTITLE, '# OF WEEKS =''# OF WEEKS =', C#HRS/C#HRSW, C#HRS/C#HRSW

FROMFROM COURSE COURSE

WHERE WHERE C#HRS/C#HRSWC#HRS/C#HRSW > 4 > 4 ORDER BY 3 ;ORDER BY 3 ;

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT SELECT AVGAVG ([ DISTINCT ] ColumnName) ([ DISTINCT ] ColumnName)FROM ...FROM ...WHERE ... ;WHERE ... ;

القيمة المتوسطة لمعدل الموظفين العاملين القيمة المتوسطة لمعدل الموظفين العاملين : : 11مثال مثال بالقاهرةبالقاهرة

SELECT AVG (RAT) SELECT AVG (RAT) FROM EMPFROM EMP

WHERE LOCATION = ‘Cairo’ WHERE LOCATION = ‘Cairo’ ;;

Column FunctionsColumn Functions دوال األعمدةدوال األعمدةAVGAVG القيمة المتوسطة لقيم عمودالقيمة المتوسطة لقيم عمود

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT SELECT SUMSUM ([ DISTINCT ] ColumnName) ([ DISTINCT ] ColumnName)FROM ...FROM ...WHERE ... ;WHERE ... ;

أخصائيي ومبرمجي قواعد أخصائيي ومبرمجي قواعد مجموع مرتبات مجموع مرتبات : : 22مثال مثال بالقاهرةبالقاهرةالبيانات البيانات

SELECT SUM (SALARY) SELECT SUM (SALARY) FROM EMPFROM EMP WHERE WHERE (JOB = 'DBA' OR JOB = 'DBP')(JOB = 'DBA' OR JOB = 'DBP')

AND LOCATION = ‘Cairo’ AND LOCATION = ‘Cairo’ ;;

Column FunctionsColumn Functions دوال األعمدةدوال األعمدةSUMSUM مجموع قيم عمودمجموع قيم عمود

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT SELECT MINMIN ([ DISTINCT ] ColumnName) ([ DISTINCT ] ColumnName)FROM ...FROM ...WHERE ... ;WHERE ... ;SELECT SELECT MAXMAX ([ DISTINCT ] ColumnName) ([ DISTINCT ] ColumnName)FROM ...FROM ...WHERE ... ;WHERE ... ;

تاريخ ميالد أكبر وأصغر مبرمجتاريخ ميالد أكبر وأصغر مبرمج : : 33مثال مثال SELECT MAX(DOB), MIN(DOB) SELECT MAX(DOB), MIN(DOB) FROM EMPFROM EMP

WHERE WHERE JOB = ’PRG'JOB = ’PRG' ;;

Column FunctionsColumn Functions دوال األعمدةدوال األعمدةوأكبر قيمة في وأكبر قيمة في MIN MIN أقل قيمة في قيم عمودأقل قيمة في قيم عمود

MAXMAX قيم عمودقيم عمود

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT COUNT(*) SELECT COUNT(*) FROM ...FROM ...WHERE ... ;WHERE ... ;

ومتوسط مرتباتهمومتوسط مرتباتهم”الجيزة“ ”الجيزة“ عدد موظفي عدد موظفي : : 44مثال مثال

SELECT COUNT(*), AVG(SALARY) SELECT COUNT(*), AVG(SALARY) FROM EMPFROM EMP

WHERE LOCATION WHERE LOCATION = ’Giza' = ’Giza' ;;

Column FunctionsColumn Functions دوال األعمدةدوال األعمدةCOUNTCOUNT عدد صفوف جدول النتائجعدد صفوف جدول النتائج

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT COUNT(DISTINCT ColumnName) SELECT COUNT(DISTINCT ColumnName) FROM ...FROM ...WHERE ... ;WHERE ... ;

عدد األعمال غير المتكررة التي يقوم بها عدد األعمال غير المتكررة التي يقوم بها : : 55مثال مثال الموظفونالموظفون

SELECT COUNT(DISTINCT JOB) SELECT COUNT(DISTINCT JOB)

FROM EMPFROM EMP;;

Column FunctionsColumn Functions دوال األعمدةدوال األعمدةالمتكررة المتكررة عدد صفوف جدول النتائج بدون القيمعدد صفوف جدول النتائج بدون القيم

NULLsNULLs أوأو

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECT ColumnName[,ColumnName]SELECT ColumnName[,ColumnName][,ColumnFunction], ...[,ColumnFunction], ...

FROMFROM … … WHERE ...WHERE ...GROUP BY ColumnName[,ColumnName ...]GROUP BY ColumnName[,ColumnName ...]

ORDER BY ColumnNameORDER BY ColumnName [DESC][,ColumnName [DESC][,ColumnName [DESC]...][DESC]...]

SequenceNumber [DESC]SequenceNumber [DESC]

[,SequenceNumber [DESC]...][,SequenceNumber [DESC]...];;

GroupingGrouping المجموعـاتالمجموعـات GROUP GROUP تجميع الصفوف في مجموعات فرعيةتجميع الصفوف في مجموعات فرعية

BYBY

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

ما مجموع مرتبات الموظفين بكل موقع عملما مجموع مرتبات الموظفين بكل موقع عمل: : 11مثال مثال LocationLocation عدا مرتبات المبرمجين؟ رتب النتيجة طبقا عدا مرتبات المبرمجين؟ رتب النتيجة طبقاللمجموعللمجموع

SELECT LOCATION, SUM (SALARY)SELECT LOCATION, SUM (SALARY)FROM EMPFROM EMPWHERE NOT JOB = 'PRG'WHERE NOT JOB = 'PRG'GROUP BY LOCATIONGROUP BY LOCATIONORDER BY 2ORDER BY 2 ; ;

GroupingGrouping المجموعـاتالمجموعـات GROUP GROUP تجميع الصفوف في مجموعات فرعيةتجميع الصفوف في مجموعات فرعية

BYBY

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

بكل موقع عملبكل موقع عمل DBADBA عداعدا JOBJOB متوسط مرتبات كل عملمتوسط مرتبات كل عمل: : 22مثال مثال LocationLocation لألعمال التي يقوم بها أكثر من موظف. رتب النتيجة لألعمال التي يقوم بها أكثر من موظف. رتب النتيجة

تنازليا بمتوسط المرتبات تصاعديا داخل العمل داخل موقع تنازليا بمتوسط المرتبات تصاعديا داخل العمل داخل موقع .. العملالعمل

SELECT LOCATION, 'JOB NAME IS', JOB,SELECT LOCATION, 'JOB NAME IS', JOB, AVG (SALARY)AVG (SALARY)FROMFROM EMP EMPWHERE JOB <> 'DBA'WHERE JOB <> 'DBA'GROUP BY LOCATION, JOBGROUP BY LOCATION, JOB HAVING COUNT (*) > 1 HAVING COUNT (*) > 1 ORDER BY LOCATION, JOB, 4 DESC ;ORDER BY LOCATION, JOB, 4 DESC ;

GroupingGrouping المجموعـاتالمجموعـات ... GROUP BY ... GROUP BY ترشيح المجموعات الفرعيةترشيح المجموعات الفرعية

HAVINGHAVING

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

SELECTSELECT تسلسل تنفيذتسلسل تنفيذ

اختيار صفوف الجدول التي تحقق شروطاختيار صفوف الجدول التي تحقق شروط WHEREWHEREت�كو�نت�كو�ن GROUP BYGROUP BY مجموعات فرعية من الصفوف مجموعات فرعية من الصفوف

المختارةالمختارةحذف المجموعات الفرعية التي ال يتوافر فيها شروطحذف المجموعات الفرعية التي ال يتوافر فيها شروط

HAVINGHAVINGتنفيذ دوال العمود أو التعبيرات الحسابية فيتنفيذ دوال العمود أو التعبيرات الحسابية في SELECTSELECT

على المجموعات الفرعية الناتجة في الخطوة السابقةعلى المجموعات الفرعية الناتجة في الخطوة السابقةترتيب ناتج الخطوة السابقة طبقا لعبارةترتيب ناتج الخطوة السابقة طبقا لعبارة ORDER BYORDER BY..

GroupingGrouping المجموعـاتالمجموعـات ... GROUP BY ... GROUP BY ترشيح المجموعات الفرعيةترشيح المجموعات الفرعية

HAVINGHAVING

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 3838

Using and Defining ViewsUsing and Defining Views ViewsViews provide users provide users controlledcontrolled accessaccess to to tablestables BaseBase TableTable –table containing the –table containing the rawraw datadata Dynamic ViewDynamic View

A “A “virtualvirtual tabletable” created ” created dynamicallydynamically upon request by a upon request by a user user

NoNo datadata actually actually storedstored; instead data from base table ; instead data from base table made available to usermade available to user

Based on Based on SQLSQL SELECTSELECT statementstatement on on basebase tablestables or or otherother viewsviews

Materialized ViewMaterialized View Copy or Copy or replicationreplication of of datadata DataData actuallyactually storedstored MustMust be be refreshedrefreshed periodicallyperiodically to match the to match the

corresponding base tablescorresponding base tables

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 3939

Sample CREATE VIEWSample CREATE VIEW

CREATECREATE VIEWVIEW EXPENSIVE_STUFF_V EXPENSIVE_STUFF_V ASAS

SELECTSELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICE PRODUCT_ID, PRODUCT_NAME, UNIT_PRICE

FROMFROM PRODUCT_T PRODUCT_T

WHEREWHERE UNIT_PRICE >300 UNIT_PRICE >300

WITHWITH CHECK_OPTIONCHECK_OPTION;;

View has a nameView is based on a SELECT statementCHECK_OPTION works only for updateable views and prevents updates that would create rows not included in the view

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 4040

Advantages of ViewsAdvantages of Views Simplify query commandsSimplify query commands Assist with data security (but don't rely on Assist with data security (but don't rely on

views for security, there are more views for security, there are more important security measures)important security measures)

Enhance programming productivityEnhance programming productivity Contain most current base table dataContain most current base table data Use Use littlelittle storagestorage spacespace Provide Provide customizedcustomized viewview for for useruser Establish physical data independenceEstablish physical data independence

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 4141

Disadvantages of ViewsDisadvantages of Views

Use Use processingprocessing timetime each time view each time view is referencedis referenced

MayMay or may or may notnot be directly be directly updateableupdateable

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall 4242

SchemaSchema DefinitionDefinition ControlControl processing/storageprocessing/storage efficiencyefficiency Some Some techniquestechniques used to used to tunetune dbase dbase

performanceperformance:: Choosing to Choosing to index keys index keys to increase the speed of row to increase the speed of row

selection, table joining, and row ordering.selection, table joining, and row ordering. Selecting Selecting FileFile organizationsorganizations for base for base tables that match tables that match

type of processing type of processing (keeping table physically sorted by (keeping table physically sorted by a frequently used sort key)a frequently used sort key)

Selecting Selecting FileFile organizationsorganizations for for indexes indexes appropriate to appropriate to the way the indexes are used.the way the indexes are used.

DataData clustering clustering so that related rows of frequently so that related rows of frequently joined tables are joined tables are stored close together in secondary stored close together in secondary storagestorage

StatisticsStatistics maintenance maintenance about about tablestables and their and their indexesindexes so that DBMS can find the most efficient ways to so that DBMS can find the most efficient ways to perform various database operations.perform various database operations.

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

Chapter 7 © 2007 by Prentice Hall© 2007 by Prentice Hall

Creating indexesCreating indexes DBMS uses Indexes to DBMS uses Indexes to SpeedSpeed upup random/sequential random/sequential

accessaccess to base to base tabletable datadata Although users do not directly refer to indexes when Although users do not directly refer to indexes when

writing any SQL command, the writing any SQL command, the DBMSDBMS recognizesrecognizes which which existingexisting indexesindexes would improve query would improve query performanceperformance

IndexesIndexes are usually created for both are usually created for both primaryprimary and and foreignforeign keyskeys and both and both singlesingle and and compoundcompound keyskeys

Indexes could be in Indexes could be in ascendingascending or or descendingdescending sequencesequence

ExampleExample CREATECREATE INDEXINDEX NAME_IDX NAME_IDX ONON

CUSTOMER_T(CUSTOMER_NAME)CUSTOMER_T(CUSTOMER_NAME) This makes an index for the CUSTOMER_NAME field of the This makes an index for the CUSTOMER_NAME field of the

CUSTOMER_T tableCUSTOMER_T table To To removeremove the index the index

DropDrop INDEXINDEX NAME_IDX NAME_IDX4343