Ms. Hatoon Al-Sagri CCIS – IS Department SQL-99 :Schema Definition, Constraints, Queries, and Views 1.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Fundamentals of Database Systems Fourth Edition El Masri & Navathe
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
Fall 2005 ICS184/EECS116 – Notes 08 1 ICS 184/EECS116: Introduction to Data Management Lecture Note 8 SQL: Structured Query Language -- DDL.
Overview Begin 6:00 Quiz15 mins6:15 Review Table Terms25 mins6:40 Short Break10 mins6:50 SQL: Creating Tables60 mins7:50 Break10 mins8:00 Lab – Creating.
Database Design -- Basic SQL
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 The Basic (Flat) Relational Model.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
CS 104 Introduction to Computer Science and Graphics Problems Introduction to Database (2) Basic SQL 12/05/2008 Yang Song.
1 Pertemuan 11 SQL Data Definition Matakuliah: >/ > Tahun: > Versi: >
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Spring 2008 Project 1, Lecture 3 Slides adapted from those used by Jeffrey Ullman, via Jennifer.
CSC 240 (Blum)1 Data Definition Language Based on Chapter 6 of Database Systems (Connolly and Begg)
Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial Password: UWPstudent Password is case sensitive.
1 CSE 480: Database Systems Lecture 9: SQL-DDL Reference: Read Chapter of the textbook.
Oracle Data Definition Language (DDL)
CS 380 Introduction to Database Systems (Chapter 5: The Relational Data Model and Relational Database Constraints)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL.
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E) 1. LECTURE OUTLINE  SQL Data Definition and Data Types  Specifying Constraints in SQL  Basic Retrieval Queries.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: Schema Definition, Constraints, and Queries and Views.
Structured Query Language The main reference of this presentation is the textbook and PPT from : Elmasri & Navathe, Fundamental of Database Systems, 4.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
CG084&085 / / 1 The Relational Data Model Properties of Relations Keys and Constraints.
Chapter 6 SQL Data Definition Language Chapter 7 in Textbook.
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
-Software School of Hunan University-
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Chapter 5: Part 1: DDL STRUCTURED QUERY LANGUAGE (SQL)
SQL: DDL John Ortiz Cs.utsa.edu.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Tables and Constraints Oracle PL/SQL. Datatypes The SQL Data Definition Language Commands (or DDL) enable us to create, modify and remove database data.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Prince Sultan University Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Chapter Name SQL: Data Definition
Lu Chaojun, SJTU Relational Data Model 1. Lu Chaojun, SJTU What’s a Data Model? A notation (collection of conceptual tools) for describing data as seen.
Lecture5: SQL Overview, Oracle Data Type, DDL and Constraints Ref. Chapter6 Lecture4 1.
CS 338The Relational Model2-1 The Relational Model Lecture Topics Overview of SQL Underlying relational model Relational database structure SQL DDL and.
CSE314 Database Systems Lecture 3 The Relational Data Model and Relational Database Constraints Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1.
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
Data Definition Language
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Physical Model Lecture 11. Physical Data Model The last step is the physical design phase, In this phase data is – Store – Organized and – Access.
CDT/1 Creating data tables and Referential Integrity Objective –To learn about the data constraints supported by SQL2 –To be able to relate tables together.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Chapter 10 SQL DDL.
Fundamental of Database Systems
國立臺北科技大學 課程:資料庫系統 Chapter 7 SQL Data Definition.
Managing Tables, Data Integrity, Constraints by Adrienne Watt
SQL: Schema Definition and Constraints Chapter 6 week 6
Chapter 4 Basic SQL.
Minggu 5, Pertemuan 9 SQL: Data Definition
STRUCTURED QUERY LANGUAGE
لغة قواعد البيانات STRUCTURED QUERY LANGUAGE SQL))
CS4222 Principles of Database System
Oracle Data Definition Language (DDL)
SQL-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
SQL (Structured Query Language)
Presentation transcript:

Ms. Hatoon Al-Sagri CCIS – IS Department SQL-99 :Schema Definition, Constraints, Queries, and Views 1

Database Design 2 Steps in building a database for an application: Real-world domain Conceptual model DBMS data model Create Schema (DDL) Create Schema (DDL) Load data (DML)

