Presentation is loading. Please wait.

Presentation is loading. Please wait.

Istanbul Ticaret Universitesi 2009 Veri Tabanı Ders Notları Öğr.Görevlisi Kıvanç Güler.

Similar presentations


Presentation on theme: "Istanbul Ticaret Universitesi 2009 Veri Tabanı Ders Notları Öğr.Görevlisi Kıvanç Güler."— Presentation transcript:

1 Istanbul Ticaret Universitesi 2009 Veri Tabanı Ders Notları Öğr.Görevlisi Kıvanç Güler

2 Istanbul Ticaret Universitesi 2009 I - 2 Ders İçeriği Veritabanı ve ilişkisel veritabanı kavramı,tasarımı ve yönetimini anlamak Veri tabanı sistemlerinin denetimi ve erişimi yöntemlerini ve araçlarını öğrenmek, (SQL komutlarının kullanımı) Verilecek teori bilgiler temelinde VTYS uygulamalarını (Oracle ile) yapmaktır.

3 Istanbul Ticaret Universitesi 2009 I - 3 Data Data: is known recorded facts which has specific meanings or interpretation. Example : the numbers 10.5, 22, and 119 are data Information: is a precise specific representation of data. Example : The temperature of room 119 in building 22 is 10.5, is information Knowledge: is something which is derived or inferred from available information using some level of intelligence. Example : Based on experience, the above information can be used to infer that the room is quite cold and could cause some inconvenience if we work on that room for a long period of time with out wearing worm clothes.

4 Istanbul Ticaret Universitesi 2009 I - 4 Managing Data There are two approaches to manage data File-based approach: An approach that utilizes a collection of application programs which performs services to end-users (e.g. Reports). Each program defines and manages its own data. Database approach: An approach that data is collected and manipulated using specific software called Database Management System, and many programs share this data.

5 Istanbul Ticaret Universitesi 2009 I - 5 Dosya Sistemi Data User 1 User 2 Application programs

6 Istanbul Ticaret Universitesi 2009 I - 6 DOSYA SİSTEMLERİNİN SAKINCALARI Klasik dosya sistemleri kullanılmaya başlandıktan sonra bazı dezavantajları olduğu ortaya çıkmıştır. Bunlar şöyle sıralanabilir : Veri tekrarı: Aynı veri çeşitli dosyalarda birden fazla yer alabilmektedir buda sistemin hantallaşmasına neden olur. Mesela bir stok dosyasında stok numarası verisinin malzeme dosyasında, fatura dosyasında ve ambar girişi dosyasında yer alması gibi. Verinin birkaç dosyada güncellemesi: Veri birden fazla dosyada tekrar edilebildiği için, verinin bir dosyada güncellenip diğerlerinde güncellenmemesi Veri Bütünlüğünün (Data Integrity) bozulmasına neden olabilir. Buna bağlı olarak birbiri ile çelişen raporlar üretilebilir. Belleğin tekrarlı bilgi nedeniyle israfı: Aynı verinin birden fazla dosya içinde bulunması nedeniyle kullanılan veri hard diskte fazla yer işgal edecek. Yani hard disk tekrarlı veriler için kullanılmış olacaktır. Sadece belirli bir dilin kullanılması :Verilerin dosya sisteminde saklandığı ortamlar için değişik programlama dillerinden bir tanesi kullanılır. Kullanılan bu programlama dili ise SQL dili gibi esnek değildir.

7 Istanbul Ticaret Universitesi 2009 I - 7 Database Veri Tabanı Sistemi User 1 User 2 DBMS Application programs Databse programs Veritabanı sistemleri, veri kümelerinin düzenli biçimde tutulduğu ve bu verilerin yazılımlar aracılığı ile yönetildiği ortamlardır.

8 Istanbul Ticaret Universitesi 2009 I - 8 VERİTABANI ve VTYS Veri tabanı Düzenli bilgiler topluluğudur. Bilgisayar ortamında saklanan düzenli verilerdir. Bilgisayar terminolojisinde, sistematik erişim imkanı olan, yönetilebilir, güncellenebilir, taşınabilir, birbirleri arasında tanımlı ilişkiler bulunabilen bilgiler kümesidir. Bilgisayarda sistematik şekilde saklanmış, programlarca işlenebilecek veri yığınıdır VTYS (DBMS) Veri tabanı yönetim sistemleri Veri tabanı tanımlamak, yaratmak, yaşatmak ve veri tabanına denetimli erişim sağlamak için kullanılan yazılım sistemidir.

9 Istanbul Ticaret Universitesi 2009 I - 9 Database A database is a collection of inter-related data, and it has the following implicit properties: A database represents some aspects of the real world, sometimes called the miniworld. A database is a logically coherent collection of data with some inherent meaning. A database is designed, built, and populated with data for specific purpose. Examples University database

10 Istanbul Ticaret Universitesi 2009 I - 10 Database Management System (DBMS) DBMS is a software package that enables user to create and maintain databases. It facilitates: Defining a database that involves specifying the data types, structures, and constraints for the data to be stored in the database. Constructing a database which is the process of storing the data. Manipulating a database such as functions of querying the database, updating the database, and generating reports from the data. Example of DBMS: Oracle, Access, DB2, Ingress, Teradata,Sysbase Database and DBMS software together constitute a database system.

11 Istanbul Ticaret Universitesi 2009 I - 11 Veri Tabanı Sistemini Avantajları Verinin tekrarlanmasını önler. Veritabanı sistemleri alt sistemler arasında ilişki kurulması ve birçok uygulamada verilerin aynı veritabanı içersinde ortak olarak tasarlanmasını öngörür. Verilerin tutarlı olmasını sağlar. Veri bütünlüğü(data integrity), verinin doğruluğunu ve tutarlığını ifade etmektedir. Veri girişlerine kısıtlar konularak sadece istenilen aralıkta değer girişi sağlanabilir. Aynı andaki erişimlerde tutarsızlıkların ortaya çıkmasını önler. Veritabanı uygulamalarında, veritabanı nesneleri başka uygulamalar ve farklı kullanıcılar tarafından paylaşılabilir. Verilerin güvenliğini sağlar. Her kullanıcının erişeceği veriler ayrı ayrı tanımlanabilir. Yetkiler ve kısıtlamalar ile istenilen kullanıcı erişim ayarları gerçekleştirilir.

12 Istanbul Ticaret Universitesi 2009 I - 12 Advantages of Using DBMS … Controlling redundancy: A DBMS has capacity of controlling redundancy that leads to prevent inconsistency and waste of storage. Providing data consistency: A DBMS provides and assures the consistency of stored data. Enabling sharing of data: A DBMS is designed to enable many users to share the same stored data. Supporting multiple views of the same stored data: A DBMS provides multiple views for different users from the available stored data. Restricting unauthorized access: A DBMS provides a security and authorization subsystem, which DBA uses to create accounts and specify account restrictions that are then enforced by the DBMS automatically.

13 Istanbul Ticaret Universitesi 2009 I - 13 Advantages of Using DBMS … Providing multiple user interfaces: A DBMS provides a variety of user interfaces for users with varying levels of technical knowledge to use a database. Presenting complex relationships among data: A database may include numerous varieties of data that are inter-related in many ways. A DBMS has the capability to representing a variety of complex relationships among the data as well as to retrieve and update related data easily and efficiently. Enforcing integrity constraints: Most databases has certain integrity constraints that must hold for the data. A DBMS provides capabilities for defining and enforcing these constraints. Providing backup and recovery: A DBMS provides facilities for recovering from hardware or software failures. The backup and recovery subsystem of the DBMS is responsible for recovery.

14 Istanbul Ticaret Universitesi 2009 I - 14 Advantages of Using DBMS … Potential for enforcing standards: In the database approach, the DBA defines standards and the DBMS enforces these standards among database users in a large organization. Reduces application development time: Application development time using a DBMS is estimated to be one-sixth to one-fourth of that for file-based approach. Flexibility: Modern DBMS allow certain types of changes to the structure of the database without affecting the stored data and the existing application programs. Availability of up-to-date information: A DBMS makes the database available to multiple users. As soon as one user’s update is applied to the database, all other users can immediately see this update. Economies of Scale: The DBMS approach permits consolidation of data and applications, thus reducing the amount of wasteful overlap between activities of data processing personnel in different projects or departments.

15 Istanbul Ticaret Universitesi 2009 I - 15 June 29, 2016DB: Relational Data Model 15 8 - Terminology A relation is a table (logical) with columns and rows. An attribute is a named column of a relation. A domain is a set of allowable values for one or more attributes. A tuple is a row of a relation. Degree is a number of attributes in a relation. Cardinality is a number of tuples in a relation. Relational Database is a collection of relations.

