Data Definition Language (DDL)

Similar documents
Lab # 4. Data Definition Language (DDL)

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

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

Database design process

SQL Introduction. CS 377: Database Systems

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

SQL STRUCTURED QUERY LANGUAGE

Overview Relational data model

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

COSC344 Database Theory and Applications. σ a= c (P) S. Lecture 4 Relational algebra. π A, P X Q. COSC344 Lecture 4 1

ECE 650 Systems Programming & Engineering. Spring 2018

ECE 650 Systems Programming & Engineering. Spring 2018

COSC Assignment 2

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

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

L130 - DATABASE MANAGEMENT SYSTEMS LAB CYCLE-1 1) Create a table STUDENT with appropriate data types and perform the following queries.

Slides by: Ms. Shree Jaswal

CS 348 Introduction to Database Management Assignment 2

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

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

Database Technology. Topic 3: SQL. Olaf Hartig.

A taxonomy of SQL queries Learning Plan

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

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

DATABASE CONCEPTS. Dr. Awad Khalil Computer Science & Engineering Department AUC

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

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

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

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

Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries

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

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

Part 1 on Table Function

RELATIONAL DATA MODEL

SQL-99: Schema Definition, Basic Constraints, and Queries. Create, drop, alter Features Added in SQL2 and SQL-99

CIS611 Lab Assignment 1 SS Chung

Advanced Databases (SE487) Prince Sultan University College of Computer and Information Sciences

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

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

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

Full file at

Session Active Databases (2+3 of 3)

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

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

CS2300: File Structures and Introduction to Database Systems

CSIE30600 Database Systems Basic SQL 2. Outline

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

Guides for Installing MS SQL Server and Creating Your First Database. Please see more guidelines on installing procedure on the class webpage

The Relational Data Model and Relational Database Constraints

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

Some different database system architectures. (a) Shared nothing architecture.

Lecture 07. Spring 2018 Borough of Manhattan Community College

Chapter 6: RELATIONAL DATA MODEL AND RELATIONAL ALGEBRA

SQL. Copyright 2013 Ramez Elmasri and Shamkant B. Navathe

DBMS LAB SESSION PAVANKUMAR MP

CHAPTER4 CONSTRAINTS

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

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

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

Basic SQL. Basic SQL. Basic SQL

3ISY402 DATABASE SYSTEMS

Information Systems Development 37C Lecture: Final notes. 30 th March 2017 Dr. Riitta Hekkala

Relational Model. CS 377: Database Systems

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra

CSC 742 Database Management Systems

Announcement5 SQL5. Create%and%drop%table5. Basic%SFW%query5. Reading%a%table5. TDDD37%% Database%technology% SQL5

Relational Algebra 1

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

SQL DATA DEFINITION LANGUAGE

15CSL58: DATABASE MANAGEMENT LABORATORY

Chapter 8: Relational Algebra

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

More SQL: Complex Queries, Triggers, Views, and Schema Modification

Relational Database Systems Part 01. Karine Reis Ferreira

CS5300 Database Systems

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

CMP-3440 Database Systems

SQL- Updates, Asser0ons and Views

SQL: DDL. John Ortiz Cs.utsa.edu

SQL DATA DEFINITION LANGUAGE

Advanced Databases. Winter Term 2012/13. Prof. Dr. Dietmar Seipel University of Würzburg. Advanced Databases Winter Term 2012/13

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

Oracle User Administration

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

MIT Database Management Systems Lesson 03: ER-to-Relational Mapping

SQL: Data Definition Language

This chapter discusses how to design a relational

SQL DATA DEFINITION LANGUAGE

Structured Query Language (SQL)

MTAT Introduction to Databases

Creating and Managing Tables Schedule: Timing Topic

Oracle Tables TECHGOEASY.COM

COSC344 Database Theory and Applications. Lecture 11 Triggers

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

More SQL: Complex Queries, Triggers, Views, and Schema Modification