DDL Statements The main SQL data definition language statements are used to CREATE, DROP, and ALTER the descriptions of the tables (relations) of a database. CREATE SCHEMA DROP SCHEMA CREATE DOMAIN ALTER DOMAIN DROP DOMAIN CREATE TABLE ALTER TABLE DROP TABLE CREATE VIEW DROP VIEW CREATE INDEX DROP INDEX 3

Notations Notations to define SQL statements: UPPER-CASE letters represents reserved words Lower-case letters represents user-defined words | indicates a choice among alternatives; (e.g. a | b | c) { } indicates a required element [ ] indicates an optional element … indicates optional repetition of an item zero or more times Underlined words represent default values 4

Identifiers May contain A-Z, a-z, 0-9, _ No longer than 128 characters Start with letter Cannot contain spaces 5

Attribute data types and domains in SQL Type SQL Data Type Used Numeric INTEGER or INT and SMALLINT Integer numbers of various sizes. NoRoom SMALLINT FLOAT or REAL and DOUBLE PRECISION Floating-point (real) numbers of various precision NUMERIC (i, j) or DECIMAL (i, j) Formatted numbers, where i The precision and j the scale. salary DECIMAL(7,2) Character -string CHAR(n) or CHARACTER(n) Fixed length, where n is the number of characters Bno CHAR(4) VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n) Varying length, where n is the maximum number of characters Name VERCHAR(15) 6

Attribute data types and domains in SQL Type SQL Data Type Used Bit-string BIT(n) Fixed length, where n is the number of bits (0 or 1) BitSt BIT(4) BIT VARYING (n) Varying length, where n is the maximum number of bits. BitSt BIT VARYING(4) Boolean BOOLEAN There are three values (TRUE,FALSE and UNKNOWN) 7

Attribute data types and domains in SQL Type SQL Data Type Used Date_Time DATE Has ten positions. Made up of year- month-day in the format yyyy-mm-dd ViewDate DATE TIME Made up of hour:minute:second in the format hh:mm:ss ViewTime TIME TIME(i) Made up of hour:minute:second plus i additional digits specifying fractions of a second. format is hh:mm:ss:i Timestamp TIMESTAMP Has both DATE and TIME components INTERVAL Specifies a relative value rather than an absolute value. 8

Schema concepts in SQL Schema is a named collection of related database objects (tables, views, domains,..) who belong to the same database application. Specifies a new database schema by giving it a name. An SQL schema is identified by a schema name and includes an authorization identifier to indicate the user or account who owns the schema. 9

Creating a DB Syntax CREATE SCHEMA [Name | AUTHORIZATION Identifier] Example CREATE SCHEMA COMPANY AUTHORIZATION Jsmith; 10

Domains in SQL It is possible to specify the data type of each attribute directly or a domain can be declared and the domain name used with the attribute specification. Syntax: CREATE DOMAIN domainName [AS] datatype [DEFAULT default option] [CHECK (search condition)]; Example: CREATE DOMAIN SSN_TYPE AS CHAR(9); 11

Domains in SQL Example: CREATE DOMAIN DepartmentNo AS INT;. DnoDepartmentNo, 12

Creating a Table Syntax CREATE TABLE tablename { ( {columnName dataType [NOT NULL | NULL] [UNIQUE] [DEFAULT defaultOption,] [CHECK (search condition),] (,…) } [PRIMARY KEY (column (,…) ),] [UNIQUE (column (,…) ),] [FOREIGN KEY (FK column (,…) ) REFERENCES tablename [(CK column (,…))] [ON UPDATE ReferentialAction] [ON DELETE ReferentialAction], ] [CHECK (search condition)] ) } 13

Creating a Table Specifies a new relation by giving it a name, and specifying each of its attributes and their data types. A constraint NOT NULL may be specified on an attribute. Example: CREATE TABLE DEPARTMENT ( DnameVARCHAR(10)NOT NULL, DnumberINTEGERNOT NULL, Mgr_ssnCHAR(9), Mgr_start_dateCHAR(9) ); 14

DROP Schema The DROP command can be used to drop the whole schema or drop table and its definition. Two drop behavior options: – CASCADE, drops all objects associated with schema – RESTRICT, schema must be empty. Syntax DROP SCHEMA Name [RESTRICT | CASCADE] Example: DROP SCHEMA COMPANY CASCADE ; 15

