Lab # 4. Data Definition Language (DDL)

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

Data Definition Language (DDL)

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

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

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

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

Full file at

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

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

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

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

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

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

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

SQL DATA DEFINITION LANGUAGE

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

TINYINT[(M)] [UNSIGNED] [ZEROFILL] A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

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

Slides by: Ms. Shree Jaswal

SQL DATA DEFINITION LANGUAGE

Oracle Database 10g: Introduction to SQL

Creating and Managing Tables Schedule: Timing Topic

SQL: Data Definition Language

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

SQL DATA DEFINITION LANGUAGE

1. Using Bitvise SSH Secure Shell to login to CS Systems Note that if you do not have Bitvise ssh secure shell on your PC, you can download it from

STRUCTURED QUERY LANGUAGE (SQL)

Basic SQL. Basic SQL. Basic SQL

Oracle Syllabus Course code-r10605 SQL

Lab # 1. Introduction to Oracle

Introduction to Computer Science and Business

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

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

INTRODUCTION TO DATABASE

Oracle User Administration

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

Database design process

Lab # 6. Data Manipulation Language (DML)

Using SQL with SQL Developer 18.1 Part II

Course Outline and Objectives: Database Programming with SQL

Data Manipulation Language (DML)

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

Oracle Tables TECHGOEASY.COM

3ISY402 DATABASE SYSTEMS

Using SQL with SQL Developer Part II

Physical Design of Relational Databases

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

Using SQL with SQL Developer 18.2

M.C.A. (CBCS) Sem.-III Examination November-2013 CCA-3004 : Database Concepts and Tools. Faculty Code: 003 Subject Code:

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

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

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

Chapter 1 SQL and Data

Lecture 07. Spring 2018 Borough of Manhattan Community College

CS2300: File Structures and Introduction to Database Systems

SQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

2 PL/SQL - fundamentals Variables and Constants Operators SQL in PL/SQL Control structures... 7

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

CSIE30600 Database Systems Basic SQL 2. Outline

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

Full file at

normalization are being violated o Apply the rule of Third Normal Form to resolve a violation in the model

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

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

SQL STRUCTURED QUERY LANGUAGE

Basant Group of Institution

DB Creation with SQL DDL


Mahathma Gandhi University

Lab # 9. Java to Database Connection

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

Principles of Data Management

SQL Introduction. CS 377: Database Systems

Business Analytics. SQL PL SQL [Oracle 10 g] P r i n c e S e t h i w w w. x l m a c r o. w e b s. c o m

CMP-3440 Database Systems

SQL DDL II. CS121: Relational Databases Fall 2017 Lecture 8

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

SQL Structured Query Language (1/2)

Introduction to Oracle

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

Overview Relational data model

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

5. Single-row function

Relational Database Systems Part 01. Karine Reis Ferreira

SQL Data Definition Language

SQL: DDL. John Ortiz Cs.utsa.edu

Database Systems CSE 303. Lecture 02

Database Systems CSE 303. Lecture 02

Architecture. Architecture. Introduction to Oracle 10g Express Edition. Help

UNIT-IV (Relational Database Language, PL/SQL)

In This Lecture. SQL Data Definition SQL SQL. Non-Procedural Programming. Notes. Database Systems Lecture 5 Natasha Alechina

doc. RNDr. Tomáš Skopal, Ph.D. RNDr. Michal Kopecký, Ph.D.

Misc. Triggers Views Roles Sequences - Synonyms. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering

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

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

1 Prepared By Heena Patel (Asst. Prof)

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

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Standard Query Language. SQL: Data Definition Transparencies

Transcription:

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Lab # 4 Data Definition Language (DDL) Eng. Haneen El-Masry November, 2014

2 Objective To be familiar with SQL Language especially with Data Definition Language (DDL). Relational Database (RDB) Relational Database means data stored in relations. Relation is essentially a mathematical term for table. Each table is a named collection of rows (tuples). Each row of a given table has the same set of named Columns (attributes), and each column is of a specific data type. Database Keys A key is a logical way to access a record in a table. There are many types of key in RDB: 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.

3 SQL Language SQL is presently expanded as Structured Query Language. Originally, SQL was called SEQUEL. SQL is now the standard language for commercial relational DBMSs. SQL Statements SQL has insensitive statements for data definitions, queries, and updates. SQL commands are grouped into major categories depending on their functionality: Data Definition Language (DDL): These SQL commands are used for creating, modifying, and dropping the structure of database objects. It also define keys, specify links between tables, and impose constraints between tables. The commands are ALTER, ANALYZE, AUDIT, COMMENT, CREATE, DROP, FLASHBACK, GRANT, PURGE, RENAME, REVOKE and TRUNCATE. Data Manipulation Language (DML): These SQL commands are used for storing, retrieving, modifying, and deleting data. These Data Manipulation Language commands are CALL, DELETE, EXPLAIN, INSERT, LOCK TABLE, MERGE, SELECT and UPDATE. Transaction Control Language (TCL): These SQL commands are used for managing changes affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT. In this lab, we will concentrate on DDL. Schema Creating To create a new schema in default XE database, we have to create a new user and the Oracle creates a schema for that user with the same name.

4 To create a new user, you have to follow the next steps: 1- Connect to XE database by SYSTEM user. 2- Expand the connection and R-click on other users >> Create User.

5 3- User tab >> enter user name and password and choose the default and temporary table spaces. Tablespaces are the physical locations where data base objects are stored. These tablespaces are typically included in the XE database by default. The USERS and TEMP tablespaces are generally assigned to users that generate examples and demonstrations.

