3ISY402 DATABASE SYSTEMS

Similar documents
Standard Query Language. SQL: Data Definition Transparencies

Lecture 5 Data Definition Language (DDL)

Lecture 6 Structured Query Language (SQL)

Example 1 - Create Horizontal View. Example 2 - Create Vertical View. Views. Views

Lecture 07. Spring 2018 Borough of Manhattan Community College

DB Creation with SQL DDL

STRUCTURED QUERY LANGUAGE (SQL)

Transforming ER to Relational Schema

Chapter 6. SQL Data Manipulation

ADVANCED QUERY AND VIEWS

COMP102: Introduction to Databases, 5 & 6

CS317 File and Database Systems

CMP-3440 Database Systems

A <column constraint> is a constraint that applies to a single column.

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Chapter 6. SQL: SubQueries

Lecture 03. Spring 2018 Borough of Manhattan Community College

Relational Algebra and Relational Calculus. Pearson Education Limited 1995,

Relational Data Model ( 관계형데이터모델 )

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

CS317 File and Database Systems

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

CS317 File and Database Systems

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

CMP-3440 Database Systems

RELATIONAL DATA MODEL

Logical Database Design. ICT285 Databases: Topic 06

Lab # 4. Data Definition Language (DDL)

Lecture 03. Fall 2017 Borough of Manhattan Community College

Data Definition Language (DDL)

Basic SQL. Basic SQL. Basic SQL

Relational Model. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Chapter 1 SQL and Data

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CMP-3440 Database Systems

Physical Database Design

The Structured Query Language Get Started

Objective. The goal is to review material covered in Chapters 1-5. Do the following questions from the book.

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

Conceptual Database Design

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

CS317 File and Database Systems

Relational Database Language

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

The Relational Model

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

Slides by: Ms. Shree Jaswal

Database Technologies. Madalina CROITORU IUT Montpellier


CS2300: File Structures and Introduction to Database Systems

Database design process

Unit 1 - Chapter 4,5

SQL DATA MANIPULATION. Prepared By: Dr. Vipul Vekariya.

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

Midterm Review. Winter Lecture 13

Institute of Southern Punjab, Multan

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Data about data is database Select correct option: True False Partially True None of the Above

Lecture4: Guidelines for good relational design Mapping ERD to Relation. Ref. Chapter3

The DBMS accepts requests for data from the application program and instructs the operating system to transfer the appropriate data.

Creating and Managing Tables Schedule: Timing Topic

SQL STRUCTURED QUERY LANGUAGE

Database Systems. A Practical Approach to Design, Implementation, and Management. Database Systems. Thomas Connolly Carolyn Begg

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

2.9 Table Creation. CREATE TABLE TableName ( AttrName AttrType, AttrName AttrType,... )

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

SQL DATA MANIPULATION. Prepared By: Vipul Vekariya M.E( Computer) Gardi College Of Eng. & Tech. Rajkot.


SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Using SQL with SQL Developer 18.2

Principles of Data Management

2.2.2.Relational Database concept

CPS510 Database System Design Primitive SYSTEM STRUCTURE

Lecture 08. Spring 2018 Borough of Manhattan Community College

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

Oracle Database 10g: Introduction to SQL

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

Mahathma Gandhi University

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Chapter 5. Relational Algebra and Relational Calculus

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

Chapter 3. The Relational database design

3.1. Keys: Super Key, Candidate Key, Primary Key, Alternate Key, Foreign Key

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

Structured Query Language (SQL)

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

SQL - Subqueries and. Schema. Chapter 3.4 V4.0. Napier University

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Database Technology. Topic 2: Relational Databases and SQL. Olaf Hartig.

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

CMP-3440 Database Systems

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Basant Group of Institution

COSC 304 Introduction to Database Systems. Views and Security. Dr. Ramon Lawrence University of British Columbia Okanagan

MySQL Introduction. By Prof. B.A.Khivsara

Transcription:

3ISY402 DATABASE SYSTEMS - SQL: Data Definition 1 Leena Gulabivala Material from essential text: T CONNOLLY & C BEGG. Database Systems A Practical Approach to Design, Implementation and Management, 4th Edition. Addison-Wesley, 2005.

Lecture - Objectives Introduction to some basic SQL DDL statements. How to define table structures using CREATE TABLE statements. How to define Primary and Foreign Keys. How to amend tables using ALTER statements. How to delete tables using DROP statements. How to rename tables using RENAME statements. How to create and delete views using CREATE VIEW and DROP VIEW. Under what conditions views are updatable. Advantages and disadvantages of views. 2 Leena Gulabivala

Data Definition SQL DDL allows database objects such as schemas, domains, tables, views, and indexes to be created and destroyed. Relations and other database objects exist in an environment. Each environment contains one or more catalogs, and each catalog consists of a set of schemas. A schema is a named collection of related database objects. Objects in a schema can include tables, views, domains, etc. 3 Leena Gulabivala

