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

Slides:



Advertisements
Similar presentations
CSC271 Database Systems Lecture # 11.
Advertisements

Structure Query Language (SQL) COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7 Data Modeling Using the Entity- Relationship (ER) Model.
Structured Query Language
Chapter 6 SQL: Data Manipulation. 2 Objectives of SQL u Database language should allow user to: –create database and relation structures –perform insertion,
Introduction to Structured Query Language (SQL)
1 Minggu 4, Pertemuan 7 SQL: Data Manipulation Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.
Michael F. Price College of Business Chapter 6: Logical database design and the relational model.
Chapter 3 Data Modeling Using the Entity- Relationship (ER) Model Dr. Bernard Chen Ph.D. University of Central Arkansas.
Data Modeling Using the Entity-Relationship Model
Data Modeling Using the Entity-Relationship Model
DeSiamorewww.desiamore.com/ifm1 Database Management Systems (DBMS)  B. Computer Science and BSc IT Year 1.
CSE314 Database Systems Data Modeling Using the Entity- Relationship (ER) Model Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
Chapter 3 Data Modeling Using the Entity-Relationship (ER) Model.
Entities and Attributes
CSC271 Database Systems Lecture # 10.
Database Technical Session By: Prof. Adarsh Patel.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7 Data Modeling Using the Entity- Relationship (ER) Model.
Concepts and Terminology Introduction to Database.
Agenda TMA01 M876 Block 3 – Using SQL Structured Query Language - SQL A non-procedural language to –Create database and relation structures. –Perform.
Data Manipulation Using MySQL tMyn1 Data Manipulation Using MySQL Ideally, a database language should allow a user to: –Create the database and relation.
Announcements Read 6.7 – 6.10 for Wednesday Homework 6, due Friday 10/29 Project Step 4, due today Research paper –List of sources - due 10/29.
Database Systems: A Practical Approach to Design, Implementation and Management International Computer Science S. Carolyn Begg, Thomas Connolly Lecture.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
SQL Structured Query Language Programming Course.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 3 Data Modeling Using the Entity- Relationship (ER) Model.
Chapter 5: Part 1: DDL STRUCTURED QUERY LANGUAGE (SQL)
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Oracle DML Dr. Bernard Chen Ph.D. University of Central Arkansas.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Initial Design of Entity Types for the COMPANY Database Schema Based on the requirements, we can identify four initial entity types in the COMPANY database:
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
UNIT_2 1 DATABASE MANAGEMENT SYSTEM[DBMS] [Unit: 2] Prepared By Lavlesh Pandit SPCE MCA, Visnagar.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Chapter 9 Logical Database Design : Mapping ER Model To Tables.
Copyright © 2007 Ramez Elmasr and Shamkant B. Navathei Slide 3- 1.
IST 210 SQL Todd Bacastow IST 210: Organization of Data.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
The relational model A data model (in general) : Integrated collection of concepts for describing data (data requirements). Relational model was introduced.
DatabaseIM ISU1 Fundamentals of Database Systems Chapter 3 Data Modeling Using Entity-Relationship Model.
Data Modeling Using the Entity- Relationship (ER) Model.
ITS232 Introduction To Database Management Systems Siti Nurbaya Ismail Faculty of Computer Science & Mathematics, Universiti Teknologi MARA (UiTM), Kedah.
SQL and QBE Transparencies. ©Pearson Education 2009 Chapter 3 - Objectives Purpose and importance of SQL, the main language for querying relational databases.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
LECTURE TWO Introduction to Databases: Data models Relational database concepts Introduction to DDL & DML.
SQL: Additional Notes. 2 Example 5.3 Use of DISTINCT List the property numbers of all properties that have been viewed. SELECT propertyNo FROM Viewing;
1 The Relational Data Model David J. Stucki. Relational Model Concepts 2 Fundamental concept: the relation  The Relational Model represents an entire.
Database Designsemester Slide 1 Database Design Lecture 7 Entity-relationship modeling Text , 7.1.
Data Modeling Using the Entity- Relationship (ER) Model
Comp 1100 Entity-Relationship (ER) Model
Teacher Workshop Database Design Pearson Education © 2014.
Logical Database Design and the Rational Model
Chapter 10 SQL DDL.
Data Modeling Using the Entity- Relationship (ER) Model
Translation of ER-diagram into Relational Schema
STRUCTURED QUERY LANGUAGE
© Pearson Education Limited, 2004
Structured Query Language - SQL
Chapter Name SQL: Data Manipulation
Structured Query Language - SQL
Chapter Name SQL: Data Manipulation
Presentation transcript:

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

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.

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.

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.

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

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.

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.

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.

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

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.

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.

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.

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.

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.

Istanbul Ticaret Universitesi 2009 I - 15 June 29, 2016DB: Relational Data Model 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.

Istanbul Ticaret Universitesi 2009 I - 16 ID NAME NAT_ID DOB DEPTCODE KHALED ICS ADEL COE AHMED COE HASSAN SWE MUSTAFA ICS - Terminology Tuples STUDENT Attributes Relation name Degree Cardinality

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

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.

