1 / 65

بسم الله الرحمن الرحيم

بسم الله الرحمن الرحيم. Lecture (10&11). Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views. لغة الاستفسارات الهيكلية Structured Query Language (SQL). تعتبر اللغة الاساسية لكل قواعد البيانات العلائقية (Standard for Relational DBs)

yazid
Télécharger la présentation

بسم الله الرحمن الرحيم

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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. • CreateSchema <Schema name> Authorization <Owner name>; • Example: • CreateSchema 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. مثال: CreatetableFMS.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) ); CreatetableCourses (CNo varchar(10) Not Null, CName varchar(20) Not Null, Dept varchar(30), UNIQUE (CNAME), Primary key(CNo)); • راجع الـSQL Data Types .

  8. Create Domain: • CreateDomain 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. Default value: • يمكن تحديد Default value للصفة .في حالة عدم تحديد قيمة للصفة في أي صف يتم وضع الـDefault value المحددة للصفة وفي حالة عدم تحديد Default value توضع القيمة Null . • مثلا في تعريف الـCourse table: • Dept varchar(30) default 'Computer' ,

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

  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. Drop Schema: DropSchema FMS Cascade; • مسح الـSchema ومتابعة حذف كل الجداول ، المرئيات ، المجالات وكل القيود الخاصة بالخارطة. • DropSchemaFMSRestrict ; • منع حذف الخارطة إذا كانت تحتوي علي أي جداول (حذف الجداول أولا ثم حذف الخارطة).

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

  15. 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;

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

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

  18. مثال(1) • من الجداول السابقة Student, Project: Query 1: استرجع اسماء وأرقام الطلاب الذين أرقام مشاريعهم أكبر من 90. SELECT StdNo, Stdname FROM Student WHERE Project No>90; Result:

  19. Query 2: استرجع اسماء الطلاب ونوعية مشاريعهم (Parea) إذا كان رقم الطالب 96-14ورقم المشروع 23 . SELECT Stdname, Parea FROM Student, Project StdNoWHERE=‘96-14’ ANDp.No=’23’ AND projectNo = P.No; Result:

  20. يمكن استخدام (.) اذا كانت الصفتين تحملان نفس الاسم في الجدولين مثلا 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;

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

  22. Query (5): SELECT PNo FROM Projects; • يعني هذا الاستفسار استرجاع كل صفوف العمود PNo .

  23. Relational Database Schema--Figure 5.5

  24. 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 where as Q11A does not have any duplicate values Q11: SELECT SALARY FROM EMPLOYEEQ11A: SELECT DISTINCT SALARY FROM EMPLOYEE

  25. 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 eliminatedfrom 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

  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 eliminatedfrom 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 (cont.) • 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 DISTINCT PNUBER FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT DISTINCT PNUBER FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND NAME='Smith'); First select retrieves the projects that involve smiths as a manager of the department that controls the projects.

  28. 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

  29. 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'

  30. 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’

  31. 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

  32. 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

  33. 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

  34. 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)

  35. 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

  36. Read (8.4.5 ,8.5.1, 8.5.2)

  37. 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’

  38. 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

  39. 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.

  40. 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>][GROUPBY <grouping attribute(s)>][HAVING <group condition>][ORDER BY <attribute list>]

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

  42. حالة قاعدة البيانات الحالية علي النحو التالي:

  43. Query (1): Select * from Courses where SemNo = ‘1’ Order by CNo; • Result:

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

  45. 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;

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

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

More Related