CREATE TABLE Syntax CREATE TABLE TableName ( {colname datatype [NOT NULL] [,...]} [PRIMARY KEY (listofcolumns),] {[FOREIGN KEY (listoffkcolumns) REFERENCES ParentTableName [(listofckcolumns)] [, ]} ); 4 Leena Gulabivala

CREATE TABLE Creates a table with one or more columns of the specified datatype. 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. FOREIGN KEY clause specifies FK. 5 Leena Gulabivala

Some Common SQL Data Types CHAR(size) VARCHAR2(size) NUMBER (l, d) DATE Fixed length character data of length size bytes. Variable length character string having maximum length size bytes. Fixed-point or floating-point numbers, where l stands for length and d stands for the number of decimal digits. Eg NUMBER(5,2) allows max 999.99. Eg NUMBER(3) allows max 999. Stores dates ranging from 01 January 4712 BC to 31 December 4712 AD 6 Leena Gulabivala

Example 1 - CREATE TABLE Branch Create the structures for the Branch table. CREATE TABLE Branch ( branchno CHAR(5) NOT NULL, street VARCHAR2(25), city VARCHAR2(15), postcode VARCHAR2(10) ); 7 Leena Gulabivala

Example 2 - CREATE TABLE Staff Create the structures for the Staff table. CREATE TABLE Staff ( staffno CHAR(5) NOT NULL, fname VARCHAR2(20) NOT NULL, lname VARCHAR2(25) NOT NULL, position VARCHAR2(10) NOT NULL, sex CHAR(1) NOT NULL, DOB DATE, salary NUMBER(8,2) NOT NULL, branchno CHAR(5) NOT NULL ); 8 Leena Gulabivala

Defining Primary and Foreign Keys Primary Key A column or a set of columns that is selected to uniquely identify a row within a table. The primary key of a table must contain a unique, non-null value for each row. (Use NOT NULL) A primary key comprising more than one column is called a composite key or compound key. Foreign Key A column or a set of columns within one table that matches the candidate key of another table. 9 Leena Gulabivala

Referential Integrity Referential integrity means that, if the foreign key contains a value, that value must refer to an existing row in the parent table. Any INSERT/UPDATE attempting to create a foreign key value in the child table without a matching key value in the parent is rejected with the following error message. SQL Error: ORA-02291: integrity constraint violated - parent key not found 10 Leena Gulabivala

Example 3 CREATE TABLE with a Simple Primary Key 3ISY402 Database Systems Create the structures for the Staff table and define staff number (staffno) as its primary key. CREATE TABLE Staff ( staffno CHAR(5) NOT NULL, fname VARCHAR2(20) NOT NULL, lname VARCHAR2(25) NOT NULL, position VARCHAR2(10) NOT NULL, sex CHAR(1) NOT NULL, DOB DATE, salary NUMBER(8,2) NOT NULL, branchno CHAR(5) NOT NULL, PRIMARY KEY (staffno) ); 11 Leena Gulabivala

Example 4 CREATE TABLE with a Compound Key 3ISY402 Database Systems Create the structures for the Viewing table and define property number (propertyno), client number (clientno) and the viewing date as its primary key (compound key). CREATE TABLE Viewing ( clientno CHAR(4) NOT NULL, propertyno CHAR(4) NOT NULL, viewdate DATE NOT NULL, comment VARCHAR2(30), PRIMARY KEY (clientno, propertyno, viewdate) ); 12 Leena Gulabivala

Example 5 CREATE TABLE with Foreign Keys Create the structures for the Viewing table and define property number, client number and viewdate as its primary key (compound key) and property number and client number as foreign keys. CREATE TABLE Viewing ( clientno CHAR(4) NOT NULL, propertyno CHAR(4) NOT NULL, viewdate DATE NOT NULL, comment VARCHAR2(30), PRIMARY KEY (clientno, propertyno, viewdate), FOREIGN KEY (clientno) REFERENCES Client(clientNo), FOREIGN KEY (propertyno) REFERENCES PropertyForRent(propertyNo) ); 13 Leena Gulabivala

ALTER TABLE Allows modification of table structures already defined. Amend an existing column data definition in a table. Adding new column to existing tables. Drop a column from a table. Rename a column in a table. Add a Primary or Foreign Key. 14 Leena Gulabivala

Example 6 - ALTER TABLE Change Existing Column Data Definition ALTER TABLE TableName MODIFY (colname newdatatype); Increase the size of column position in the Staff table from 10 to 20 to accommodate the new post of Managing Director. ALTER TABLE Staff MODIFY position VARCHAR2(20); 15 Leena Gulabivala

Example 7 - ALTER TABLE Adding Columns to Existing Tables ALTER TABLE TableName ADD (colname datatype [NOT NULL] ); Add a column called nationality to the Staff table. ALTER TABLE Staff ADD (nationality VARCHAR2(20)); 16 Leena Gulabivala

ALTER TABLE Deleting a Column or Renaming a Column Delete a Column: ALTER TABLE TableName DROP COLUMN colname; Rename a Column: ALTER TABLE TableName RENAME COLUMN oldcolumnname TO newcolumnname; Example - rename the column from sex to gender: ALTER TABLE Staff RENAME COLUMN sex TO gender; 17 Leena Gulabivala

Example 8 - ALTER TABLE Add a Primary Key or Foreign Key Constraint Define branchno as the primary key of the existing Branch table. ALTER TABLE ADD Branch PRIMARY KEY(branchNo); Define branchno as the foreign key of the existing Staff table. ALTER TABLE Staff ADD FOREIGN KEY (branchno) REFERENCES Branch(branchNo); 18 Leena Gulabivala

DROP TABLE DROP TABLE TableName [RESTRICT CASCADE] [CONSTRAINTS]; e.g. DROP TABLE PropertyForRent; Removes named table and all rows within it. With CASCADE CONSTRAINTS, SQL drops all dependent objects (eg tables and views) and objects dependent on these objects. With RESTRICT, if any other objects depend for their existence on continued existence of this table, SQL does not allow request. 19 Leena Gulabivala

RENAME TABLE RENAME OldTableName TO NewTableName; e.g. RENAME Property TO PropertyForRent; Renames named table to new named table. DBMS automatically transfers to the new table the integrity constraints, indexes and privileges that referenced the old table. BUT objects that referenced the old table (eg views, stored procedures and functions) become invalid. 20 Leena Gulabivala

Views Dynamic result of one or more relational operations operating on base relations to produce another relation. Virtual relation that does not necessarily actually exist in the database but is produced upon request, at time of request. Contents of a view are defined as a query on one or more base relations. 21 Leena Gulabivala

SQL - CREATE VIEW CREATE VIEW ViewName [ (newcolumnname [,...]) ] AS subselect Can assign a name to each column in view. If a list of column names is specified, it must have the same number of items as the number of columns produced by the subselect. If omitted, each column takes the name of the corresponding column in the subselect. List must be specified if there is any ambiguity in a column name. The subselect is known as the defining query. 22 Leena Gulabivala

Example 9 - Create Horizontal View Create view so that manager at branch B003 can only see details for staff who work in his or her office. CREATE VIEW ManagerStaff AS SELECT * FROM Staff WHERE branchno = 'B003'; 23 Leena Gulabivala

Example 10 - Create Vertical View Create view of staff details at branch B003 excluding salaries. CREATE VIEW Staff AS SELECT staffno, fname, lname, position, sex FROM Staff WHERE branchno = 'B003'; 24 Leena Gulabivala

Example 11 - Grouped and Joined Views Create view of staff who manage properties for rent, including branch number they work at, staff number, and number of properties they manage. CREATE VIEW StaffPropCnt (branchno, staffno, cnt) AS SELECT s.branchno, s.staffno, COUNT(*) FROM Staff s, PropertyForRent p WHERE s.staffno = p.staffno GROUP BY s.branchno, s.staffno; 25 Leena Gulabivala

SQL - DROP VIEW DROP VIEW ViewName [RESTRICT CASCADE] Causes definition of view to be deleted from database. For example: DROP VIEW ManagerStaff; With CASCADE, all related dependent objects are deleted; i.e. any views defined on view being dropped. With RESTRICT (default), if any other objects depend for their existence on continued existence of view being dropped, command is rejected. 26 Leena Gulabivala

Restrictions on Views SQL imposes several restrictions on creation and use of views. Grouped view may never be joined with a base table or a view. Eg StaffPropCnt view is a grouped view, so cannot join this view with another table or view. If a column in a view is based on an aggregate function: Column may appear only in SELECT and ORDER BY clauses of queries accessing view. Column may not be used in WHERE nor be an argument to an aggregate function in any query based on view. 27 Leena Gulabivala

Example 12 - Restrictions on Views For example, following query would fail: SELECT COUNT(cnt) FROM StaffPropCnt; Similarly, following query would also fail: SELECT * FROM StaffPropCnt WHERE cnt > 2; 28 Leena Gulabivala

View Updatability All updates to the base table are reflected in all views that encompass the base table. Similarly, may expect that if a view is updated then base table(s) will reflect change. For a view to be updatable, DBMS must be able to trace any row or column back to its row or column in the source or base table. 29 Leena Gulabivala

View Updatability ISO specifies that a view is updatable if and only if: - DISTINCT is not specified. - Every element in SELECT list of defining query is a column name and no column appears more than once. - FROM clause specifies only one table, excluding any views based on a join, union, intersection or difference. - No nested SELECT referencing outer table. - No GROUP BY or HAVING clause. - Also, every row added through view must not violate integrity constraints of base table. 30 Leena Gulabivala

Advantages and Disadvantages of Views Advantages of Views Data independence Currency Improved security Reduced complexity Convenience Customization Data integrity Disadvantages of Views Update restriction Structure restriction Performance 31 Leena Gulabivala

References and Further Reading: T CONNOLLY & C BEGG. Database Systems A Practical Approach to Design, Implementation and Management, 4 th Edition. Addison-Wesley, 2005. Chapter 6 SQL Data Definition. T CONNOLLY & C BEGG. Database Solutions A step-by-step guide to building databases, 2 nd Edition. Addison-Wesley, 2004. Chapter on SQL Data Definition. J MORRISON, M MORRISON & R CONRAD. Guide to ORACLE 10g. Thomson Learning, 2006. Chapter 2 Creating and Modifying Database Tables. 32 Leena Gulabivala