Presentation is loading. Please wait.

Presentation is loading. Please wait.

بسم الله الرحمن الرحيم Lecture (10).

Similar presentations


Presentation on theme: "بسم الله الرحمن الرحيم Lecture (10)."— Presentation transcript:

1 بسم الله الرحمن الرحيم Lecture (10)

2 SQL-99: SchemaDefinition, Constraints, and Queries and Views
Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views

3 لغة الاستفسارات الهيكلية Structured Query Language (SQL)
تعتبر اللغة الاساسية لكل قواعد البيانات العلائقية (Standard for Relational DBs) السبب الرئيسي في انتشار ونجاح النموذج العلائقي . تضم كل اللغات لقواعد البيانات ((Comprehensive DB Language وتشمل DDL + DML + VDL Commands وتمتاز أيضا بأنها More Declarative أي أن المستخدم يمكن أن يحدد ما يريد دون الاهتمام بطريقة التنفيذ. تمتاز بسهولة الـ .( user Friendly syntax) syntax النتيجة من أوامر الـSQL لا تمثل علاقة.

4 تستخدم الـ SQL المصلحات التالية :table ,row, column

5 DDL Commands in SQL Schema Definition:
Specifies a new database schema by giving it a name. Create Schema <Schema name> Authorization <Owner name>; Example: Create Schema FMS Authorization Ali; إسم خارطة قاعدة البيانات FMS اسم ممتلك خارطة قاعدة البيانات Ali Ali له الصلاحيات (drop, Modify, Insert,… ) ومنح الصلاحيات للمستخدمين. عناصر الـ Schema هي الجداول ، القيود ، المرئيات ، الـ domains.

6 إنشاء جدول (علاقة) جديد مع تحديد الصفات واسم العلاقة والقيود:
CREATE TABLE: Specifies a new base relation by giving it a name, and specifying each of its attributes and their data types (INTEGER, FLOAT, DECIMAL(i,j), CHAR(n), VARCHAR(n)) A constraint NOT NULL may be specified on an attribute

7 مثال: Create table FMS.Students (StdNo varchar(6) Not Null,
StdName varchar(30) Not Null, Address varchar(40), CourseNo varchar(10), Primary Key (stdNo), Foreign Key(CourseNo) References Courses (CNo) ); Create table Courses (CNo varchar(10) Not Null, CName varchar(20) Not Null, Dept varchar(30), UNIQUE (CNAME), Primary key(CNo)); راجع الـSQL Data Types .

8 Create Domain Names As char (30);
يمكن استخدام اسم الـ Domain بدلا عن char(30) مثلا في تعريف الجدول Students : StdName Names Not Null; Domain definition with Check clause: Create domain D-Num AS integer Check (D-Num>0 AND D-Num<21) In table definition: either Dno INT not Null check(Dno>0 and Dno<21) , OR Dno D-NUM,

9 Specifying constraints on tuples using Check:
Example At the end of create table statement of department table you can add check clause as following : Check (dept_create_date <=Mgr_start_date);

10 مثلا في تعريف الـCourse table: Dept varchar(30) default 'Computer' ,
Default value: يمكن تحديد Default value للصفة .في حالة عدم تحديد قيمة للصفة في أي صف يتم وضع الـDefault value المحددة للصفة وفي حالة عدم تحديد Default value توضع القيمة Null . مثلا في تعريف الـCourse table: Dept varchar(30) default 'Computer' ,

11 مثال في الجدول Student:
تحديد الخيارات في حالة أن العلاقة بها مفتاح خارجي: ON Delete ON Update set Null cascade set default مثال في الجدول Student: Foreign Key (CourseNo) References Courses (CNo) ON Delete set Null ON update Cascade;

12 Example CREATE TABLE EMP( ENAME VARCHAR(30) NOT NULL, ESSN CHAR(9), BDATE DATE, DNO INTEGER DEFAULT 1, SUPERSSN CHAR(9), PRIMARY KEY (ESSN), FOREIGN KEY (DNO) REFERENCES DEPT ON DELETE SET DEFAULT ON UPDATE CASCADE, FOREIGN KEY (SUPERSSN) REFERENCES EMP ON DELETE SET NULL ON UPDATE CASCADE);

13

14 Drop Schema: Drop Schema FMS Cascade; مسح الـSchema ومتابعة حذف كل الجداول ، المرئيات ، المجالات وكل القيود الخاصة بالخارطة. Drop Schema FMS Restrict ; منع حذف الخارطة إذا كانت تحتوي علي أي جداول (حذف الجداول أولا ثم حذف الخارطة).

15 مسح الجدول ، المرئيات التابعة له وكل القيود التابعة له.
Drop table: Drop table Students Cascade ; مسح الجدول ، المرئيات التابعة له وكل القيود التابعة له. Alter table: إضافة أو حذف عمود في الجدول (تغيير تعريف الجدول) وإضافة أوحذ ف قيود الجدول. Alter table FMS.Courses Drop Column Dept Cascade ; Alter table FMS.Students Add Column DeptNo varchar(30); تغيير نوع StdNo الي varchar(10) بدلاعن varchar(6) Alter table FMS.Students Alter column StdNo varchar(10)

16 Cont. Alter table company.department Alter column Mgr_ssn Drop Default; Alter table company.employee Alter column Mgr_ssn set Default ’123445’; Alter table company.employee Drop Constraint EMPSUPERFK Cascade;

17 DML Commands in SQL الاستفسارات الأساسية في SQL:
الأمر الأساسي للاستفسار أو الاسترجاع هو Select Statement الصورة العامة : SELECT        <attribute list> FROM <table list> WHERE <Condition>; attribute list :الصفات المراد استرجاع قيمها بواسطة الاستفسار. table list : الجداول اللازمة لتنفيذ الاستفسار. Condition : الشرط أو الشروط Boolean Expression والتي تحدد الصفوف المسترجعة من الاستفسار.

18 DML Commands in SQL الاستفسارات الأساسية في SQL:
الأمر الأساسي للاستفسار أو الاسترجاع هو Select Statement الصورة العامة : SELECT        <attribute list> FROM <table list> WHERE <Condition>; attribute list :الصفات المراد استرجاع قيمها بواسطة الاستفسار. table list : الجداول اللازمة لتنفيذ الاستفسار. Condition : الشرط أو الشروط Boolean Expression والتي تحدد الصفوف المسترجعة من الاستفسار.

19 مثال(1) من الجداول السابقة Student, Project : Query 1:
استرجع اسماء وأرقام الطلاب الذين أرقام مشاريعهم أكبر من 90 . SELECT StdNo, Stdname FROM Student WHERE Project No>90; Result: stdname Std No Taha 96-32 Mohd 96-22 96-24

20 P.area Stdname Cs Ali Query 2:
SELECT Stdname, Parea FROM Student, Project StdNo WHERE=‘96-14’ AND p.No=’23’ AND projectNo = P.No; P.area Stdname Cs Ali Result:

21 SELECT S.Stdname, P.Parea FROM Student AS S, Project AS P
يمكن استخدام (.) اذا كانت الصفتين تحملان نفس الاسم في الجدولين مثلا Student.PNo و Project.PNo . كذلك ايضا يمكن استخدام اسماء مستعارة للجداول Aliases وعليه يمكن إعادة كتابة الاستفسار (باستخدام (.) وأسماء مستعارة للجدولين) علي النحو التالي: SELECT S.Stdname, P.Parea FROM Student AS S, Project AS P WHERE S.StdNo = '96-14' AND S.ProjectNo= '23' AND S.ProjectNo = P.PNo;

22 Student وتعني استرجاع كل الجدول
Query (3): SELECT * FROM Students; Select * ≡ Select All Student وتعني استرجاع كل الجدول Query (4): SELECT * FROM Student WHERE ProjectNo = ‘56'; يعني هذا الاستفسار استرجاع كل أعمدة الجدول Student والصفوف التي تحقق الشرط ProjectNo= 56

23 Query (5): SELECT PNo FROM Projects;

24 Relational Database Schema--Figure 5.5

25 USE OF DISTINCT SQL does not treat a relation as a set; duplicate tuples can appear To eliminate duplicate tuples in a query result, the keyword DISTINCT is used For example, the result of Q11 may have duplicate SALARY values whereas Q11A does not have any duplicate values Q11: SELECT SALARY FROM EMPLOYEE Q11A: SELECT DISTINCT SALARY FROM EMPLOYEE

26 SET OPERATIONS SQL has directly incorporated some set operations
There is a union operation (UNION), and in some versions of SQL there are set difference (MINUS) and intersection (INTERSECT) operations The resulting relations of these set operations are sets of tuples; duplicate tuples are eliminated from the result The set operations apply only to union compatible relations; the two relations must have the same attributes and the attributes must appear in the same order

27 SET OPERATIONS SQL has directly incorporated some set operations
There is a union operation (UNION), and in some versions of SQL there are set difference (MINUS) and intersection (INTERSECT) operations The resulting relations of these set operations are sets of tuples; duplicate tuples are eliminated from the result The set operations apply only to union compatible relations; the two relations must have the same attributes and the attributes must appear in the same order

28 SET OPERATIONS (contd.)
Query : Make a list of all project numbers for projects that involve an employee whose last name is 'Smith' as a worker or as a manager of the department that controls the project. Q: (SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND NAME='Smith')

29 Include COUNT, SUM, MAX, MIN, and AVG
AGGREGATE FUNCTIONS Include COUNT, SUM, MAX, MIN, and AVG Query 15: Find the maximum salary, the minimum salary, and the average salary among all employees. Q15: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE Some SQL implementations may not allow more than one function in the SELECT-clause

30 AGGREGATE FUNCTIONS (cont.)
Query 16: Find the maximum salary, the minimum salary, and the average salary among employees who work for the 'Research' department. Q16: SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME='Research'

31 AGGREGATE FUNCTIONS (cont.)
Queries 17 and 18: Retrieve the total number of employees in the company (Q17), and the number of employees in the 'Research' department (Q18). Q17: SELECT COUNT (*) FROM EMPLOYEE Q18: SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME='Research’

32 GROUPING In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation Each subgroup of tuples consists of the set of tuples that have the same value for the grouping attribute(s) The function is applied to each subgroup independently SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause

33 GROUPING (cont.) Query 20: For each department, retrieve the department number, the number of employees in the department, and their average salary. Q20: SELECT DNO, COUNT (*), AVG (SALARY) FROM EMPLOYEE GROUP BY DNO In Q20, the EMPLOYEE tuples are divided into groups- Each group having the same value for the grouping attribute DNO The COUNT and AVG functions are applied to each such group of tuples separately The SELECT-clause includes only the grouping attribute and the functions to be applied on each group of tuples A join condition can be used in conjunction with grouping

34

35 GROUPING (cont.) Query 21: For each project, retrieve the project number, project name, and the number of employees who work on that project. Q21: SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME In this case, the grouping and functions are applied after the joining of the two relations

36 THE HAVING-CLAUSE Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain conditions The HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples)

37 THE HAVING-CLAUSE (cont.)
Query 22: For each project on which more than two employees work, retrieve the project number, project name, and the number of employees who work on that project. Q22: SELECT PNUMBER, PNAME, COUNT(*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME HAVING COUNT (*) > 2

38 SUBSTRING COMPARISON The LIKE comparison operator is used to compare partial strings Two reserved characters are used: '%' (or '*' in some implementations) replaces an arbitrary number of characters, and '_' replaces a single arbitrary character

39 SUBSTRING COMPARISON (cont.)
Query 25: Retrieve all employees whose address is in Houston, Texas. Here, the value of the ADDRESS attribute must contain the substring 'Houston,TX‘ in it. Q25: SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX%'

40 SUBSTRING COMPARISON (cont.)
Query 26: Retrieve all employees who were born during the 1950s. Here, '5' must be the 8th character of the string (according to our format for date), so the BDATE value is '_______5_', with each underscore as a place holder for a single arbitrary character. Q26: SELECT FNAME, LNAME FROM EMPLOYEE WHERE BDATE LIKE '_______5_’ The LIKE operator allows us to get around the fact that each value is considered atomic and indivisible Hence, in SQL, character string attribute values are not atomic

41 ARITHMETIC OPERATIONS
The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and division, respectively) can be applied to numeric values in an SQL query result Query 27: Show the effect of giving all employees who work on the 'ProductX' project a 10% raise. Q27: SELECT FNAME, LNAME, 1.1*SALARY FROM EMPLOYEE, WORKS_ON, PROJECT WHERE SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX’

42 ORDER BY The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s) Query 28: Retrieve a list of employees and the projects each works in, ordered by the employee's department, and within each department ordered alphabetically by employee last name. Q28: SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER ORDER BY DNAME, LNAME

