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.
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
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
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
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
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))
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
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
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;
ترتيب جدول النتائج بالرقم النسبي لعمودترتيب جدول النتائج بالرقم النسبي لعمود
لحقل بيان (عمود)لحقل بيان (عمود)ترتيب جدول النتائج بالرقم النسبي ترتيب جدول النتائج بالرقم النسبي 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;
تفاصيل البرامج المتطلبة لجميع تفاصيل البرامج المتطلبة لجميع : : 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 نفي الشروطنفي الشروط
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%';
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%' ;
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 ;
ما مجموع مرتبات الموظفين بكل موقع عملما مجموع مرتبات الموظفين بكل موقع عمل: : 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 تجميع الصفوف في مجموعات فرعيةتجميع الصفوف في مجموعات فرعية
بكل موقع عملبكل موقع عمل 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 ترشيح المجموعات الفرعيةترشيح المجموعات الفرعية
اختيار صفوف الجدول التي تحقق شروطاختيار صفوف الجدول التي تحقق شروط WHEREWHEREت�كو�نت�كو�ن GROUP BYGROUP BY مجموعات فرعية من الصفوف مجموعات فرعية من الصفوف
المختارةالمختارةحذف المجموعات الفرعية التي ال يتوافر فيها شروطحذف المجموعات الفرعية التي ال يتوافر فيها شروط
HAVINGHAVINGتنفيذ دوال العمود أو التعبيرات الحسابية فيتنفيذ دوال العمود أو التعبيرات الحسابية في SELECTSELECT
على المجموعات الفرعية الناتجة في الخطوة السابقةعلى المجموعات الفرعية الناتجة في الخطوة السابقةترتيب ناتج الخطوة السابقة طبقا لعبارةترتيب ناتج الخطوة السابقة طبقا لعبارة ORDER BYORDER BY..
GroupingGrouping المجموعـاتالمجموعـات ... GROUP BY ... GROUP BY ترشيح المجموعات الفرعيةترشيح المجموعات الفرعية
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
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
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
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.
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
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