SQL Data Definition: Table Creation

Similar documents
SQL. SQL Data Manipulation: Queries

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Full file at

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

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

SQL DATA DEFINITION LANGUAGE

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

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

Lab # 4. Data Definition Language (DDL)

SQL: DDL. John Ortiz Cs.utsa.edu

Basic SQL. Basic SQL. Basic SQL

Full file at

SQL: Data Definition Language

From theory to practice. Designing Tables for an Oracle Database System. Sqlplus. Sqlplus. Technicalities. Add the following to your.

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

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

SQL DATA DEFINITION LANGUAGE

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

Lecture 07. Spring 2018 Borough of Manhattan Community College

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

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

Data Definition Language (DDL)

CSC 453 Database Technologies. Tanu Malik DePaul University

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

CS2300: File Structures and Introduction to Database Systems

Designing Tables for an Oracle Database System. From theory to practice

Tutorial 1 Database: Introductory Topics

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

SQL DATA DEFINITION LANGUAGE

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

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

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

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

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Intro to Database Commands

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

Chapter 1 SQL and Data

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

Using DDL Statements to Create and Manage Tables. Copyright 2006, Oracle. All rights reserved.

SQL Data Definition Language

Simple SQL. Peter Y. Wu. Dept of Computer and Information Systems Robert Morris University

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

The Relational Model of Data (ii)

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

ACCESS isn t only a great development tool it s

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

Creating and Managing Tables Schedule: Timing Topic

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Using DDL Statements to Create and Manage Tables. Copyright 2004, Oracle. All rights reserved.

Principles of Data Management

IBM DB2 UDB V7.1 Family Fundamentals.

3.2.4 Enforcing constraints

Chapter 4: Intermediate SQL

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

Microsoft MOS- Using Microsoft Office Access Download Full Version :

MySQL Creating a Database Lecture 3

EXAMINATIONS 2009 END-YEAR. COMP302 / SWEN304 Database Systems / Database System Engineering. Appendix

1) Introduction to SQL

3ISY402 DATABASE SYSTEMS

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

SQL functions fit into two broad categories: Data definition language Data manipulation language

SQL Structured Query Language Introduction

The Relational Model. CS157A Chris Pollett Sept. 19, 2005.

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

Chapter-14 SQL COMMANDS

The Relational Model. Week 2

Networks and Web for Health Informatics (HINF 6220)

Introduction p. 1 The Logical and Physical View of Tables p. 1 Database Types p. 4 NULLs p. 6 DDL and DML Statements p. 7 Column and Table Constraint

MTAT Introduction to Databases

Part II Relational Databases Data as Tables

SQL Introduction. CS 377: Database Systems

CHAPTER4 CONSTRAINTS

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

Information Systems for Engineers Fall Data Definition with SQL

Referential Integrity and Other Table Constraints Ray Lockwood

Indexes (continued) Customer table with record numbers. Source: Concepts of Database Management

The Structured Query Language Get Started

Fundamentals, Design, and Implementation, 9/e Copyright 2004 Database Processing: Fundamentals, Design, and Implementation, 9/e by David M.

CSC Web Programming. Introduction to SQL

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Lab # 2 Hands-On. DDL Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

Downloaded from

Relational Model. CSE462 Database Concepts. Demian Lessa. Department of Computer Science and Engineering State University of New York, Buffalo

CS634 Architecture of Database Systems Spring Elizabeth (Betty) O Neil University of Massachusetts at Boston

Tables From Existing Tables

Databases. Jörg Endrullis. VU University Amsterdam

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

Creating a Relational Database Using Microsoft SQL Code. Farrokh Alemi, Ph.D.

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

Teach Yourself InterBase

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

Outline. Chapter 3. CREATE TABLE Statement. Tables. Relationships. Common Data Types

Databases-1 Lecture-01. Introduction, Relational Algebra

SQL Structured Query Language (1/2)

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

COMP302. Database Systems

Database Management Systems,

Transcription:

SQL Data Definition: Table Creation ISYS 464 Spring 2002 Topic 11 Student Course Database Student (Student Number, Student Name, Major) Course (Course Number, Course Name, Day, Time) Student Course (Student Number, Course Number) Student Student Student Major Number Name 123 Joe IS 234 Fred IS 345 Mary Acct 456 Sue Mgmt 567 Lee Acct Course Course Course Name Day Time Number ISYS 365 Adv C++ MW 12:30 ISYS 464 Database TTh 9:30 ISYS 565 Data Comm TTh 14:00 IBUS 330 Int Business MW 8:00 FIN 350 Finance MW 14:00 MGMT 405 Org Behavior MW 15:30 MKTG 431 Marketing TTh 8:00 Student Course Student Number Course Number 123 ISYS 365 123 FIN 350 123 MGMT 405 234 ISYS 365 234 FIN 350 234 MGMT 405 234 MKTG 431 345 ISYS 464 567 ISYS 464 567 ISYS 565 567 MGMT 405 678 ISYS 363 678 MGMT 405 1 2 Relational Database Integrity: Entity Integrity No part of a primary key can be null Consequence: Each row has a unique primary key The primary key does not have attributes that are not needed (i.e., it is minimal) Specified when table is created 3 Relational Database Integrity: Referential Integrity A foreign key must either: Match its corresponding primary key in the parent relation, or Be null Consequence: No tuple in a child relation can exist without a matching tuple in the parent relaton, unless its foreign key value is null We cannot add a child to a database without first adding the parent, unless the child's foreign key is null Examples: Trees Networks Specified when table is created 4 CREATE TABLE Statement Basic syntax: CREATE TABLE tablename (columnname datatype {,...}) Reserves space for a table Creates meta-data for a table Does not populate the table Create simple table CREATE TABLE Student Student_Name CHAR(12), Major CHAR(6)) This form does not create a primary key Entity integrity can be violated 5 Primary Key Constraint PRIMARY KEY (columnnamelist) Unique primary key is enforced Enforces entity integrity (no NULL values allowed for any part of primary key) Example: Create table with primary key CREATE TABLE Student Student_Name CHAR(12), Major CHAR(6), PRIMARY KEY (Student_Number)) Example: Create table with composite primary key CREATE TABLE Student_Course Course_Number CHAR(14), PRIMARY KEY (Student_Number, Course_Number)) 6. Not for general distribution. 1

Datatypes SMALLINT INTEGER INT DECIMAL(p,s) DEC(p,s) NUMERIC(p,s) NUMBER(p,s) CHARACTER(n) CHAR(n) VARCHAR(n) CHAR VARYING(n) CHARACTER VARYING(n) VARCHAR2(n) DATE BLOB CLOB Oracle Datatypes Data type Description Comments Standard SMALLINT Integer data between 32768 and +32767 SQL_92 INTEGER Integer data between 2^31 and +2^31 SQL_92 INT DECIMAL(p,s) Decimal numeric data of length p Default p = 38 SQL_92 DEC(p,s) NUMERIC(p,s) (precision) with s (scale) positions to right of decimal point Default s = 0 0<=s<=p<=38 NUMBER(p,s) Synonymous with DECIMAL(p,s) Oracle CHARACTER(n) CHAR(n) VARCHAR(n) CHAR VARYING(n) CHARACTER VARYING(n) Fixed length character data of a length n. Unused characters are filled with blanks on the right. Variable length character data of a maximum length of n. If data is < n in length, no blanks are filled on the right. Default n = 1 Max n = 4096 Default n = 1 Max n = 4096 SQL_92 SQL_92 VARCHAR2(n) Synonymous with VARCHAR(n) Oracle DATE Date Default format: SQL_92 DD-MON-YY BLOB Binary large object Max size: 4 GB Oracle CLOB Character large object Max size: 4 GB Oracle 7 8 NOT NULL constraint Prevents column from containing a NULL value Syntax: NOT NULL UNIQUE constraint Prevents non-unique values in a column; allows NULL values Syntax: UNIQUE Example: CREATE TABLE Course (Course_Number CHAR (14), Course_Name CHAR(12) UNIQUE, Day CHAR (3) NOT NULL, Time CHAR (5) NOT NULL, PRIMARY KEY (Course_Number)) Note: PRIMARY KEY column(s) is automatically NOT NULL and UNIQUE 9 DEFAULT constraint; Sets default value for column if no value is inserted Syntax: DEFAULT literal literal must be same type as datatype of column Example: CREATE TABLE Student Student_Name CHAR(12), Major CHAR(6) DEFAULT 'IS', PRIMARY KEY (Student_Number)) 10 CHECK constraint; Prevents insertion into column of any value that violates of constraint Syntax: CHECK (columnname restriction) restriction can use: <, >, =, <=, >=, <> BETWEEN x AND y IN (set of values) AND, OR, NOT with other restrictions CREATE TABLE Sample_Table ( B_Col CHAR(5), C_Col DEC(10,2) NOT NULL UNIQUE, D_Col INTEGER UNIQUE CHECK (D_Col >= 0), E_Col SMALLINT DEFAULT 0 CHECK (E_Col BETWEEN 0 AND 100), F_Col CHAR(1) DEFAULT 'S' CHECK (F_Col IN ('S','M','D')), PRIMARY KEY (A_Col, B_Col)) 11 12. Not for general distribution. 2