43 ORDER BY (cont.) The default order is in ascending order of values
We can specify the keyword DESC if we want a descending order; the keyword ASC can be used to explicitly specify ascending order, even though it is the default.

44 Summary of SQL Queries A query in SQL can consist of up to six clauses, but only the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order: SELECT <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>] [HAVING <group condition>] [ORDER BY <attribute list>]

45 مثال(2) لتكن لدينا خارطة قاعدة البيانات University والتي تحتوي علي الجداول التالية: Students (StdNo, StdName, City) Courses (CNo, CName, SemNo) StdCourses (StdNo, CNo, Score)

46 1 2 OP.SYS CS23 Ali S1 P.L CS25 John S2 DB CS99 Osman S3 S.Methods S90
حالة قاعدة البيانات الحالية علي النحو التالي: SemNo CName CNo Courses City StdName StdNo Student 1 OP.SYS CS23 Kassala Ali S1 P.L CS25 Juba John S2 2 DB CS99 Khartoum Osman S3 S.Methods S90 Medani Abbas S4 group P99 Obaied Ammar S5 complex A55 Omdurman Ahmed S6

47 Score CNo StdNo StdCourse 90 CS23 S1 80 CS99 S2 70 S3 60 CS25 S4 75 S5 S6

48 Query (1): CS23 CS25 P99 Select * from Courses where SemNo = ‘1’
Order by CNo; Result: SemNo CName CNo 1 OP.SYS CS23 P.L CS25 Group P99