6 4- System Privileges tab >> Grant the necessary privileges for the user. Granted Privileges: Create session: to be able to connect to XE database by the new user. Create table/ view/ procedure/ synonym/ sequence/ trigger/ type/materialized view: to be able to create tables, views, procedures, synonyms, sequences, user defined data types and materialized views respectively inside the new schema. Unlimited tablespace: to permit a user to use an unlimited amount of any tablespace in the database. Alter session: to set or modify any of the conditions or parameters that affect your connection to the database.

7 5- Apply. 6- Connect to XE database by the new user. 7- Now you can issue SQL statements for the new schema.

8 Table Creating Create Table Create Table tablename ( Col.1 DataType [col. Default] [InLine Constraints], Col.2 DataType [col. Default] [InLine Constraints],... [Out Of Line Constraints] ); DATA TYPES NUMERIC TYPES Name 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. Integer INT Number(p) = Number(p,0) s=0. Number: specifies the maximum range and precision for an Oracle number. Number (32) 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. -2 ^31 (2 ^31)-1

9 Float(p) 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 BINARY_FLOAT is a 32-bit, single-precision floating-point number data type. Binary_Double 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. CHARACTER TYPES Definition Description Notes char A single character. Char (n[byte char]) NCHAR[(n)] VARCHAR2(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. 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. NVARCHAR2(n) A Variable length Unicode character string having maximum length n characters. You must specify size for NVARCHAR2. BINARY DATA TYPES Definition 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. 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.

10 DATE/TIME DATA TYPES Name Description Notes Example Date timestamp [(p)] Timestamp [(p)] with time zone Date Only. Its components are YEAR, MONTH, and DAY. The default format is: DD-MON-YY. SYSDATE: special value that is current system date. Includes the DATE and TIME fields, with a blank space between two 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 To specify a value to Date types, you can: Place the value between single quotation marks in DD-MON-YY/YYYY format. Use Date keyword and YY/YYYY-MM-DD Format. To specify a value for Timestamps DataType, you can: 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 31-MAY-2002 Date 2002-05-31 Date 02-05-31 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 2002-05-02 15:30:56.36 ASIA/JERUSALEM'

11 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. 31-MAY-14 10:30:56 31-MAY-14 10:30:56 PM Timestamp 2013-05-06 10:30:56 P: is an optional fractional seconds precision, it can be specified timestamp, and interval types. P can be from 0 to 9. The default p is 6. 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.

12 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. 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,. );

13 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. 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 Specification [Constraint const_name] const_type [const_specifications] Note: In this specification const_type doesn t specified for foreign key constraint.

14 Out Of Line Specification [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. In Line Specification [Constraint const_name] Not Null Unique Constraint In Line Specification [Constraint const_name] Unique Out of Line Specification [Constraint const_name] Unique (Column[s]) Primary Key Constraint In Line Specification [Constraint const_name] Primary Key Out of Line Specification [Constraint const_name] Primary Key (Column[s])

15 Check Constraint In Line & Out Of Line Specifications [Constraint const_name] ckeck (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. In Line Specification [Constraint const_name] references ReferencedTable (ReferencedCol) [ON Delete set Null CASCADE] [ON UPDATE set NULL CASCADE] Out Of Line Specification [Constraint const_name] foreign key (Column[s]) references ReferencedTable (ReferencedCol[s]) [ON Delete set Null CASCADE] [ON UPDATE set NULL CASCADE] 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.

16 Example: Create table EMPLOYEE ( SSN varchar2(9) Not Null constraint PK Primary Key, FName varchar2(10) constraint FN_NN Not Null, LName varchar2(10), Salary number (6,2) check (Salary > 2000), MgrSSN varchar2(9) constraint fk references EMPLOYEE (SSN), Hired_Date Date, DNo INTEGER, Constraint fk2 foreign key (DNo) references DEPARTMENT (DNUM) ); 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. ALTER TABLE TName Add Column ADD ColName DataType [Default value] [Constraints];

17 Change Column Data Type ALTER TABLE TName MODIFY ColName newdatatype; Note: You can change the data type of any column if all rows of the column contain nulls. Specify Column Default Value ALTER TABLE TName MODIFY ColName DEFAULT DefValue; To discontinue previously specified default values, so that they are no longer automatically inserted into newly added rows, replace the values with NULL. Remove Default Value ALTER TABLE TName MODIFY ColName DEFAULT NULL; Rename Column ALTER TABLE TName Rename Column oldname to newname; Remove Column ALTER TABLE TName Drop Column ColName [CASCADE]; CASCADE: if you want to drop everything that depends on the column.

18 Add Out Of Line Constraint ALTER TABLE TName Add OutOfLineConstraint ; To add a not-null constraint, which cannot be written as out of line constraint, use this syntax: Add Not Null Constraint ALTER TABLE TName Modify ColName Not Null; ALTER TABLE TName Rename Constraint RENAME CONSTRAINT OldName TO NewName; Remove Constraint ALTER TABLE TName DROP CONSTRAINT name [CASCADE]; Remove Not Null Constraint ALTER TABLE TName MODIFY ColName NULL; ReName Table ALTER TABLE TName RENAME TO NewName; Remove Table DROP TABLE TName [CASCADE];

19 Notes: SQL Statements are executed sequentially. To run a statement, Put the cursor on the statement and press Ctrl+Enter, or click on icon. You can run more than statement sequentially, put the cursor on the first statement and press F5. Or click on icon. Example: You have the following COMPANY Schema, create it on Oracle.

20 Solution: 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.

21

22

23

24 To view the tables in the schema, R-Click on Tables >> Refresh.

25 Exercises Create University and Mail Order Schemas that are in Lab 2. Best Wishes