16 Istanbul Ticaret Universitesi 2009 I - 16 ID NAME NAT_ID DOB DEPTCODE 201111 KHALED 1111111111 16-05-1984 ICS 202222 ADEL 2222222222 23-09-1984 COE 203333 AHMED 3333333333 11-08-1984 COE 211111 HASSAN 4444444444 23-10-1985 SWE 204444 MUSTAFA 55555555555 16-11-1984 ICS - Terminology Tuples STUDENT Attributes Relation name Degree Cardinality

17 Istanbul Ticaret Universitesi 2009 I - 17 Varlık-İlişki Modeli (The Entity-Relationship Model) Veri çözümleme ve modellemede ilişkilerin ortayakonması için kullanılan araçtır. Varlık (Entity): Bir alan içersinde diğer nesnelerden ayırt edilebilen bir şey (“thing”) yada “nesne” (“object”) Niteliklerin kümesi (set of attributes) tarafından tanımlanır. İlişki (Relationship): Birden fazla varlığın arasındaki bağıntı-ilişki. Görsel olarak varlık-ilişki tablosu ile gösterilir: Locations DEPARTMENT Name Number Manager ManagerStartDate

18 Istanbul Ticaret Universitesi 2009 I - 18 Varlık-İlişki Modeli Kavramlar Varlık(Entity): Var olan ve diğer varlıklardan ayırt edilebilen nesnedir. (Bir kitap, öğrenci, veritabanı dersi birer varlıktır. Varlık Dizisi: Aynı türdeki varlıklar varlık kümesini oluştururlar. Bir okuldaki tüm öğrenciler “öğrenci” isimli varlık kümesi olarak değerlendirilir. Varlıklar arasındaki bağlantıya ilişki adı verilir. örneğin Öğretmen varlığı ile “Dersler” varlığı arasından ilişki vardır. Bir varlık çok sayıda nitelik yardımıyla tanımlanabilir. Örneğin, personel varlığının nitelikleri şu şekilde olabilir: –Personel No –Adı ve Soyadı –Adres –SSK no –Gelir Niteliğin aldığı değerlere etki alanı(domain) adı verilir. Bir nitelik kullanılarak, bir başka varlık nitelik elde edilebiliyorsa bu yeni niteliğe “türetilen nitelik” adı verilir. Örneğin personel varlığının “doğum tarihi” niteliğinden yararlanılarak “yaş” niteliği elde edilebilir.

19 Istanbul Ticaret Universitesi 2009 I - 19 -- Entity Types A database usually contains groups of entities that are similar. Example: A company employing many employees stores similar information about each employee. Entity type: is a collection (or set) of entities that have the same attributes. Example 1: Entity type EMPLOYEE has attributes such as –Name –DOB –Salary Example 2: Entity type COMPANY has attributes such as –Name –Headquarters –President

20 Istanbul Ticaret Universitesi 2009 I - 20 BİRİNCİL VE YABANCI ANAHTAR Birincil Anahtar(Primary Key) : Üzerinde işlem yapılan tabloya ait kayıtları benzersiz olarak tanımlayan alanlardır. Örneğin bir okulu ele alalım burda öğrencileri benzersiz biçimde tanımlayabilen en önemli öge şüphesiz ki ögrenci numarasıdır.Bir okulda,isim,soyisim gibi kimilik bilgilerl aynı olabilecek bir çok öğrenci mevcut olabilir fakat,hiç bir öğrencinin, o öğrenciyi tanımlayan, öğrenci numarası aynı olamaz benzer bir mantık ile telefon numaraları da düşünülebilir. Yabancı Anahtarlar(Foreign Keys) : Tablo içerisindeki verilerin birbirleri ile iletişim kurabilmeleri amacı ile kullanılan benzersiz olması gerekmeyen alanlardır. Örneğin içerisinde "Ogrenci_No" birincil anahtarını barındıran "Ogrenciler" isimli tablonun var olduğunu varsayalım ayrıca "Notlar" isimli bir tablonun içerisinde, aynı "Ogrenci_No" alanını çesitli defalar yabancı anahtar olarak kullanmamız gerekebilir (Çünkü, genellikle bir öğrencinin birden fazla dersi ve dolayısıyla "Notlar" isimli tabloya işlenmesi gereken birden fazla sınav notu olacaktır.) Bağımsız tablolarda bu şekilde organize edilmiş veriye "ilişkisel(Relational)" bu veriyi içeren veritabanına ise "ilişkisel veritabanı" ismi verilir.Veritabanlarındaki verinin okunması ve yönetilmesi için kullanılan ortak sorgulama diline Yapısal Sorgulama Dili (Structured Query Language (SQL) ) denir.

21 Istanbul Ticaret Universitesi 2009 I - 21

22 Istanbul Ticaret Universitesi 2009 I - 22 -- ER Diagrams for Entities and Attributes ER diagrams are used to represent entity types, attributes of these types and the relationship between them. In an ER diagram, an entity type is represented by a rectangular box enclosing the entity name. Attribute names are enclosed in ovals and they are attached to their entity type by a strait line. Composite attributes are attached to their attributes by straight lines. Multi-valued attributes are enclosed by double ovals. Key attributes of an entity are underlined in the ER diagram PhoneEMPLOYEE Name F. name M. Init L. name SSN Age

23 Istanbul Ticaret Universitesi 2009 I - 23 - Initial Conceptual design for the Company Database … From the requirements of the company DB we can identify the following entities: DEPARTMENT PROJECT EMPLOYEE DEPENDENT In the next few slides, we will show how the above four entities together with their attributes are represented using ER diagram.

24 Istanbul Ticaret Universitesi 2009 I - 24 -- DEPARTMENT Entity Representation An entity type DEPARTMENT has attributes: Name (key) Number (key) Locations (multi-valued attribute) Manager and ManagerStartDate. Locations DEPARTMENT Name Number Manager ManagerStartDate

25 Istanbul Ticaret Universitesi 2009 I - 25 -- PROJECT Entity Representation An entity type PROJECT has attributes: Name (key) Number (key) location ControllingDepartment Location PROJECT Name Number ControllingDepartment

26 Istanbul Ticaret Universitesi 2009 I - 26 -- EMPLOYEE Entity Representation Entity Representation: An entity type EMPLOYEE with attributes: Name, SSN, Address, Salary, BirthDate, Department, Supervisor, and WorksOn. WorksOn is multi-valued composite attribute (project, Hours). SSN is the key attribute. Both name and address can be composite attributes. BirthDate EMPLOYEE Name M. Init L. name SSN F. name Supervisor Works_On Department Sex Address Project Hours Salary

27 Istanbul Ticaret Universitesi 2009 I - 27 -- DEPENDENT Entity Representation An entity type DEPENDENT has attributes: Employee DependentName Sex BirthDate Relationship DEPENDENT Employee Sex BirthDate DependentName

28 Istanbul Ticaret Universitesi 2009 I - 28 - Relationships Introduction to Relationship Types + Relationship types and Instances + Role names and Relation types + Role names and Recursive Relationship types + Constraints on Relationship Types + Attributes of Relationship Types + Relationship Representation in ER Diagram + Higher Degree Relationships + Examples +

29 Istanbul Ticaret Universitesi 2009 I - 29 -- Introduction to Relationship Type By reviewing the initial design of the COMPANY DB example we can see the following: Some attributes of an entity reference other attributes in the same or other entities. For example, The attribute Department of the EMPLOYEE entity type refers to the DEPARTMENT entity that the employee works for.EMPLOYEE These are implicit relationships that exist between entity types. A better representation will be obtained if these are represented as relationships between the entity types rather than linking attributes. Here we will describe another major component of ER model; namely relationships. We will discuss relationship types, instances, degrees, and constraints on relationships.

30 Istanbul Ticaret Universitesi 2009 I - 30 … -- Relationship Types and Instances For example, lets look ate the relationship type WORKS_FOR between the two entities EMPLOYEE and DEPARTMENT, which associates each employee with the department he works for. Each relationship instance in the relationship set WORKS_FOR associates one EMPLOYEE entity and one DEPARTMENT entity as shown in the figure below.

31 Istanbul Ticaret Universitesi 2009 I - 31 -- Role Names and Relation Types Each entity type that participates in a relationship type plays a particular role in the relationship. For example, in the WORKS_FOR relationship type, EMPLOYEE plays the role of employee or worker and DEPARTMENT plays the role of department. In most of the cases, the name of the entity type can be used as the role name of that entity type in the relationship type it participates in, a shown in the previous example.previous example

32 Istanbul Ticaret Universitesi 2009 I - 32 -- Role Names and Recursive Relations … In some cases, the same entity type participates more than once in a relationship roles. In such cases the role name becomes essential for distinguishing the meaning of each participation. Such relationship type are called recursive relationships. For example, the SUPERVISOR relationship type relates an employee to a supervisor, and both belongs to the EMPLOYEE entity type, as shown in this figure.this figure

33 Istanbul Ticaret Universitesi 2009 I - 33 … -- Role Names and Recursive Relations e 1 e 2 e 3 e 4 e 5 e 6 e 7 EMPLOYEE r1r2r3r4r5r6r1r2r3r4r5r6 WORKS_FOR 2 1 1 2 2 1 1 1 2 1 2 2 1: Supervises 2: Supervised

34 Istanbul Ticaret Universitesi 2009 I - 34 … -- Role Names and Recursive Relations EMPLOYEESUPERVISION e1 e2 e3 e4 e5 … … r1 r2 r3 r4 … … … 1 1 1 1 2 2 2 2 1: Supervises 2: Supervised

35 Istanbul Ticaret Universitesi 2009 I - 35 -- Constraints on Relationship Types Relationship types usually have some constraints that limit the possible combination of entities that may participate in the corresponding relationship set. These constraints are obtained from the mini-world situation that the relationship represents. For example, if we have a rule in the COMPANY stating that an employee can work for one department only, then we should be able to represent this constraint. Two main types of restrictions on relationships are: cardinality and Participation

36 Istanbul Ticaret Universitesi 2009 I - 36 --- Cardinality (Ratio) Constraints Determines the number of possible relationships for each participating entity. For example, in the relationship type WORKS_FOR, the cardinality ratio of DEPARTMENT:EMPLOYEE is 1:N, meaning that each department can be related to many employees but an employee can be related to only one department. Most common degree for relationships is binary with cardinality ratios of one-to-one (1:1), one-to-many (1:n), or many-to-many (N:M).

37 Istanbul Ticaret Universitesi 2009 I - 37 ---- One-to-many(1:N) or Many-to-one (N:1) RELATIONSHIP e 1 e 2 e 3 e 4 e 5 e 6 e 7 EMPLOYEE r1r2r3r4r5r6r7r1r2r3r4r5r6r7 WORKS_FOR d 1 d 2 d 3 DEPARTMENT

38 Istanbul Ticaret Universitesi 2009 I - 38 --- Participation Constraints Determines whether the existence of an entity depends on its being related to another entity through the relationship. An entity is either totally or partially participating in a relationship. For example, if the company policy states that each employee entity can exist only if it participates in a WORKS_FOR relationship instance. Thus, the participation of the employee entity in the relationship WORKS_FOR is total. Total participation is also called existence dependency. However, only some employees manage departments in the company. Therefore, we say that the participation of the EMPLOYEE entity in the relationship MANAGES is partial.

39 Istanbul Ticaret Universitesi 2009 I - 39 ---- Example of Partial/Total Relationship EMPLOYEE MANAGES e1 e2 e3 e4 e5 … … r1 r2 r3 … … … d1 d2 d3 … … DEPARTMENT

40 Istanbul Ticaret Universitesi 2009 I - 40 -- Attributes of Relationship Types Relationship types can have their own attributes similar to the entity types. For example, to record the number of hours per week that an employee works on a particular project, we can include an attribute Hours for the relationship type WORK_ON between EMPLOYEE and PROJECT entity types. Another Example, is to include the date on which a manager starts managing a department via an attribute StartDate for the relationship type MANAGES between EMPLOYEE and DEPARTMENT entity types.

41 Istanbul Ticaret Universitesi 2009 I - 41 -- Relationship Representation in ER Diagram Relationship types can have their own attributes similar to the entity types. For example, to record the number of hours per week that an employee works on particular object, we can include an attribute Hours for the relationship type WORK_ON between EMPLOYEE and PROJECT entity types. Another example, is to include the date on which a manager starts managing a department via an attribute StartDate for the relationship type MANAGES between EMPLOYEE and DEPARTMENT entity types. EMPLOYEE MANAGES DEPARTMENT StartDate 11

42 Istanbul Ticaret Universitesi 2009 I - 42 -- Higher Degree Relationships In many instances, it is required to represent relationship that is of a degree higher than 2 (HD), i.e. it involves more than two entity types. Sometime these relationships can be represented using binary relations, although sometime this may not give the same meaning. For example the tuple (s, p, j) which states that SUPPLIER s supplies PART p to PROJECT j may not be expressed by the three tuples (s,p), (s,j) and (p,j).

43 Istanbul Ticaret Universitesi 2009 I - 43 --- Example: Higher Degree Relationships

44 Istanbul Ticaret Universitesi 2009 I - 44 -- Examples Example of Participation Constraint Partial/Total Relationship Examples of Cardinality Constraint One-to-One One-to-Many Many-to-Many

45 Istanbul Ticaret Universitesi 2009 I - 45 --- Partial/Total Relationship EMPLOYEE MANAGES e1 e2 e3 e4 e5 r1 r2 r3 d1 d2 d3 DEPARTMENT EMPLOYEE MANAGES DEPARTMENT StartDate 11 Partial participation Total participation

46 Istanbul Ticaret Universitesi 2009 I - 46 ---- One-to-One (1:1) Relationship EMPLOYEE WORKD_FOR e1 e2 e3 e4 e5 r1 r2 r3 r4 r5 d1 d2 d3 DEPARTMENT EMPLOYEE WORKS_FOR DEPARTMENT 11 Cardinality is 1:1 d4 d5

47 Istanbul Ticaret Universitesi 2009 I - 47 ---- One-to-many(1:N) or Many-to-one (N:1) Relationship EMPLOYEE WORKD_FOR e1 e2 e3 e4 e5 r1 r2 r3 r4 r5 d1 d2 d3 DEPARTMENT EMPLOYEE WORKS_FOR DEPARTMENT N1 Cardinality is N:1

48 Istanbul Ticaret Universitesi 2009 I - 48 ---- Many-to-many (M:N) or Many-to-Many (N:M) Relationship EMPLOYEE WORKD_FOR e1 e2 e3 e4 r1 r2 r3 r4 r5 d1 d2 d3 DEPARTMENT EMPLOYEE WORKS_FOR DEPARTMENT MN Cardinality is M:N

49 Istanbul Ticaret Universitesi 2009 I - 49 - Refining The ER Diagram for the COMPANY Database … Now we can refine the initial design of the COMPANY database using concepts of relationships that were introduced in the previous sections. Revision will be made by placing the attributes that represent relationships into relationship types. The cardinality ratio and participation constraints of each relationship type are determined from the initial requirements. If not stated then they should be obtained from the user. In the COMPANY example we can determine the following relationship type:

50 Istanbul Ticaret Universitesi 2009 I - 50 … - Refining The ER Diagram for the COMPANY Database … MANAGES: A 1:1 relationship type between EMPLOYEE and DEPARTMENT. EMPLOYEE participation is partial. The participation of DEPARTMENT is total. The attribute StartDate is assigned to the relationship type. WORKS_FOR: A 1:N relationship type between EMPLOYEE and DEPARTMENT. Both participations are total. CONTROLS: A 1:N relationship type between DEPARTMENT and PROJECT. The participation of PROJECT is total. The participation of DEPARTMENT is partial (was known after consulting with users.

51 Istanbul Ticaret Universitesi 2009 I - 51 … - Refining The ER Diagram for the COMPANY Database … SUPREVISION: A 1:N relationship type between EMPLOYEE (in supervisor role) and EMPLOYEE (in supervisee role). Both participations are partial, determined after consulting users. WORKS_ON: An M:N relationship type between EMPLOYEE and PROJECT. Both participations are total. The attribute hours is added to the relationship type. DEPENDENTS_OF: An 1:N relationship type between EMPLOYEE and DEPENDENT. The participation of EMPLOYEE (the identifying entity) is partial The participation of DEPENDENT (the weak entity) is total.

52 Istanbul Ticaret Universitesi 2009 I - 52 … - Refining The ER Diagram for the COMPANY Database … Now after specifying the above six relationship types, we need to remove all the attributes that has been refined from the initial conceptual design. These include removing: Manager and ManagerStartDate from DEPARTMENT. ControllingDepartment from PROJECT. Department, Supervisor, and WorksOn from EMPLOYEE. Employee from DEPENDENT The final design of the COMPANY database is shown in the following ER diagram.

53 Istanbul Ticaret Universitesi 2009 I - 53 ---The E-R Model representation of the COMPANY Database

54 Istanbul Ticaret Universitesi 2009 I - 54 - Summary of ER Diagram Notations … Entity types, such as EMPLOYEE, are shown in rectangular boxes. Relationship types, such as MANAGES, are shown in diamond- shaped boxes attached with straight lines to the participating entity types. Attributes such as Name, are shown in ovals and each attribute is attached by straight line to its entity type relationship type. Component attributes of a composite attribute, such as address, are shown in ovals are attached with straight lines to the oval of the composite attribute.

55 Istanbul Ticaret Universitesi 2009 I - 55 - … Summary of ER Diagram Notations … Multi-valued attributes, such as Locations of departments, are shown in double ovals. Derived attributes, such as NumberOfEmployees of a department, are shown in dotted ovals. Key attributes, such as Name of a department, have their names underlined. Weak entity types, such as DEPENDENT, are distinguished by being placed in double rectangles and by having their identifying relationship type placed in double diamonds. The partial key of the weak entity type is dashed underlined,

56 Istanbul Ticaret Universitesi 2009 I - 56 - … Summary of ER Diagram Notations The cardinality ratio of each binary relations, such as WORKS_FOR, is specified by placing a 1, M or N on each participating edge. The participation constraint is specified by a single line for partial participation and double lines for total participation. For recursive relationship type, such as SUPERVISION, the different role names of the entity type are placed on the different edges of the relationship type.

57 Istanbul Ticaret Universitesi 2009 I - 57 -- Summary of ER diagram notation.

58 Istanbul Ticaret Universitesi 2009 June 29, 2016Databases: SQL58 Structured Query Language - SQL

59 Istanbul Ticaret Universitesi 2009 I - 59 June 29, 2016Databases: SQL 59 Objectives Example Tables + Introduction + ISO SQL Data Types + Comparison Operators in SQL + Logical Operators in SQL + Arithmetic Operators in SQL + SQL Schema and Catalog + SQL Data Definition Statements (DDL) + SQL Data Manipulation Statements (DML) + Other SQL Operators +

60 Istanbul Ticaret Universitesi 2009 I - 60 June 29, 2016Databases: SQL 60 --- Example Table … Car_Sales CityYearCars_sold Dhahran2001525 Dhahran2002456 Riyadh2001700 Riyadh2002654 Jeddah2001921 Jeddah2002752 Khobar2002

61 Istanbul Ticaret Universitesi 2009 I - 61 June 29, 2016Databases: SQL 61 … --- Example: Tables 1 2 3 ICS COE SWE dno dname Lid Lnamednosalary 1 2 3 4 5 6 7 Ahmed Amin Hani Abdallah Ageel Yousef Khalid 1 2 1 1 2 2 4000 3700 4200 4300 4000 3500 4500 Departments Lecturers

62 Istanbul Ticaret Universitesi 2009 I - 62 June 29, 2016Databases: SQL 62 - Introduction Objectives of SQL + History of SQL + Importance of SQL + Components of SQL + Basic Guidelines for Writing SQL Statements +

63 Istanbul Ticaret Universitesi 2009 I - 63 June 29, 2016Databases: SQL 63 -- Objectives of SQL … Ideally, database language should allow user to: create the database and relation structures; perform insertion, modification, deletion of data from relations; perform simple and complex queries. Must perform these tasks with minimal user effort and command structure and syntax must be easy to learn. It must be portable. SQL does not contain flow control commands. These must be implemented using a programming or job-control language, or interactively by the decisions of the user.

64 Istanbul Ticaret Universitesi 2009 I - 64 June 29, 2016Databases: SQL 64 … -- Objectives of SQL … SQL is relatively easy to learn: It is a non-procedural language - you specify what information you require, rather than how to get it. It is essentially free-format. Can be used by a range of users including DBAs, management, application programmers, and other types of end users. An ISO standard now exists for SQL, making it both the formal and de facto standard language for relational databases.

65 Istanbul Ticaret Universitesi 2009 I - 65 June 29, 2016Databases: SQL 65 … -- Objectives of SQL Consists of standard English words: CREATE TABLE staff( sno VARCHAR(5), lname VARCHAR(15), salary NUMBER(7,2) ); INSERT INTO staff VALUES ('SG16', 'Brown', 8300); SELECT sno, lname, salary FROM staff WHERE salary > 10000;

66 Istanbul Ticaret Universitesi 2009 I - 66 June 29, 2016Databases: SQL 66 -- History of SQL … In 1974, D. Chamberlin (IBM San Jose Laboratory) defined language called 'Structured English Query Language' or SEQUEL. A revised version SEQUEL/2 was defined in 1976 but name was subsequently changed to SQL for legal reasons. Still pronounced 'see-quel', though official pronunciation is 's-q-l'. IBM subsequently produced a prototype DBMS called System R, based on SEQUEL/2. Roots of SQL, however, are in SQUARE (Specifying Queries as Relational Expressions), which predates System R project.

67 Istanbul Ticaret Universitesi 2009 I - 67 June 29, 2016Databases: SQL 67 … -- History of SQL In late 70s, ORACLE appeared and was probably first commercial RDBMS based on SQL. In 1987, ANSI and ISO published an initial standard for SQL. In 1989, ISO published an addendum that defined an 'Integrity Enhancement Feature'. In 1992, first major revision to ISO standard occurred, referred to as SQL2 or SQL/92.

68 Istanbul Ticaret Universitesi 2009 I - 68 June 29, 2016Databases: SQL 68 -- Importance of SQL … SQL has become part of application architectures such as IBM's Systems Application Architecture (SAA). It is strategic choice of many large and influential organizations (e.g. X/OPEN). SQL is Federal Information Processing Standard (FIPS) to which conformance is required for all sales of databases to American Government.

69 Istanbul Ticaret Universitesi 2009 I - 69 June 29, 2016Databases: SQL 69 … -- Importance of SQL SQL Access Group trying to define enhancements that will support interoperability across disparate systems. SQL is used in other standards and even influences development of other standards as a definitional tool. Examples include: ISO's Information Resource Directory System (IRDS) Standard Remote Data Access (RDA) Standard.

70 Istanbul Ticaret Universitesi 2009 I - 70 June 29, 2016Databases: SQL 70 -- Components of SQL A database language must have support for the components listed below. Most implementations of SQL support various components listed below: Data Definition Language (DDL) Interactive Data Manipulation Language (Interactive DML) Embedded Data Manipulation Language (Embedded DML) Views Integrity and transaction control Authorization Catalog and dictionary facility.

71 Istanbul Ticaret Universitesi 2009 I - 71 June 29, 2016Databases: SQL 71 -- Basic Guidelines for Writing SQL Statements … SQL statement consists of reserved words and user-defined words. Reserved words are a fixed part of SQL and must be spelt exactly as required and cannot be split across lines. User-defined words are made up by user and represent names of various database objects such as relations, columns, views. Most components of an SQL statement are case insensitive, except for literal character data. More readable with indentation and lineation: Each clause should begin on a new line. Start of a clause should line up with start of other clauses. If clause has several parts, should each appear on a separate line and be indented under start of clause.

72 Istanbul Ticaret Universitesi 2009 I - 72 June 29, 2016Databases: SQL 72 … -- Basic Guidelines for Writing SQL Statements Use extended form of BNF notation: Upper case letters represent reserved words. Lower case letters represent user-defined words. | indicates a choice among alternatives. Curly braces indicate a required element. Square brackets indicate an optional element. … indicates optional repetition (0 or more).

73 Istanbul Ticaret Universitesi 2009 I - 73 June 29, 2016Databases: SQL 73 - ISO SQL Data Types

74 Istanbul Ticaret Universitesi 2009 I - 74 June 29, 2016Databases: SQL 74 - Comparison Operators in SQL + There are six comparison operators in SQL. These operators are used to build conditions that are used in the WHERE clause of a DML statement: Operator Meaning = <> < > <= >= Equal Not Equal Less than Greater than Less than or Eqaul Greater than or Eqaul

75 Istanbul Ticaret Universitesi 2009 I - 75 June 29, 2016Databases: SQL 75 - Logical Operators in SQL There are three logical operators that help us to build compound conditions to be used in the WHERE clause of the SELECT statement. The AND operator joins two or more conditions, and display a row only if that row’s data satisfies ALL the specified conditions. The OR operator joins two or more conditions, and display a row only if that row’s data satisfies any of the specified conditions. The NOT is a unary operator, and is used to negates a condition.

76 Istanbul Ticaret Universitesi 2009 I - 76 June 29, 2016Databases: SQL 76 - Arithmetic Operators in SQL Another feature of SQL allows the use of arithmetic in queries. The standard arithmetic operators ( +, -, /, *) can be applied to numeric values or attributes with numeric domain. The arithmetic operators can be used in expressions in the SELECT and the WHERE clauses to compute numeric values. All attributes that can be computed using arithmetic expressions (such as age from birth date, annual salary from monthly salary) must be eliminated as part of a good design practice in databases.

77 Istanbul Ticaret Universitesi 2009 I - 77 June 29, 2016Databases: SQL 77 - SQL Schema and Catalog In SQL92, relations and other database objects exist in an environment. Each environment contains one or more catalogs, and each catalog consists of set of schemas. Schema is a named collection of related database objects. Objects in a schema can be tables, views, domains, constraints, translations, and character sets. All have same owner.

78 Istanbul Ticaret Universitesi 2009 I - 78 June 29, 2016Databases: SQL 78 - SQL Data Definition Statements (DDL) CREATE SCHEMA and DROP SCEHMA + CREATE TABLE + ALTER TABLE + DROP TABLE +

79 Istanbul Ticaret Universitesi 2009 I - 79 June 29, 2016Databases: SQL 79 -- CREATE SCHEMA and DROP SCHEMA CREATE SCHEMA [name| AUTHORIZATION creator_id ]; Example : CREATE USER COMPANY IDENTIFIED BY password; DROP SCHEMA name [RESTRICT | CASCADE ]; Example : DROP USER COMPANY CASCADE; With RESTRICT (default), schema must be empty or operation fails. With CASCADE, operation cascades to drop all objects associated with schema in the order defined above. If any of these operations fail, DROP SCHEMA fails.

80 Istanbul Ticaret Universitesi 2009 I - 80 June 29, 2016Databases: SQL 80 -- CREATE TABLE CREATE TABLE table_name (col_name data_type [NULL | NOT NULL] [,...]); Creates a table with one or more columns of the specified data_type. NULL (default) indicates whether column can contain nulls. With NOT NULL, system rejects any attempt to insert a null in the column. Primary keys should always be specified as NOT NULL. Foreign keys are often (but not always) candidates for NOT NULL.

81 Istanbul Ticaret Universitesi 2009 I - 81 June 29, 2016Databases: SQL 81 --- CREATE TABLE – Example 1 CREATE TABLE Employee ( fname VARCHAR2(15)NOT NULL,minitCHAR,lnameVARCHAR2(15)NOT NULL,ssnCHAR(9),bdateDATE,addressVARCHAR2(50),sexCHAR,salaryNUMBER(10,2) NOT NULL,SuperssnCHAR(9),dnoNUMBER(3) NOT NULL,CONSTRAINT employee_ssn_pk PRIMARY KEY(ssn),CONSTRAINT employee_superssn_fk FOREIGN KEY(Superssn) REFERENCES employee(ssn),CONSTRAINT employee_dno_fk FOREIGN KEY(dno) REFERENCES department(dnumber) );

82 Istanbul Ticaret Universitesi 2009 I - 82 June 29, 2016Databases: SQL 82 --- CREATE TABLE – Example 2 CREATE TABLE department ( dnameVARCHAR2(15)NOT NULL,dnumber NUMBER(3)NOT NULL,mgrssnCHAR(9),mgrStartDateDATE,CONSTRAINT department_dnumber_pk PRIMARY KEY(dnumber),CONSTRAINT department_mgrssn_fk FOREIGN KEY(mgrssn) REFERENCES employee(ssn) );

83 Istanbul Ticaret Universitesi 2009 I - 83 June 29, 2016Databases: SQL 83 -- DROP TABLE DROP TABLE tbl_name [RESTRICT | CASCADE] e.g.DROP TABLE employee; Removes named table and all rows within it. With RESTRICT, if any other objects depend for their existence on continued existence of this table, SQL does not allow request. With CASCADE, SQL drops all dependent objects (and objects dependent on these objects).

84 Istanbul Ticaret Universitesi 2009 I - 84 June 29, 2016Databases: SQL 84 -- ALTER TABLE The ALTER command is a schema modification command. It is used to add or drop a column, change a column definition, add or drop table constraints. Example: ALTER TABLE COMPANY.EMPLOYEE MODIFY(lname VARCHAR2(30));

85 Istanbul Ticaret Universitesi 2009 I - 85 June 29, 2016Databases: SQL 85 - SQL Data Manipulation Statements (DML) INSERT Statement + UPDATE Statement + DELETE Statement +

86 Istanbul Ticaret Universitesi 2009 I - 86 June 29, 2016Databases: SQL 86 -- INSERT Statement Definition of INSERT Statement + Types of INSERT Statement + INSERT and Integrity Constraints +

87 Istanbul Ticaret Universitesi 2009 I - 87 June 29, 2016Databases: SQL 87 -- Definition of INSERT Statement INSERT is used to add a single row to a table where we specify the relation name and a list of values for the row. There are three types of INSERT Statement: INSERT With Column list + INSERT Without Column list + INSERT with SELECT Statement +

88 Istanbul Ticaret Universitesi 2009 I - 88 June 29, 2016Databases: SQL 88 --- INSERT with Column list INSERT INTO table_name (column_list) VALUES (data_value_list); Example: INSERT INTO employee(fname, lname, ssn, salary, dno) VALUES (‘Majid', ‘Al-Ghamdi', ‘1111111', 4000, 123); data_value_list must match column_list as follows: Number of items in each list must be the same. Must be direct correspondence in position of items in two lists. Data type of each item in data_value_list must be compatible with data type of corresponding column. If one of the table columns is omitted from the column_list It must also be omitted from the data_value_list and make sure it is nullable.

89 Istanbul Ticaret Universitesi 2009 I - 89 June 29, 2016Databases: SQL 89 --- INSERT without Colum List INSERT INTO table_name VALUES (data_value_list); Example: INSERT INTO employee VALUES (‘Adel', NULL, ‘Al-Eid', ‘222222’, NULL, NULL, NULL, NULL, NULL, 1); data_value_list must match the columns of the table as follows: Number of items in the list must be equal to the number of columns of the table. Data type of corresponding items must be compatible.

90 Istanbul Ticaret Universitesi 2009 I - 90 June 29, 2016Databases: SQL 90 --- INSERT … SELECT Second form of INSERT allows multiple rows to be copied from one or more tables to another: INSERT INTO table_name [ (column_list) ] SELECT... Example: INSERT INTO Table1 (A1, A2, A3) SELECT B1, B2, B3 FROM Table2;

91 Istanbul Ticaret Universitesi 2009 I - 91 June 29, 2016Databases: SQL 91 --- INSERT and Integrity Constraints A DBMS that fully implement SQL2 should support and enforce all the integrity constraints that can be specified in the DDL. A DBMS enforcing NOT NULL will reject an INSERT command in which an attribute declared to be NOT NULL does not have a value. A DBMS not supporting referential integrity will allow insertion even if the referential integrity constraint is violated.

92 Istanbul Ticaret Universitesi 2009 I - 92 June 29, 2016Databases: SQL 92 -- UPDATE Definition + Examples Update All Rows + Update Specific Rows + Update Multiple Columns +

93 Istanbul Ticaret Universitesi 2009 I - 93 June 29, 2016Databases: SQL 93 --- UPDATE Definition … The UPDATE command is used to modify attribute values of one or more selected rows. UPDATE table_name SET column_name1 = data_value1 [, column_name2 = data_value2...] [WHERE search_condition] table_name can be name of a base table or an updatable view. SET clause specifies names of one or more columns that are to be updated.

94 Istanbul Ticaret Universitesi 2009 I - 94 June 29, 2016Databases: SQL 94 … --- UPDATE Definition WHERE clause is optional: If omitted, named columns are updated for all rows in table. If specified, only those rows that satisfy search_condition are updated. New data_value(s) must be compatible with data type for corresponding column.

95 Istanbul Ticaret Universitesi 2009 I - 95 June 29, 2016Databases: SQL 95 ---- Example: UPDATE All Rows Give all employees a 3% pay increase. UPDATE employee SET salary = salary*1.03;

96 Istanbul Ticaret Universitesi 2009 I - 96 June 29, 2016Databases: SQL 96 ---- Example: UPDATE Specific Rows Give all Employees in Department one a 5% pay increase. UPDATE employee SET salary = salary*1.05 WHERE dno = 1; WHERE clause finds rows that contain data for dno = 1. Update is applied only to these particular rows.

97 Istanbul Ticaret Universitesi 2009 I - 97 June 29, 2016Databases: SQL 97 ---- Example: UPDATE Multiple Columns Change Adel’s department to 2 and his Salary to 4,000. Assume Adel’s ssn = 111; UPDATE employee SET dno = 2, salary = 4000 WHERE ssn = ‘111’;

98 Istanbul Ticaret Universitesi 2009 I - 98 June 29, 2016Databases: SQL 98 -- DELETE DELETE Definition + DELETE Example +

99 Istanbul Ticaret Universitesi 2009 I - 99 June 29, 2016Databases: SQL 99 --- DELETE Definition A DELETE command removes rows from a table and may include a where-clause. Rows are explicitly deleted from only one table at a time. However, the deletion may propagate to rows in other tables if referential triggered actions are specified in the referential integrity constraints of the DDL. DELETE FROM table_name [WHERE search_condition] table_name can be name of a base table or an updatable view. The WHERE clause is optional; if omitted, all rows are deleted from table. But if it is included only those rows that satisfy the search_condition are deleted.

100 Istanbul Ticaret Universitesi 2009 I - 100 June 29, 2016Databases: SQL 100 --- Example: DELETE Delete all records from employee. DELETE FROM employee; Delete all employees in department 1. DELETE FROM employee WHERE dno = 1;

101 Istanbul Ticaret Universitesi 2009 I - 101 June 29, 2016Databases: SQL 101 -- SELECT SELECT Definition + Selecting Columns + Selecting Rows + Sorting + Aggregation + Grouping + Restricting Groups + Aliasing Table Names + Nested Queries + Join + Set Operations +

102 Istanbul Ticaret Universitesi 2009 I - 102 June 29, 2016Databases: SQL 102 --- SELECT Definition … SQL has only one statement for retrieving information from a database called the SELECT statement. SQL SELECT statement is different from that of Relational Algebra. An important distinction between SQL and formal relational model is that SQL allows duplicate rows. Hence an SQL table is not a set but a multiset (some times called a bag) of tuples.

103 Istanbul Ticaret Universitesi 2009 I - 103 June 29, 2016Databases: SQL 103 -- SELECT Definition … A SELECT statement can consist up to six clauses. SELECT [DISTINCT | ALL] {* | [column_expression [AS new_name]] [,...] } FROM table_name [alias] [,...] [WHERE condition] [GROUP BY column_list] [HAVING condition] [ORDER By column_list] Only SELECT and FROM clauses are mandatory. Order of the clauses cannot be changed.

104 Istanbul Ticaret Universitesi 2009 I - 104 June 29, 2016Databases: SQL 104 -- SELECT Definition FROM Specifies table(s) to be used. WHERE Filters rows. GROUP BY Forms groups of rows with same column value. HAVING Filters groups subject to some condition. SELECT Specifies which columns are to appear in output. ORDER BY Specifies the order of the output.

105 Istanbul Ticaret Universitesi 2009 I - 105 June 29, 2016Databases: SQL 105 --- Selecting Columns Selecting all columns + Selecting Specific columns + Selecting Computed columns + Renaming Columns +

106 Istanbul Ticaret Universitesi 2009 I - 106 June 29, 2016Databases: SQL 106 ---- Selecting All Columns Example 1: SELECT city, year, cars_sold FROM car_sales; Can use * as an abbreviation for 'all columns': Example 2: SELECT * FROM car_sales; CityYearCars_sold Dhahran2001525 Dhahran2002456 Riyadh2001700 Riyadh2002654 Jeddah2001921 Jeddah2002752 Khobar2002 Input Tables

107 Istanbul Ticaret Universitesi 2009 I - 107 June 29, 2016Databases: SQL 107 ---- Selecting Specific Columns Selected columns can be listed as shown in the following example. Notice that the year column was not selected so it doesn’t appear in the output. Example: SELECT city, cars_sold FROM car_sales; CityCars_sold Dhahran525 Dhahran456 Riyadh700 Riyadh654 Jeddah921 Jeddah752 Khobar Input Tables

108 Istanbul Ticaret Universitesi 2009 I - 108 June 29, 2016Databases: SQL 108 ---- Selecting Computed Columns If the value of a car is 100,000 then the total sales per year for each city is computed as follows. Example: SELECT city,year,cars_sold,cars_sold * 100000 FROM car_sales; Dhahran Riyadh Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 CityYearCars_Sold 52500000 45600000 70000000 65400000 92100000 75200000 Cars_Sold *100000 Khobar200200 Input Tables

109 Istanbul Ticaret Universitesi 2009 I - 109 June 29, 2016Databases: SQL 109 ---- Renaming Columns The name of the computed column in the last slide cab be changed from cars_sold*100000 to sales as follows. Example: SELECT city,year,cars_sold As Sold,cars_sold * 100000 AS sales FROM car_sales; Dhahran Riyadh Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 CityYearSold 52500000 45600000 70000000 65400000 92100000 75200000 sales Khobar200200 Input Tables

110 Istanbul Ticaret Universitesi 2009 I - 110 June 29, 2016Databases: SQL 110 --- Selecting Rows Selecting All Rows + Partial match Search + Range Search + Set Membership Search + Pattern matching Search + Null Search + Removing Duplicate Rows +

111 Istanbul Ticaret Universitesi 2009 I - 111 June 29, 2016Databases: SQL 111 ---- Selecting All Rows A SELECT statement without a WHERE clause selects all rows. Example: SELECT * FROM car_sales; Dhahran Riyadh Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 City YearCars_Sold Khobar 2002 Input Tables

112 Istanbul Ticaret Universitesi 2009 I - 112 June 29, 2016Databases: SQL 112 -- Selecting Rows To Select certain rows of a table you need to use the WHERE clause of the SELECT statement. The WHERE clause has a condition which is a logical expression. The Where condition consists of: Comparison Operators Logical Operators Arithmetic Operators Other SQL constructs which will be discussed lated. A record to be selected it must make the WHERE logical expression true. In other words it must satisfy the where condition.

113 Istanbul Ticaret Universitesi 2009 I - 113 June 29, 2016Databases: SQL 113 ---- Partial match Search Selecting all the records whose column values match the column values specified in the WHERE clause. Example1: SELECT * FROM car_sales WHERE city = ‘Dhahran’; Dhahran 2001 2002 525 456 CityYearCars_Sold Dhahran2002456 CityYearCars_Sold Example2: SELECT * FROM car_sales WHERE city = ‘Dhahran’ AND year > 2001; Input Tables

114 Istanbul Ticaret Universitesi 2009 I - 114 June 29, 2016Databases: SQL 114 ---- Range Search Example: SELECT * FROM car_sales WHERE cars_sold >= 525 AND cars_sold <= 752; OR SELECT * FROM car_sales WHERE cars_sold BETWEEN 525 AND 752; Dhahran Riyadh Jeddah 2001 2002 525 700 654 752 City YearSold Selecting all the records whose column values is between the values specified in the WHERE cluause. BETWEEN test includes the endpoints of range. NOT BETWEEN list the one not in the range. Input Tables

115 Istanbul Ticaret Universitesi 2009 I - 115 June 29, 2016Databases: SQL 115 ---- Set Membership Search … Example: SELECT * FROM car_sales WHERE city IN (‘Dhahran’, ‘Riyadh’); Selecting all the records whose column value is a member of the set specified in the WHERE clause. Dhahran Riyadh 2001 2002 2001 2002 525 456 700 654 City YearSold Input Tables

116 Istanbul Ticaret Universitesi 2009 I - 116 June 29, 2016Databases: SQL 116 … ---- Set Membership Search Example: SELECT * FROM car_sales WHERE city NOT IN (‘Dhahran’, ‘Riyadh’); Selecting all the records whose column value not a member of the set specified in the WHERE clause. Jeddah 2001 2002 921 752 City YearSold Khobar 2002 Input Tables

117 Istanbul Ticaret Universitesi 2009 I - 117 June 29, 2016Databases: SQL 117 ---- Pattern Matching Search … SQL has two special pattern matching symbols: %: sequence of zero or more characters; _ (underscore): any single character. LIKE '%dd%' means a sequence of characters of any length containing ‘dd'.

118 Istanbul Ticaret Universitesi 2009 I - 118 June 29, 2016Databases: SQL 118 ---- Pattern matching Search Example: SELECT * FROM car_sales WHERE city LIKE ‘J%’ Selecting all the records whose column value match the pattern specified in the WHERE clause. Jeddah 2001 2002 921 752 City YearSold Example: SELECT * FROM car_sales WHERE city LIKE ‘%dd%’ Jeddah 2001 2002 921 752 City YearSold Input Tables

119 Istanbul Ticaret Universitesi 2009 I - 119 June 29, 2016Databases: SQL 119 ---- NULL Search Example 1: Select all cities where the number of cars sold is unkown. SELECT city FROM car_sales WHERE cars_sold IS NULL; City Khobar Example 2: Select all cities where the number of cars sold is kown. SELECT city FROM car_sales WHERE cars_sold IS NOT NULL; City Dhahran Riyadh Jeddah Dhahran Riyadh Jeddah Input Tables

120 Istanbul Ticaret Universitesi 2009 I - 120 June 29, 2016Databases: SQL 120 ---- Removing Duplicate Rows Example1: SELECT city FROM car_sales Example2: SELECT DISTINCT city FROM car_sales Dhahran Riyadh Jeddah City Dhahran Riyadh Jeddah City Using DISTINCT in the SELECT clause removes duplicate rows from the output table Khobar Input Tables

121 Istanbul Ticaret Universitesi 2009 I - 121 June 29, 2016Databases: SQL 121 ---- Sorting The ORDER BY clause specifies an order for displaying the result of a query. SQL allows the user to order the tuples in the result of a query by the values of one or more attributes; the default order is ascending or increasing. The keyword DECS is specified to sort in a descending order of values while the keyword ASC can be used to specify ascending order explicitly. The sorting will be applied alphabetically or numerically depending on the type of the column attribute.

122 Istanbul Ticaret Universitesi 2009 I - 122 June 29, 2016Databases: SQL 122 ---- Example: Sorting Example: The following SELECT statement sorts the car_sales table in ascending order of city and descending order of car_sales columns SELECT * FROM car_sales ORDER BY city asc, car_sales desc; Dhahran Riyadh Jeddah 2001 2002 2001 2002 2001 2002 525 456 700 654 921 752 City YearCars_Sold Khobar 2002 Input Tables

123 Istanbul Ticaret Universitesi 2009 I - 123 June 29, 2016Databases: SQL 123 --- Aggregation … ISO standard defines five aggregate functions: COUNT returns number of values in a specified column. SUMreturns sum of values in a specified column. AVGreturns average of values in a specified column. MINreturns smallest value in a specified column. MAXreturns largest value in a specified column.

124 Istanbul Ticaret Universitesi 2009 I - 124 June 29, 2016Databases: SQL 124 … --- Aggregation … Each operates on a single column of a table and return single value. COUNT, MIN, and MAX apply to numeric and non-numeric fields, but SUM and AVG may be used on numeric fields only. Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null values. COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate values occur. Can use DISTINCT before column name to eliminate duplicates.

125 Istanbul Ticaret Universitesi 2009 I - 125 June 29, 2016Databases: SQL 125 … --- Aggregation DISTINCT has no effect with MIN/MAX, but may have with SUM/AVG. Aggregate functions can be used only in SELECT list and in HAVING clause. If SELECT list includes an aggregate function and there is no GROUP BY clause, then SELECT list cannot reference a column with an aggregate function. For example, following is illegal: SELECT city, COUNT(*) FROM car_sales;

126 Istanbul Ticaret Universitesi 2009 I - 126 June 29, 2016Databases: SQL 126 ---- Example : COUNT How many rows are there in the car_sales table? SELECT COUNT(*) as Rows FROM car_sales Rows 7 How many cities are there in the car_sales table? SELECT COUNT(DISTINCT city) as city FROM car_sales city 4 Input Tables

127 Istanbul Ticaret Universitesi 2009 I - 127 June 29, 2016Databases: SQL 127 ---- Example : SUM Find the total number of all the cars sold from the car_sales table? SELECT SUM(cars_sold) as cars_sold FROM car_sales Cars_sold 4008 Find the number of all the cars_sold in Dhahran from the car_sales table? SELECT SUM(cars_sold) as Dah_cars FROM car_sales WHERE city = ‘Dhahran’ Dah_cars 981 Input Tables

128 Istanbul Ticaret Universitesi 2009 I - 128 June 29, 2016Databases: SQL 128 ---- Example: MIN, MAX, AVG Find the minimum, maximum, and average cars_sold per year and per city form the car_sales table SELECT MIN(cars_sold) as Min_sold, MAX(cars_sold) as Max_sold, AVG(cars_sold) as Avg_sold FROM car_sales WHERE car_sales IS NOT NULL; Min_sold Max_soldAvg_sold 456 921668 Input Tables

129 Istanbul Ticaret Universitesi 2009 I - 129 June 29, 2016Databases: SQL 129 --- Grouping Use GROUP BY clause to get sub-totals. SELECT and GROUP BY closely integrated: each item in SELECT list must be single-valued per group, and SELECT clause may only contain: Column names. Aggregate functions. Constants. An expression involving combinations of the above. All column names in SELECT list must appear in GROUP BY clause unless name is used only in an aggregate function. If WHERE is used with GROUP BY, WHERE is applied first, then groups are formed from remaining rows satisfying predicate. ISO considers two nulls to be equal for purposes of GROUP BY.

130 Istanbul Ticaret Universitesi 2009 I - 130 June 29, 2016Databases: SQL 130 ---- Example: Grouping Find the total cars sold in each city from the car_sales table. SELECT city, SUM(cars_sold) as cars FROM car_sales WHERE cars_sold IS NOT NULL GROUP BY city ORDER BY SUM(cars_sold) ; City Cars Dhahran 981 Riyadh 1354 Jeddah 1637 Input Tables

131 Istanbul Ticaret Universitesi 2009 I - 131 June 29, 2016Databases: SQL 131 --- Restricting Groups HAVING clause is designed for use with GROUP BY clause to restrict groups that appear in final result table. Similar to WHERE, but WHERE filters individual rows whereas HAVING filters groups. Column names in HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function.

132 Istanbul Ticaret Universitesi 2009 I - 132 June 29, 2016Databases: SQL 132 ---- Example: Restricting Groups Find the cities who sold a total of more than 1000 cars from the car_sales table. SELECT city, SUM(cars_sold) as cars FROM car_sales WHERE cars_sold IS NOT NULL GROUP BY city HAVING SUM(cars_sold) > 1000 ; City Cars Riyadh1354 Jeddah1637 Input Tables

133 Istanbul Ticaret Universitesi 2009 I - 133 June 29, 2016Databases: SQL 133 -- Aliasing Table Names A table alias is created by directly placing an alias after the table name in the FROM clause. The advantage of using a table alias when performing JOIN is readily apparent when we discuss JOIN later. For example in the following example we will refer to departments table as d or dept. SELECT d.dname FROM departments d WHERE d.dno = 1; SELECT dept.dname FROM departments dept WHERE dept.dno = 1;

134 Istanbul Ticaret Universitesi 2009 I - 134 June 29, 2016Databases: SQL 134 --- Nested queries Some SQL statements can have a SELECT embedded within them. A subselect can be used in WHERE and HAVING clauses of an outer SELECT, where it is called a nested query or a subquery. Subselects may also appear in INSERT, UPDATE, and DELETEs.

135 Istanbul Ticaret Universitesi 2009 I - 135 June 29, 2016Databases: SQL 135 ---- Example: Nested queries From the Lecturer table, select lecturers whose salary is above average. Cannot write 'WHERE salary > avg(salary)'. SELECT AVG(salary) FROM lecturers SELECT * FROM lecturers WHERE salary > ( ); Inner select Outer select  The Inner select is done before the outer select. Input Tables

136 Istanbul Ticaret Universitesi 2009 I - 136 June 29, 2016Databases: SQL 136 ---- Nested query: Example List the names of all Lecturers who are in the ICS department SELECT lname FROM lecturers WHERE dno IN ( ); SELECT dno FROM department WHERE dname = ‘ICS’ Input Tables

137 Istanbul Ticaret Universitesi 2009 I - 137 June 29, 2016Databases: SQL 137 ---- Nested Query Rules ORDER BY clause may not be used in a subquery (although it may be used in outermost SELECT). Subquery SELECT list must consist of a single column name or expression, except for subqueries that use EXISTS. By default, column names refer to table name in FROM clause of subquery. Can refer to a table in FROM using an alias. When subquery is an operand in a comparison, subquery must appear on right-hand side. A subquery may not be used as an operand in an expression.

138 Istanbul Ticaret Universitesi 2009 I - 138 June 29, 2016Databases: SQL 138 ---- Nested Query: Example Find lecturers whose salary higher than the salary of at least 1 COE lecturer. SELECT min(salary) FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > ( ); SELECT DNO FROM department WHERE dname = ‘COE’ Input Tables

139 Istanbul Ticaret Universitesi 2009 I - 139 June 29, 2016Databases: SQL 139 ---- Nested Query: Example Find lecturers whose salary higher than the salary of every COE lecturer. SELECT max(salary) FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > ( ); SELECT DNO FROM department WHERE dname = ‘COE’ Input Tables

140 Istanbul Ticaret Universitesi 2009 I - 140 June 29, 2016Databases: SQL 140 -- Join Can use subqueries provided result columns come from same table. If result columns come from more than one table must use a join. To perform join, include more than one table in FROM clause. Use comma as separator and typically include WHERE clause to specify join column(s). Also possible to use an alias for a table named in FROM clause. Alias is separated from table name with a space. Alias can be used to qualify column names when there is ambiguity.

141 Istanbul Ticaret Universitesi 2009 I - 141 June 29, 2016Databases: SQL 141 --- Example: Join (Inner Join) … The default type of join is inner join, where arow is included in the result only if matching row exists in the other relation. List each lecturer’s name and his department name. SELECT a.lname, b.dname FROM lecturers a, departments b WHERE a.dno = b.dno; Lnamedname Ahmed Amin Hani Ageel Yousef Khalid ICS COE ICS COE Input Tables

142 Istanbul Ticaret Universitesi 2009 I - 142 June 29, 2016Databases: SQL 142 … Example: Join (Inner Join) To obtain correct rows, include only those rows from both tables that have identical values in the dno columns: a.dno = b.dno. These two columns are the matching columns for two tables. This type of join is also called inner join and they equivalent to equi-join in relational algebra.

143 Istanbul Ticaret Universitesi 2009 I - 143 June 29, 2016Databases: SQL 143 ---- Computing a Join Procedure for generating results of a SELECT with a join are: 1.Form Cartesian product of the tables named in FROM clause. 2.If there is a WHERE clause, apply the search condition to each row of the product table, retaining those rows that satisfy the condition. 3.For each remaining row, determine the value of each item in the SELECT list to produce a single row in the result table. 4.If SELECT DISTINCT has been specified, eliminate any duplicate rows from the result table. 5.If there is an ORDER BY clause, sort the result table as required.

144 Istanbul Ticaret Universitesi 2009 I - 144 June 29, 2016Databases: SQL 144 --- Outer Joins … With an inner join, if one row of a table is unmatched, row is omitted from result table. The outer join operations retain rows that do not satisfy the join condition. There are three types of OUTER JOIN Left Outer Join Right Outer Join Full Outer Join Lets discuss inner join then we will come back to outer join.

145 Istanbul Ticaret Universitesi 2009 I - 145 June 29, 2016Databases: SQL 145 … ---- Outer Join … Inner join of departments and lecturers tables will result in the following output. SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno = b.dno Lid Lnamednosalary 1 2 3 4 5 6 Ahmed Amin Hani Ageel Yousef Khalid 1 2 1 1 2 2 4000 3700 4200 4000 3500 4500 1 2 1 1 2 2 dno ICS COE ICS COE dname Input Tables

146 Istanbul Ticaret Universitesi 2009 I - 146 June 29, 2016Databases: SQL 146 … ---- Outer Join … Result table has two rows where the dno are the same. There are no rows corresponding to NW or Abdella. To include unmatched rows in result table, use an outer join.

147 Istanbul Ticaret Universitesi 2009 I - 147 June 29, 2016Databases: SQL 147 ---- Example: Left Outer Join If We want to Include in the output table the lecturers whose department is unknow we rewrite our previous query as follows SELECT a.*, b.* FROM lecturers a, Departments b WHERE b.dno(+) = a.dno Lid Lnamednosalary 1 2 3 5 6 7 Ahmed Amin Hani Ageel Yousef Khalid 1 2 1 1 2 2 4000 3700 4200 4000 3500 4500 1 2 1 1 2 2 dno SE COE ICS SWE dname 4Addella4300 Input Tables

148 Istanbul Ticaret Universitesi 2009 I - 148 June 29, 2016Databases: SQL 148 ---- Example: Right Outer Join If We want to Include in the output table the departments with no lecturers we rewrite our previous query as follows SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno = b.dno(+) Lid Lnamednosalary 1 2 3 5 6 7 Ahmed Amin Hani Ageel Yousef Khalid 4 3 1 3 2 2 4000 3700 4200 4000 3500 4500 4 3 1 3 2 2 dno SE COE ICS SWE dname 5NW Input Tables

149 Istanbul Ticaret Universitesi 2009 I - 149 June 29, 2016Databases: SQL 149 ---- Example: Full Outer Join If We want to Include in the output table the departments with no lecturers and the lecturers with unknow departments we rewrite our previous query as follows SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno = b.dno(+) UNION SELECT a.*, b.* FROM lecturers a, Departments b WHERE a.dno(+) = b.dno; Lid Lnamednosalary 1 2 3 5 6 7 Ahmed Amin Hani Ageel Yousef Khalid 4 3 1 3 2 2 4000 3700 4200 4000 3500 4500 4 3 1 3 2 2 dno SE COE ICS SWE dname 5 NW 4Abdella4300 Input Tables

150 Istanbul Ticaret Universitesi 2009 I - 150 June 29, 2016Databases: SQL 150 ---- Characteristic of Outer Join Left Outer Join: Includes those rows of first (left) table unmatched with rows from second (right) table. Columns from second table are filled with NULLs. Right outer Join : includes those rows of second (right) table that are unmatched with rows from first (left) table. Columns from first table are filled with NULLs. Full Outer Join: Is the UNION of both left and right outer joins.

151 Istanbul Ticaret Universitesi 2009 I - 151 June 29, 2016Databases: SQL 151 -- Union, Intersect, and Difference Can use normal set operations of union, intersection, and difference to combine results of two or more queries into a single result table. Union of two tables, A and B, is table containing all rows in either A or B or both. Intersection is table containing all rows common to both A and B. Difference is table containing all rows in A but not in B. Two tables must be union compatible. If ALL specified, result can include duplicate rows

152 Istanbul Ticaret Universitesi 2009 I - 152 June 29, 2016Databases: SQL 152 ---- Example: Use of UNION … List all the ICS and COE faculty salaries. Remove duplicates SELECT salary FROM lecturers WHERE dno = 1 UNION SELECT salary FROM lecturers WHERE dno = 2; List all the ICS and COE faculty salaries. Include duplicates SELECT salary FROM lecturers WHERE dno = 1 UNION ALL SELECT salary FROM lecturers WHERE dno = 2; Input Tables

153 Istanbul Ticaret Universitesi 2009 I - 153 June 29, 2016Databases: SQL 153 … ---- Example: Use of UNION List all the ICS and COE faculty salaries. Remove duplicates SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘ICS’ ) UNION SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ ) List all the ICS and COE faculty salaries. Include duplicates SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘ICS’ ) UNION ALL SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ ) Input Tables