PES Institute of Technology Bangalore South Campus (1 K.M before Electronic City,Bangalore ) Department of MCA. Solution Set - Test-II

CSC 453 Database Technologies. Tanu Malik DePaul University

Ref1 for STUDENT RECORD DB: Ref2 for COMPANY DB:

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

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Database Lab (ECOM 4113) Lab 6 Data Definition Language (DDL) Eng. Mohammed Alokshiya November 11, 2014

Database Keys A key is a logical way to access a record in a table. There are many types of key in Relational Databases like Oracle: Candidate Key A candidate key is any field, or combination of fields, that uniquely identifies a record. The field/s of the candidate key must contain unique values, and cannot contain a null value. Primary Key (PK) A primary key is the candidate key that has been chosen to identify unique records in a particular table. Foreign Key (FK) A relationship between two tables is created by creating a common field to the two tables. The common field must be a primary key to the one table. Database Schemas A database is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL and include the following types of objects: Tables Views Synonyms Functions Procedures Sequences Packages Indexes etc. Schema Creating To create a new schema in default XE database, we have to create a new user and Oracle creates a schema for that user with the same name. 2

To create a new user, connect to XE database by SYSTEM user (or any user with sufficient privileges), and issue the following command: CREATE USER CREATE USER USER_NAME IDENTIFIED BY USER_PASSWORD DEFAULT TABLESPACE USERS QUOTA 10M ON USERS; In general, the syntax of CREATE USER statement is: 3

Granted Privileges: If you try to connect to database with the new user, you will get a message ORA-01045: user USER_NAME lacks CREATE SESSION privilige; logon denied The reason for that error is: we are trying to connect to our database using a user that do not have any privileges. So, before you leave SYSTEM connection, you have to grant some needed privileges for our new user. Grant Privileges and Roles GRANT CREATE SESSION, RESOURCE, CREATE VIEW, CREATE SYNONYM, CREATE MATERIALIZED VIEW, ALTER SESSION TO USER_NAME; Create session: to be able to connect to XE database by the new user. Connect: CONNECT is a pre-defined ROLE in Oracle. A role is a set of privileges that can be granted to users or to other roles. To know which privileges are granted to CONNECT role, then execute the following statement: 4

SELECT PRIVILEGE FROM DBA_SYS_PRIVS WHERE GRANTEE = 'RESOURCE'; Display Privileges Granted to a Role Alter session: to set or modify any of the conditions or parameters that affect your connection to the database. Table Creating CREATE TABLE Syntax CREATE TABLE TABLE_NAME ( COL_1 DATATYPE [COL. DEFAULT] [INLINE CONSTRAINTS], COL_1 DATATYPE [COL. DEFAULT] [INLINE CONSTRAINTS],... [OUT OF LINE CONSTRAINTS] ); 5