DROP Table The relation can no longer be used in queries, updates, or any other commands since its description no longer exists. Syntax: DROP TABLE tablename [RESTRICT | CASCADE]; Example: DROP TABLE DEPENDENT CASCADE; Two drop behavior options: – CASCADE, drop operation drops all column from objects it is referenced by – RESTRICT, drop operation is rejected if the column is referenced by another database object. 16

DROP Domain Syntax: DROP DOMAIN DomainName [RESTRICT | CASCADE]; RESTRICT, domain must not be used in any existing table, view or assertion. CASCADE, any column based on the domain is automatically changed to use the underlying data type, column constraint and default clause. 17

Specifying attribute constraints Three types of attribute constraints: 1. Required data 2. Defaults value 3. Domain values constraints 18

1. Required data Null is distinct from blank or zero. When NOT NULL is specified, the system rejects any attempt to insert a null in the column. Syntax: columnName dataType [NOT NULL | NULL] Example: Dname VARCHAR(10)NOT NULL, 19

2. Defaults value – It is possible to define a default value for an attribute by appending the DEFAULT value to an attribute definition. – Example: DnoINTNOT NULL DEFALT 1, 20

3. Domain values constraints: CHECK Restrict attribute values using CHECK. Syntax: CHECK (search condition) Example: Attribute (Column-Based CHECK) Dnumber INT NOT NULL CHECK(Dnumber>0 AND Dnumber<12), Domain definition (Column-Based CHECK) CREATE DOMAIN D_num AS INTEGER CHECK(D_num>0 AND D_num<12); 21

Domain values constraints: CHECK Examples sex CHAR NOT NULL CHECK (sex In (‘M’, ‘F’)) salary DECIMAL NOT NULL CHECK (salary > 10000); CREATE DOMAIN SexType AS CHAR DEFAULT ‘M’ CHECK (VALUE IN (‘M’, ‘F’)); 22

Domain values constraints: CHECK – Other table constraints can be specified through additional CHECK clauses at the end of a CREATE TABLE statement. – Called tuple-based constraints because they apply for each tuple individually and are checked whenever a tuple is inserted or modified. – Example: CHECK (Dept_create_date <= Mgr_start_date) 23

Specifying key and referential integrity constraints PRIMARY KEY UNIQUE FOREIGN KEY 24

Specifying key and referential integrity constraints PRIMARY KEY clause specifies one or more attributes that make up the primary key of a relation. Syntax: PRIMARY KEY (attribute (,…)) SQL rejects any operations that attempt to create duplication in the PK column. PK forbids NULL value. 25

Specifying key and referential integrity constraints If the primary key has a single attribute, the clause can follow the attribute directly. Example: DnumberINTEGERNOT NULL,. PRIMARY KEY (Dnumber), or DnumberINTEGERPRIMARY KEY, Composite PK: PRIMARY KEY (cno, pno), 26

Specifying key and referential integrity constraints The UNIQUE clause specifies alternate (Secondary). UNIQUE permits NULL value. Every column that appears in a UNIQUE clause must also be declared in as NOT NULL. Syntax: UNIQUE(attribute (,…)) 27

Specifying key and referential integrity constraints Example:UNIQUE can appear after a column definition or separately: DnameVARCHAR(10)NOT NULL,. UNIQUE (Dname), Or DnameVARCHAR(10)NOT NULL UNIQUE, Example: cno VARCHAR(5) NOT NULL, pno VARCHAR(5) NOT NULL, UNIQUE(cno, pno), 28

Specifying key and referential integrity constraints Referential integrity is specified via the FOREIGN KEY clause. FOREIGN KEY clause is defined in the CREATE & ALTER TABLE statements. Syntax: FOREIGN KEY (attribute (,…)) REFERENCES table_name [(attribute (,…))] Example: FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE (Ssn) SQL rejects any insert, update or delete operation that attempts to create a foreign key value without a matching PK value key. The schema designer can specify an alternative action by attaching a referential triggered action on UPDATE or DELETE operation. 29