49 Query (2): استرجع اسماء الطلاب وأسماء الكورسات فقط للطلاب الذين درجاتهم أعلي من 40 .

50 Select S. StdName ,C. CName
From Students as S, Courses as C , StdCourse as SC Where SC.Score >40 And SC.CNo = C.CNo And SC.StdNo =S.Std.No;

51 Query (3): استرجع اسماء الطلاب وأرقامهم وأرقام كورساتهم والدرجات التي تحصل عليها الطلاب في هذه الكورسات

52 Select S.StdName , S.StdNo ,SC.CNo ,SC.Score
from Students as S, StdCourse as CS where S.StdNo = SC.StdNo;

53 الاستفسارات المتداخلة (Nested Queries ) باستخدام IN و NOT IN)
Query(4): استرجع اسماء كل الطلاب الذين يدرسون الكورس C23 ويدرسون أيضا الكورس C99.

54 Select StdName from Students as S, StdCourses as SC
where CNo = '23' and S.StdNo = SC.StdNo and StdName IN (Select StdName from Students as S, StdCourses as SC where CNo = '99' and S.StdNo = SC.StdNo);

55 Insert Into <table name> values;
يستخدم لاضافة صف جديد للعلاقة Insert Into <table name> values; أمثلة: Insert Into <Students> values ('02-15', 'Osman', '23'); Insert Into <Students> (StdNo, StdName') values ('03-20', 'Ali');

56 يستخدم لحذف صف من العلاقة مثال1: حذف الصف الأول من العلاقة.
الأمر Delete :- يستخدم لحذف صف من العلاقة Delete from <table name> where <condition>; مثال1: Delete from <Students> where StdNo = '96-14'; حذف الصف الأول من العلاقة. Delete from Students; حذف جميع الصفوف بالعلاقة Students

57 الأمر Update :- يستخدم لتعديل بعض القيم في صفوف العلاقة. مثال: Update Students Set ProjectNo = '99' Where StdNo = '96-14';

58 المرئيات Views(virtual tables)
المرئية هي جدول يمكن تكوينه من عدد من الجداول الموجودة في قاعدة البيانات (الجداول القاعدية ) أو المرئيات المعرفة سابقاً وتنشأ باستخدام استفسار. Single table can be derived from other tables (other tables means base tables for DB or previously defined views).

59 GBA Sport college sname S# 3 BB Sc Ali 10 1.5 FB Eng Taha 15 2.5 Zaki
مثال: GBA Sport college sname S# 3 BB Sc Ali 10 1.5 FB Eng Taha 15 2.5 Zaki 20 3.2 Edu Satti 25 TT FMS Fatima 30 Dalia 40 R

60 VDL COMMAND IN SQL إنشاء المرئيات باستخدام أوامر SQL
Create view <viewname> As Select مثال (1):- Create view basket As Select sname ,GBA From R where sport='BB'; RESULT: basket GBA Sname 3 Ali 2.5 zaki

61 مثال(2) : Create view Ws As Select s#,sname ,sport
BB Ali 10 TT Dalia 40 Create view Ws As Select s#,sname ,sport From R where college='sc'; خارطة قاعدة البيانات تحتوى على الجداول القاعدية والمرئيات, وتعامل المرئية كالجداول القاعدية. اى تعامل المرئيات في المثال 1و2 كالجدول القاعدي. يمكن ل ال DBMS ان يحتفظ بالمرئية ((physically حقيقةً أو تبقيها مجرد استفسار وتنشأ حين السؤال عنها .

62 فوائد استخدام المرئيات
1-تستخدم كوسيلة استفسار جاهزة للمستخدمين من غير المبرمجين. 2-لتحسين الأداء (improved of performance) . -كوسيلة تأمين (security) وذلك بإعطاء المستخدم الاعمدة (الصفات) التي يحتاجها لعمله فقط.

63 )updating views تحديث المرئيات (
تحدث الجداول القاعدية ويمكن عكس التحديث على المرئيات بسهولة . إذا أجرينا تحديث على المرئيات (اضافة,حذف,تغيير) ربما لايمكن عكس التحديث بصورة صحيحة على الجداول القاعدية.فهنالك : حالات يمكن فيها تحديث المرئيات وعكس التحديث على الجداول القاعدية. حالات لا يمكن فيها تحديث المرئيات وعكس التحديث على الجداول القاعدية.

64 حالات يمكن فيها تحديث المرئيات وعكس التحديث على الجداول القاعدية:
حينما يحوى تعريف المرئية على الاختيار فقط. مثال:- Create view science as select * from R where college='Sc';

65 حالات الإسقاط والتي تضم المفتاح الاساسي(كالمرئية (ws باعتبار ان S# هو مفتاح العلاقة R ولكن قد تكون هنالك فراغات nulls)) في الجداول القاعدية في حالة الإضافة للمرئية.

66 حالات لا يمكن فيها تحديث المرئيات وعكس التحديث على الجداول القاعدية :
حالات تؤدى إلى نتائج مبهمة (في حالة استخدام الدوال الحسابية أو عمليات المجموعات). T AUB 9 5 4 7 8 6 P Q A 9 5 4 7 B 9 4 8 6 T) عبارة عن مرئية,ماذا يحدث لو اضفنا 2 لهذه المرئية؟ )

67 2-حالات الإسقاط التي لا تحتوي على المفتاح الأساسي.
3-في حالة أن المرئية تكون مكونة نتيجة ربط بين علاقتين او اكثر.


Download ppt "بسم الله الرحمن الرحيم Lecture (10)."

Similar presentations


Ads by Google