Data Types CHARACTER TYPES Data Type Description Notes CHAR [(n[byte CHAR])] A set of characters exactly n characters in length, padded with spaces. If you attempt to store a string that is too long, an error will be generated. NCHAR[(n)] VARCHAR2(n [byte char]) NVARCHAR2(n) A fixed length Unicode character string having maximum length n characters. Default and minimum n is 1 character. A Variable length character string having maximum length n bytes or characters. You must specify size for VARCHAR2. Minimum size is 1 byte or 1 character. A Variable length Unicode character string having maximum length n characters. You must specify size for NVARCHAR2. To specify a value to character data types, it is placed between single quotation marks ('), and it is a case sensitive, e.g., 'Hello'. Use concatenation operator ( ) to concatenate two strings, e.g. 'abc' 'def' results 'abcdef'. NUMERIC TYPES Data Type Description Range Number [(p[, s])] User-specified precision, scale. The precision is the number of digits to both sides of the decimal point. The positive scale is the count of decimal digits in the fractional part, to the right of the decimal point. If the scale of a value to be stored is greater than the declared scale of the column, the system will round the value to the specified number of fractional digits. When the scale is positive and the number of digits to the left of the decimal point exceeds (p-s), an error is raised. Number(p) = Number(p,0) s=0. The precision p can range from 1 to 38. The scale s can range from -84 to 127. A NUMBER value requires from 1 to 22 bytes. 6

Float [(p)] BINARY_FLOAT Binary_Double A subtype of the NUMBER data type having precision p. A FLOAT value is represented internally as NUMBER. The precision p can range from 1 to 126 binary digits. To convert from binary to decimal precision, multiply p by 0.30103. BINARY_FLOAT is a 32-bit, single-precision floating-point number data type. BINARY_DOUBLE is a 64-bit, double-precision floating-point number data type. A FLOAT value requires from 1 to 22 bytes. 15 decimal digit. Each BINARY_FLOAT value requires 4 bytes. Each BINARY_DOUBLE value requires 8 bytes. BINARY DATA TYPES Data Type Description RAW(n) Raw binary data of max length n bytes. You must specify size for a RAW value. LONG RAW Raw binary data of variable length up to 2 gigabytes. DATE/TIME DATA TYPES Data Type Description Notes Example Date Date and Time. Its components are YEAR, MONTH, DAY, HOUR, MINUTE and SECOND. The default format is: To specify a value to Date types, you can: Place the value between single quotation marks in DD-MON-YY format. '31-MAY-02' '31-MAY-2002' DD-MON-YY. SYSDATE: special value that is current system date. To specify a value for Timestamps DataType, you can: 7

timestamp [(p)] Timestamp [(p)] with time zone Includes the DATE and TIME fields. The Default format is: DD-MON-YY HH.MM.SS.p AM/PM Timestamp with time zone displacement value. The Default format is: DD-MON-YY HH.MM.SS.p AM/PM +/- HH:MM/time zone Place the value in (') marks in DD-MON-YY HH:MM:SS.p [AM/PM] [+/-HH:MM/time zone] Format. Hour from (1-12). +/-HH:MM/time zone for timestamp with time zone data type. AM/PM required for timestamp with time zone data type. If you don t specify AM/PM for timestamp and timestamp with local time zone data types the default is AM. '31-MAY-02 10:30:56' '31-MAY-02 10:30:56 PM' Timestamp '2002-05-02 10:30:56.25' 31-MAY-03 10:30:56 AM +08:00 '04-Jul-05 4:5:6 PM ASIA/JERUSALEM' Timestamp '2002-05-02 15:30:56.36-07:00' Timestamp [(p)] with local time zone Timestamp with the local time zone. The Default format is: DD-MON-YY HH.MM.SS.p AM/PM Use Timestamp literal and YYYY-MM-DD HH:MM:SS.p [+/- HH:MM/time zone] format Hour from (0-23) +/- HH:MM/time zone for timestamp with time zone data type. P: is an optional fractional seconds precision, it can be specified timestamp, and interval types. Timestamp 2002-05-02 15:30:56.36 ASIA/JERUSALEM' 31-MAY-14 10:30:56 31-MAY-14 10:30:56 PM Timestamp 2013-05-06 10:30:56 P can be from 0 to 9. The default p is 6. 8

If the number of digits of a value to be stored is greater than the declared P, the system will round the value to the specified P. INTERVAL YEAR [(p)] TO MONTH Stores a period of time in years and months. P: is the number of digits in the YEAR field. To specify a value for this data type: Interval YY-MM year to month. Interval 1-2 year to month. P can from 0 to 9. The default p is 2. INTERVAL DAY [(D)] TO SECOND [(p)] Stores a period of time in days, hours, minutes, and seconds. D: is the maximum number of digits in the DAY field. To specify a value for this data type: Interval D HH:MM:SS.p Day to second Interval 3 12:4:5 Day to Second D range: 0 to 9. The default D is 2. P: is the number of digits in the fractional part of the SECOND field. P can from 0 to 9. The default p is 2. 9

Default Values A column can be assigned a default value. When a new row is created and no values are specified for some of the columns, those columns will be filled with their respective default values. If no default value is declared explicitly, the default value is the null value. In a table definition, default values are listed after the column data type. CREATE TABLE EMPLOYEE (.. SALARY NUMBER (6,2) DEFAULT 2000,.. ); SQL Constraints SQL allows you to define constraints on columns and tables. Constraints give you as much control over the data in your tables as you wish. If a user attempts to store data in a column that would violate a constraint, an error is raised. Constraints Types: NOT NULL: prohibits a database value from being null. Unique: prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null. Primary key: combines a NOT NULL constraint and a unique constraint in a single declaration. It prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null. Check: requires a value in the database to comply with a specified condition. Foreign key: requires values in one table to match values in another table. You can define constraints syntactically in two ways: As a part of the definition of an individual column or attribute. This is called inline specification. 10

As a part of the table definition. This is called out-of-line specification. Notes: NOT NULL constraints must be declared inline. All other constraints can be declared either inline or out of line. The constraint on a combination of columns must be declared out of line. You cannot designate the same column or combination of columns as both a primary key and a unique key. In Line Constraint [CONSTRAINT CONST_NAME] CONST_TYPE [CONST_SPECIFICATIONS] Out of Line Constraint [CONSTRAINT CONST_NAME] CONST_TYPE (COLUMN[S]) [CONST_SPECIFICATIONS] Constraint const_name specifies a name for the constraint. If you omit this identifier, then Oracle Database generates a name. Constraint name clarifies error messages and allows you to refer to the constraint when you need to change it. Not Null Constraint It must be declared in line. Not Null Constraint [CONSTRAINT CONST_NAME] NOT NULL Unique Constraint [CONSTRAINT CONST_NAME] UNIQUE UNIQUE Constraint [In Line] UNIQUE Constraint [Out of Line] [CONSTRAINT CONST_NAME] UNIQUE (COLUMN[S]) 11

Primary Key Constraint [CONSTRAINT CONST_NAME] PRIMARY KEY PRIMARY KEY Constraint [In Line] PRIMARY KEY Constraint [Out of Line] [CONSTRAINT CONST_NAME] PRIMARY KEY (COLUMN[S]) Check Constraint CHECK Constraint [In and Out of Line] [CONSTRAINT CONST_NAME] CHECK (Boolean Expression) Foreign Key Constraint A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table. This maintains the referential integrity between two related tables. When Deleting or updating a referenced row, Oracle allows you to handle that as well. There are two options: CASCADE if you want Oracle to remove/update dependent foreign key values. SET NULL if you want Oracle to convert dependent foreign key values to NULL. Foreign Key Constraint [In Line] [CONSTRAINT CONST_NAME] REFERENCES REFERENCED_TABLE (REFERENCED_COL) [ON {DELETE UPDATE} SET NULL CASCADE] Foreign Key Constraint [Out of Line] [CONSTRAINT CONST_NAME] FOREIGN KEY (COLUMN_NAME) REFERENCES REFERENCED_TABLE (REFERENCED_COL) [ON {DELETE UPDATE} SET NULL CASCADE] 12

If you omit ON DELETE or ON UPDATE clause, then Oracle does not allow you to delete or update referenced key values in the parent table that have dependent rows in the child table. Note: Foreign key column data type must be as same as referenced column. Modifying Tables Alter Table command allow you to alter the definition, or structure, of the table, such you can: Add columns. Remove columns. Add constraints. Remove constraints. Change default values. Change column data types. Rename columns. Rename tables. Add Column ADD COLUMN_NAME DATATYPE [COL. DEFAULT] [INLINE CONSTRAINTS] MODIFY COLUMN_NAME NEW_DATATYPE Modify Column Data Type Note: You can change the data type of any column if all rows of the column contain nulls. Specifying Column Default Value MODIFY COLUMN_NAME DEFAULT DEFAULT_VALUE; 13

To discontinue previously specified default values, so that they are no longer automatically inserted into newly added rows, replace the values with NULL. MODIFY COLUMN_NAME DEFAULT NULL; Remove Default Value Rename Column RENAME COLUMN COLUMN_NAME TO NEW_OLUMN_NAME; DROP COLUMN COLUMN_NAME [CASCADE]; Remove Column CASCADE: if you want to drop everything that depends on the column. ADD OUT_OF_LINE_CONSTRAINT; Add Out of Line Constraint To add a not-null constraint, which cannot be written as out of line constraint, use this syntax: MODIFY COLUMN_NAME NOT NULL; Add Not Null Constraint Rename Constraint RENAME CONSTRAINT CONSTRAINT_NAME TO NEW_CONSTRAINT_NAME; Remove Constraint DROP CONSTRAINT CONSTRAINT_NAME [CASCADE]; 14

MODIFY COLUMN_NAME NULL; Remove Not Null Constraint RENAME TO NEW_NAME; Rename Table DROP TABLE TABLE_NAME [CASCADE]; Remove Table 15

Example: Solution: 1. Create First Table (Least dependent table): Create Table EMPLOYEE CREATE TABLE EMPLOYEE ( Fname VARCHAR2 (20) NOT NULL, Minit VARCHAR2(1), Lname VARCHAR2 (20) NOT NULL, Ssn NUMBER(9) PRIMARY KEY, Bdate DATE, Address VARCHAR2(100), Sex NUMBER (1) CHECK (Sex BETWEEN 0 AND 1), Salary NUMBER(6) DEFAULT 2000 NOT NULL, Super_ssn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Dno NUMBER(6) ); 16

Note: Dno is a foreign key references the Department table but we haven t created DEPARTMENT table yet, so we can t add foreign constraint here, and we need to alter EMPLOYEE table to add the foreign constraint after DEPARTMENT creating. To view the tables in the schema, R-Click on Tables >> Refresh. 2. Second Table: Department Create Table DEPARTMENT CREATE TABLE DEPARTMENT ( Dname VARCHAR2(20) NOT NULL UNIQUE, Dno NUMBER(6) PRIMARY KEY, Mgr_ssn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Mgr_start_date DATE ); Now you can alter the first table (Employee) to add foreign key constraint Alter Table EMPLOYEE ALTER TABLE EMPLOYEE ADD ( CONSTRAINT FK FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dno) ); 17

3. Create other tables Create Other Tables CREATE TABLE DEPT_LOCATIONS ( Dnumber NUMBER(6) REFERENCES DEPARTMENT(Dnumber), Dlocation VARCHAR2 (20), CONSTRAINT PK PRIMARY KEY (Dnumber, Dlocation) ); CREATE TABLE PROJECT ( Pname VARCHAR2(20) NOT NULL UNIQUE, Pnumber NUMBER(6) PRIMARY KEY, Plocation VARCHAR2(20), Dnum NUMBER(6) REFERENCES DEPARTMENT(Dnumber) ); CREATE TABLE WORKS_ON ( Essn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Pno NUMBER(6) REFERENCES DEPARTMENT(Dnumber), Hours NUMBER(3), PRIMARY KEY (Essn, Pno) ); CREATE TABLE DEPENDENT ( Essn NUMBER(9) REFERENCES EMPLOYEE(Ssn), Dependent_name VARCHAR2(20) NOT NULL, Sex NUMBER (1) CHECK (Sex BETWEEN 0 AND 1), Bdate DATE, Relationship NUMBER (2), PRIMARY KEY (Essn, Dependent_name) ); Note that Oracle DMBS generates names for constraints If you omit this the name. To display the auto-generated names for a table constraints, use the following command: Display Table Constraints SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION FROM USER_CONSTRAINTS; 18

Example: Display constrains for EMPLOYEE table columns 19

Exercise: Given the following relations, create a new user in your Oracle database; grant sufficient privileges then create all the tables with appropriate constraints. 20