154 Istanbul Ticaret Universitesi 2009 I - 154 June 29, 2016Databases: SQL 154 … ---- Example: Use of DIFFERENCE List salaries that are taken by ICS and not COE lecturers. SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments where dname= ‘ICS’ ) MINUS SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ ) Input Tables

155 Istanbul Ticaret Universitesi 2009 I - 155 June 29, 2016Databases: SQL 155 … ---- Example: Use of INTESECTION List salaries that are taken by both COE and ICS lecturers. SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments where dname= ‘ICS’ ) INTERSECT SELECT salary FROM lecturers WHERE dno = ( SELECT dno FROM departments WHERE dname= ‘COE’ ) Produces result tables from both queries and creates single result table consisting of those rows that are common to both result tables. Input Tables

156 Istanbul Ticaret Universitesi 2009 I - 156 June 29, 2016Databases: SQL 156 - Other SQL Operators IN (covered) BETWEEN (covered) LIKE (covered) ANY (SOME) + ALL + EXISTS + NOT EXISTS +

157 Istanbul Ticaret Universitesi 2009 I - 157 June 29, 2016Databases: SQL 157 -- ANY (SOME) and ALL ANY and ALL may be used with subqueries that produce a single column of numbers. If subquery preceded by ALL, condition will only be true if it is satisfied by all values produced by subquery. If subquery preceded by ANY, condition will be true if it is satisfied by any values produced by subquery. If subquery is empty, ALL returns true, ANY returns false. ISO standard allows SOME to be used in place of ANY.