Istanbul Ticaret Universitesi 2009 I 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

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.

Istanbul Ticaret Universitesi 2009 I - 21

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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.

Istanbul Ticaret Universitesi 2009 I 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

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

Istanbul Ticaret Universitesi 2009 I 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

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

Istanbul Ticaret Universitesi 2009 I 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 +

Istanbul Ticaret Universitesi 2009 I 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.

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.

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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

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 : Supervises 2: Supervised

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

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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).

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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.

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

Istanbul Ticaret Universitesi 2009 I 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.

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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).

Istanbul Ticaret Universitesi 2009 I Example: Higher Degree Relationships

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

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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:

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.

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.

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.

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

Istanbul Ticaret Universitesi 2009 I 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.

Istanbul Ticaret Universitesi 2009 I … 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,

Istanbul Ticaret Universitesi 2009 I … 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.

Istanbul Ticaret Universitesi 2009 I Summary of ER diagram notation.

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

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 +

Istanbul Ticaret Universitesi 2009 I - 60 June 29, 2016Databases: SQL Example Table … Car_Sales CityYearCars_sold Dhahran Dhahran Riyadh Riyadh Jeddah Jeddah Khobar2002

Istanbul Ticaret Universitesi 2009 I - 61 June 29, 2016Databases: SQL 61 … --- Example: Tables ICS COE SWE dno dname Lid Lnamednosalary Ahmed Amin Hani Abdallah Ageel Yousef Khalid Departments Lecturers

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 +

Istanbul Ticaret Universitesi 2009 I - 63 June 29, 2016Databases: SQL 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.

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.

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;

Istanbul Ticaret Universitesi 2009 I - 66 June 29, 2016Databases: SQL 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.

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.

Istanbul Ticaret Universitesi 2009 I - 68 June 29, 2016Databases: SQL 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.

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.

Istanbul Ticaret Universitesi 2009 I - 70 June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I - 71 June 29, 2016Databases: SQL 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.

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

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

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

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.

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.

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.

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 +

Istanbul Ticaret Universitesi 2009 I - 79 June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I - 80 June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I - 81 June 29, 2016Databases: SQL 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) );

Istanbul Ticaret Universitesi 2009 I - 82 June 29, 2016Databases: SQL 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) );

Istanbul Ticaret Universitesi 2009 I - 83 June 29, 2016Databases: SQL 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).

Istanbul Ticaret Universitesi 2009 I - 84 June 29, 2016Databases: SQL 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));

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

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

Istanbul Ticaret Universitesi 2009 I - 87 June 29, 2016Databases: SQL 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 +

Istanbul Ticaret Universitesi 2009 I - 88 June 29, 2016Databases: SQL 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', ‘ ', 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.

Istanbul Ticaret Universitesi 2009 I - 89 June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I - 90 June 29, 2016Databases: SQL 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;

Istanbul Ticaret Universitesi 2009 I - 91 June 29, 2016Databases: SQL 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.

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

Istanbul Ticaret Universitesi 2009 I - 93 June 29, 2016Databases: SQL 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.

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.

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

Istanbul Ticaret Universitesi 2009 I - 96 June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I - 97 June 29, 2016Databases: SQL 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’;

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

Istanbul Ticaret Universitesi 2009 I - 99 June 29, 2016Databases: SQL 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.

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

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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 Dhahran Dhahran Riyadh Riyadh Jeddah Jeddah Khobar2002 Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 * FROM car_sales; Dhahran Riyadh Jeddah CityYearCars_Sold Cars_Sold * Khobar Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL Renaming Columns The name of the computed column in the last slide cab be changed from cars_sold* to sales as follows. Example: SELECT city,year,cars_sold As Sold,cars_sold * AS sales FROM car_sales; Dhahran Riyadh Jeddah CityYearSold sales Khobar Input Tables

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

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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 CityYearCars_Sold Dhahran CityYearCars_Sold Example2: SELECT * FROM car_sales WHERE city = ‘Dhahran’ AND year > 2001; Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 City YearSold Input Tables

Istanbul Ticaret Universitesi 2009 I 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 City YearSold Khobar 2002 Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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'.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 City YearSold Example: SELECT * FROM car_sales WHERE city LIKE ‘%dd%’ Jeddah City YearSold Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 City YearCars_Sold Khobar 2002 Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I 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.

Istanbul Ticaret Universitesi 2009 I 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;

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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;

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I 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 Ahmed Amin Hani Ageel Yousef Khalid dno ICS COE ICS COE dname Input Tables

Istanbul Ticaret Universitesi 2009 I 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 Ahmed Amin Hani Ageel Yousef Khalid dno SE COE ICS SWE dname 4Addella4300 Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 Ahmed Amin Hani Ageel Yousef Khalid dno SE COE ICS SWE dname 5NW Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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 Ahmed Amin Hani Ageel Yousef Khalid dno SE COE ICS SWE dname 5 NW 4Abdella4300 Input Tables

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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

Istanbul Ticaret Universitesi 2009 I 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

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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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.

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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

Istanbul Ticaret Universitesi 2009 I June 29, 2016Databases: SQL 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