REFERENTIAL INTEGRITY OPTIONS Four options are supported when the user attempt to delete or update a PK, and there are matching FKs: CASCADE: automatically delete/update the PK row & all matching (FKs) rows in child table SET NULL: delete/update the PK row & set the FK values to NULL SET DEFAULT: delete/update the PK row & set the FK values to default. Valid only if DEFAULT clause is specified. NO ACTION: rejects the delete or update operation. Syntax FOREIGN KEY (FK column (,…) ) REFERENCES tablename [(CK column (,…))] [ON UPDATE [CASCADE | SET NULL| SET DEFAULT| NO ACTION] ] [ON DELETE [CASCADE | SET NULL| SET DEFAULT| NO ACTION] ] 30

REFERENTIAL INTEGRITY OPTIONS We can specify RESTRICT, CASCADE, SET NULL or SET DEFAULT on referential integrity constraints (foreign keys). CREATE TABLE DEPARTMENT ( DnameVARCHAR(10) NOT NULL, DnumberINTEGER NOT NULL, Mgr_ssnCHAR(9), Mgr_start_dateCHAR(9), PRIMARY KEY (Dnumber), UNIQUE (Dname), FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE (Ssn) ON DELETE SET NULL ON UPDATE CASCADE); 31

REFERENTIAL INTEGRITY OPTIONS CREATE TABLE EMPLOYEE( EnameVARCHAR(30)NOT NULL, EssnCHAR(9), BdateDATE, DnoINTEGER DEFAULT 1, SuperssnCHAR(9), PRIMARY KEY (Essn), FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber) ON DELETE SET DEFAULT ON UPDATE CASCADE, FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(Ssn) ON DELETE SET NULL ON UPDATE CASCADE); 32

“COMPANY” Relational Database Schema 33

SQL Create Table data definition statements for defining the COMPANY Schema 34

SQL Create Table data definition statements for defining the COMPANY Schema 35

Specifying Constraints in SQL: Giving Names to constraints: – The constraints can be given a constraint name, following the keyword CONSTRAINT. – The name must be unique. – In order to modify or delete an existing constraint, it is necessary that the constraint have a name. Sex CHAR CONSTRAINT SexTypeValid CHECK (sex IN (‘F’, ‘M’) ) Dept CHAR(4) NOT NULL CONSTRAINT DepNoInList CHECK( Dno IN (SELECT Dept FROM DEPARTMENT)) CONSTRAINT IDISKey PRIMARY KEY (SSN) 36

37

Changing a Table Definition ALTER consists of six options to:  Add a column to table  Drop a column from a table  Add a table constraint  Drop a table constraint  Set a default for a column  Drop a default for a column 38

Changing a Table Definition Syntax: ALTER TABLE tablename [ADD [COLUMN] ColumnName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption] [CHECK (search condition)] ] [DROP [COLUMN] ColumnName [RESTRICT | CASCADE]] [ADD [CONSTRAINT [Constraint Name]] TableConstraint Definition] [DROP CONSTRAINT ConstraintName [RESTRICT | CASCADE]] [ALTER ColumnName SET DEFAULT DefaultOption] [ALTER ColumnName DROP DEFAULT]; RESTRICT, drop operation is rejected if the column is referenced by another database object (e.g. view). CASCADE, drop operation drops all column from objects it is referenced by. 39

Changing a Table Definition Example: Add an attribute for keeping track of jobs of staff in the company schema ALTER TABLE staff ADD job VARCHAR(12); Example: Remove the address attribute from the staff table ALTER TABLE staff DROP address CASCASE; 40

Changing a Table Definition Example: Change the staff table by removing the default of ‘Assistant’ for the position column and setting the default for the sex column to female. ALTER TABLE staff ALTER position DROP DEFAULT; ALTER TABLE staff ALTER sex SET DEFAULT ‘F’; 41

Changing a Table Definition Example: Change the PropertyForRent table by removing the constraint that the staff are not allowed more than 100 properties at a time. ALTER TABLE PropertyForRent DROP CONSTRAINT StaffNotHandlingTooMuch CASCADE; 42

43 Material for this lecture was obtained from: – Fundamentals of Database Systems, Elmasri and Navathe, 5th edition, Addison-Wesley, – Database Systems: A Practical Approach to Design, Implementation and Management, Thomas Connolly, Carolyn Begg, 3 rd edition, – The slides of dr. Lilac Safadi, King Saud University. – The slides of T. Abeer Al-Nafjan, Asma AlSaleh Imam University.