158 Istanbul Ticaret Universitesi 2009 I - 158 June 29, 2016Databases: SQL 158 --- Example using the SOME Operator Find lecturers whose salary higher than the salary of at least 1 COE lecturer. SELECT salary FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > SOME ( ); SELECT DNO FROM department WHERE dname = ‘COE’ Input Tables

159 Istanbul Ticaret Universitesi 2009 I - 159 June 29, 2016Databases: SQL 159 --- Example Using the ALL Operator Find lecturers whose salary higher than the salary of every COE lecturer. SELECT salary FROM lecturers WHERE dno = ( ) SELECT * FROM Lecturers WHERE salary > ALL ( ); SELECT DNO FROM department WHERE dname = ‘COE’ Input Tables

160 Istanbul Ticaret Universitesi 2009 I - 160 June 29, 2016Databases: SQL 160 -- EXISTS and NOT EXISTS EXISTS and NOT EXISTS are for use only with subqueries specially with correlated subqueries. A correlated subquery is a subquery where some attributes of the outer select are used in the inner select. They produce a simple true/false result. EXISTS is true if and only if there exists at least one row in result table returned by subquery. It is false if subquery returns an empty result table. NOT EXISTS is the opposite of EXISTS. Since EXISTS and NOT EXISTS check only for existence or non-existence of rows in subquery result table, subquery can contain any number of columns.

161 Istanbul Ticaret Universitesi 2009 I - 161 June 29, 2016Databases: SQL 161 --- Example using the EXISTS Operator Find all ICS lecturers. SELECT * FROM lecturers a WHERE EXISTS ( SELECT 1 FROM department b WHERE a.dno = b.dno AND b.dname = ‘ICS‘ ); Input Tables

162 Istanbul Ticaret Universitesi 2009 I - 162 June 29, 2016Databases: SQL 162 --- Example using the NOT EXISTS Operator Find all non ICS lecturers. SELECT * FROM lecturers a WHERE NOT EXISTS ( SELECT 1 FROM department b WHERE a.dno = b.dno AND b.dname = ‘ICS‘ ); Input Tables


Download ppt "Istanbul Ticaret Universitesi 2009 Veri Tabanı Ders Notları Öğr.Görevlisi Kıvanç Güler."

Similar presentations


Ads by Google