FOREIGN KEY Constraint FOREIGN KEY (columnnamelist) REFERENCES tablename Appears in CREATE TABLE statement for table with foreign key (child) Columnnamelist can refer to single column foreign key or composite foreign key Tablename identifies table in which foreign key is primary key Foreign key does not have to have same name as corresponding primary key Must create parent before creating child with FOREIGN KEY key constraint FOREIGN KEY constraint enforces referential integrity Without FOREIGN KEY constraint referential integrity is not enforced First_Table (A_Col, B_Col, C_Col) Second_Table (X_Col, Y_Col, Z_Col, A_Col) A_Col is foreign key in Second_Table that relates Second_Table to First_Table 13 FOREIGN KEY Constraint Create parent table: CREATE First_Table ( B_Col CHAR(5), C_Col DEC (8,2), PRIMARY KEY (A_Col)) Create child table with foreign key: CREATE Second_Table (X_Col CHAR(10), Z_Col INTEGER, PRIMARY KEY (X_Col, Y_Col), ) 14 Referential Integrity Restrictions Operation Parent Child Unrestricted Rejected if inserted row has a INSERT foreign key that does not match a Rejected if deletion leaves an Unrestricted DELETE unmatched foreign key in a child Rejected if value of parent's primary Rejected if value of child's foreign key is changed in a way that leaves a key is changed in a way that leaves UPDATE foreign key of a child unmatched the foreign key unmatched with a with the primary key 15 ON DELETE CASCADE Option Syntax: ON DELETE CASCADE Causes child rows to be deleted when parent row is deleted ("cascade delete") CREATE Second_Table (X_Col CHAR(10), Z_Col INTEGER, PRIMARY KEY (X_Col, Y_Col), ON DELETE CASCADE) 16 ON DELETE CASCADE Option Referential Integrity Restrictions ON DELETE CASCADE Operation Parent Child Unrestricted Rejected if inserted row has a INSERT* foreign key that does not match a Parent deleted. All children with Unrestricted DELETE matching foreign keys are deleted Rejected if value of parent's primary Rejected if value of child's foreign key is changed in a way that leaves a key is changed in a way that leaves UPDATE* foreign key of a child unmatched the foreign key unmatched with a with the primary key * Same as without ON DELETE CASCADE 17 ON DELETE SET NULL Option Syntax: ON DELETE SET NULL Causes foreign keys of child rows to be set to NULL when parent row is deleted Used when child rows need to be kept rather than deleted CREATE Second_Table (X_Col CHAR(10), Z_Col INTEGER, PRIMARY KEY (X_Col, Y_Col), ON DELETE SET NULL) 18. Not for general distribution. 3

ON DELETE SET NULL Option Referential Integrity Restrictions ON DELETE SET NULL Operation Parent Child Unrestricted Rejected if inserted row has a INSERT* foreign key that does not match a Parent deleted. Foreign keys of all Unrestricted DELETE children with matching foreign keys are set to NULL Rejected if value of parent's primary Rejected if value of child's foreign key is changed in a way that leaves a key is changed in a way that leaves UPDATE* foreign key of a child unmatched the foreign key unmatched with a with the primary key * Same as without ON DELETE CASCADE 19 Changing Key Values How to change the primary key of a parent and all matching children: 1. Insert parent with new primary key 2. Update foreign key of all children of old parent to new primary key value 3. Delete old parent 20 Complex Example First_Table (A_Col, B_Col, C_Col) Second_Table (X_Col, Y_Col, Z_Col, A_Col) Third_Table (S_Col, T_Col, A_Col, X_Col, Y_Col) A_Col in Second_Table is a foreign key that relates Second_Table to First_Table A_Col in Third_Table is a foreign key that relates Third_Table to First_Table X_Col + Y_Col is a composite foreign key in Third_Table that relates Third_Table to Second_Table Problem: Write statement to create Third_Table 21 Complex Example Solution: CREATE TABLE Third_Table (S_Col SMALLINT, T_Col DEC(12,4), X_Col CHAR(10), PRIMARY KEY (S_Col), ON DELETE SET NULL, FOREIGN KEY (X_Col, Y_Col) REFERENCES Second_Table ON DELETE CASCADE) 22 CREATE TABLE Statement: Complete Syntax CREATE TABLE tablename (columnname datatype [NOT NULL] [UNIQUE] [DEFAULT literal] [CHECK (columnname restriction)] {,...} [, PRIMARY KEY (columnnamelist)] [, FOREIGN KEY (columnnamelist) REFERENCES tablename [ON DELETE CASCADE SET NULL]] {,...} ) Populating Tables in a Database If referential integrity is not enforced (i.e., no foreign keys are specified), tables in database can be populated in any order If referential integrity is enforced, tables in database must be populated "top down": Parent table must be populated before child table If a child table has two parent tables, both parent tables must be populated before the child table is populated 23 24. Not for general distribution. 4

Deleting Rows in Tables If referential integrity is not enforced, rows in parent and child tables can be deleted in any order If referential integrity is enforced without the ON DELETE option, rows in child table must be deleted before corresponding rows in parent table are deleted If referential integrity is enforced with the ON DELETE option, rows in parent and child tables can be deleted in any order Deleting a parent row will delete all matching child rows or set their foreign key values to NULL DROP TABLE Statement Syntax: DROP TABLE tablename Deletes table from database DROP TABLE First_Table 25 26 Dropping Tables in a Database If referential integrity is not enforced, parent and child tables can be dropped in any order If referential integrity is enforced without the ON DELETE option, tables must be dropped "bottom up": Child table must be dropped before parent table is dropped If a parent table has two child tables, both child tables must be dropped before the parent table is dropped If referential integrity is enforced with the ON DELETE option, parent and child tables can be dropped in any order Dropping a parent table will not drop a child table but will delete all matching child rows or set their foreign key values to NULL The child table must be dropped separately 27 ALTER Statement Syntax 1: ALTER TABLE tablename ADD (columnname datatype {,... }) Adds a column to a table Example: ALTER TABLE First_Table ADD D_Col CHAR(30) Syntax 2: ALTER TABLE tablename MODIFY (columnname datatype {,... }) Changes the datatype of a column in a table New datatype must not be smaller than previous datatype Example: ALTER TABLE First_Table MODIFY (X_Col CHAR(15)) Syntax 3: ALTER TABLE tablename DROP COLUMN columnname Deletes a column of table Example: ALTER TABLE First_Table DROP COLUMN Y_Col Note: It is best not to alter a table once it is create because doing so can create data problems. Better approach: Create a new table with all the alterations and then populate it with data from the old table. 28 Summary of Statements To create the tables in a database: CREATE TABLE for each table ALTER TABLE to add column, change datatype of column, delete column in existing table To populate the tables in a database: INSERT initial data into each table To access the data in the tables of a database: SELECT data from one or more tables To change the data in the tables of a database INSERT new data into a table DELETE data from a table UPDATE data in a table To delete a table: DROP TABLE Script Files Script file is a text file with a sequence of SQL statements Any SQL statement can be in a script file Each statement must end with a semicolon (;) Use a text editor such as Notepad to create a script file Do not use a word processor such as Word or WordPad Upload script file to your libra account using FTP Execute script file using the SQL*Plus start (or @) command If script file has extension.sql then no extension is needed in start command 29 30. Not for general distribution. 5

Using a Script File to Create and Populate a Database Order of steps in script file to create and populate a database: Use DROP TABLE statements to drop all tables to be created in case they already exist. Be sure to drop tables in correct order Use CREATE TABLE statements to create all new tables Use INSERT statements to populate new tables Be sure to populate tables in correct order Use COMMIT statement to make all updates permanent Example: Script File to Create and Populate Inventory-Quotation-Supplier Database See createiqs.txt file 31 32. Not for general distribution. 6