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

Similar documents
3ISY402 DATABASE SYSTEMS

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

Data Definition Language (DDL)

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.

CHAPTER4 CONSTRAINTS

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

Lab # 4. Data Definition Language (DDL)

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

The Structured Query Language Get Started

Creating and Managing Tables Schedule: Timing Topic

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

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

Lecture 07. Spring 2018 Borough of Manhattan Community College

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

4 Schema Definition with SQL / DDL (II)

Unit 1 - Chapter 4,5

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

STRUCTURED QUERY LANGUAGE (SQL)

Database Programming - Section 10. Instructor Guide

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

Relational Database Language

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

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

INTRODUCTION TO DATABASE

Full file at

SQL: DDL. John Ortiz Cs.utsa.edu

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

Tutorial 1 Database: Introductory Topics

COMP102: Introduction to Databases, 5 & 6

Chapter-14 SQL COMMANDS

ITCertMaster. Safe, simple and fast. 100% Pass guarantee! IT Certification Guaranteed, The Easy Way!

CSC Web Programming. Introduction to SQL

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

DATA CONSTRAINT. Prepared By: Dr. Vipul Vekariya

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

Lecture 6 Structured Query Language (SQL)

Creating SQL Tables and using Data Types

3.2.4 Enforcing constraints

MTAT Introduction to Databases

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

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

SQL Data Definition: Table Creation

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

1) Introduction to SQL

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

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

EDB Postgres Hadoop Data Adapter Guide

Data Base Lab. The Microsoft SQL Server Management Studio Part-3- By :Eng.Alaa I.Haniy.

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

Structured Query Language. ALTERing and SELECTing

Oracle Database 10g: SQL Fundamentals I. Oracle Internal & Oracle Academy Use Only. Student Guide Volume 2. D17108GC30 Edition 3.0 January 2009 D57871

다양한예제로쉽게배우는 오라클 SQL 과 PL/SQL 서진수저

CSC 453 Database Technologies. Tanu Malik DePaul University

Mahathma Gandhi University

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

ORACLE VIEWS ORACLE VIEWS. Techgoeasy.com

Chapter 1 SQL and Data

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

IT360: Applied Database Systems. SQL: Structured Query Language DDL and DML (w/o SELECT) (Chapter 7 in Kroenke) SQL: Data Definition Language

DB Creation with SQL DDL

Unit 7: Database Development (Basic)

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

Physical Design of Relational Databases

MySQL Introduction. By Prof. B.A.Khivsara

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

Basant Group of Institution

Step 0 How to begin and what you need to do before you start?

Standard Query Language. SQL: Data Definition Transparencies

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

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

Difficult I.Q on Databases, asked to SCTPL level 2 students 2015

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions


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

Transforming ER to Relational Schema

The Relational Model

Lecture 5 Data Definition Language (DDL)

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

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

G64DBS Database Systems. Lecture 6 More SQL Data. Creating Relations. Column Constraints. Last Lecture s Question

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

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

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

15CSL58: DATABASE MANAGEMENT LABORATORY

Chapter 14 Data Dictionary and Scripting

Intermediate SQL ( )

CS2300: File Structures and Introduction to Database Systems

Oracle Tables TECHGOEASY.COM

To understand the concept of candidate and primary keys and their application in table creation.

Downloaded from

Unit 27 Web Server Scripting Extended Diploma in ICT

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

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

Exact Numeric Data Types

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

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

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

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

CIS Slightly-different version of Week 10 Lab, also intro to SQL UPDATE and DELETE, and more

Transcription:

Lab 7 Aim: Creating Simple tables in SQL Basic Syntax for create table command is given below: CREATE TABLE <table_name> ( <column_name> <data_type> [DEFAULT <expression>] [<column_constraint>], {<column_name> <data_type> [DEFAULT <expression>] [column_constraint>],} [<table_constraints>] ); The parts enclosed in square brackets ([ ]) are optional. Curly braces ({ } )indicate that the enclosed expression can be repeated zero or many times. Angle brackets (< >) indicate that these are meta symbols that would be replaced by actual symbols of the language. Underlined paranthesis are part of the command. (Of course you do not underline them when you write the actual command in SQL*Plus J ) <column_name> should be replaced by actual column (attribute) names of the table. <data_type> can be one of the following: VARCHAR2(size): Variable length character string up to maximum length size CHAR(size): Fixed length character string of length size NUMBER: Floating point number with a precision of 38 significant digits NUMBER(p,s): Number with a maximum precision p and maximum scale s. Scale is the number of digits to the right of the decimal point. DATE: Date and time values between January 1, 4712 B.C. and December 31, 4712 A.C. LONG: Variable Length charcater values up to 2GB. Only one LONG column is allowed per table RAW or LONG RAW: Equivalent to VARCHAR2 and LONG, respectively, but used to store byte oriented or binary data Table and column constraints are formed using one of the following constraint keywords. <constraint_type> NOT NULL: Specifies that a given column cannot contain any NULL values UNIQUE: Specifies that values in a column or a combination of columns must be all unique. A unique index (that has the same name as the unique constraint) is automatically created for UNIQUE column(s). PRIMARY KEY: Specifies that a column or a combination of columns must be all UNIQUE and NOT NULL. There can be only one PRIMARY KEY in each table. A UNIQUE index (whose name is the same as the constraint name) is created for the PRIMARY KEY. FOREIGN KEY REFERENCES: Establishes and enforces foreign key relationship between the specified column(s) and the referenced column(s) CHECK: Specifies that the given condition should always hold. A <column constraint> is a constraint that applies to a single column. <column_constraint> for PRIMARY KEY, UNIQUE and NOT NULL constraints is of the following form: [CONSTRAINT <constraint_name>] <constraint_type>

You do not have to give a name to each constraint. But it is a good practice to name all constraints, because constraint names are used the error messages and giving rational names to constraints makes it easier to understand the messages. <constraint_name> can be any name you choose. ORACLE suggests using the following combination tablename_columnname_abbreviation where abbreviation is pk for PRIMARY KEY, uk for UNIQUE KEY, fk for FOREIGN KEY, ck for CHECK CONSTRAINT and nn for NOT NULL CONSTRAINT. The form of a Foreign Key constraint that applies to a single column is [CONSTRAINT <constraint_name> ] REFERENCES < referenced_table> ( <referenced_attribute>) <referenced_table> is the parent table and the <referenced_attribute> is the primary or unique key of the parent table. CHECK constraint has the following form [CONSTRAINT <constraint_name> ] CHECK (<condition>) where, <condition> is a condition that should be satisfied for the column. Table constraints are the constraints that apply to more than one column. Table constraints are more general than the column constraints, therefore column constraints can be specified as table constraints. The form of PRIMARY KEY, UNIQUE and NOT NULL table constraints is given below: [CONSTRAINT <constraint_name>] <constraint> (<column_list>) The form for FOREIGN KEY table constraint is : [CONSTRAINT <constraint_name> ] FOREIGN KEY (<foreign_key_columns>) REFERENCES <referenced_table> ( <referenced_attribute>) The form for CHECK constraint at table level is the same as the column level CHECK constraint. Example 1: Create a table for keeping information about your friends. SQL> CREATE TABLE friend 2 (friendno NUMBER(2) CONSTRAINT friend_friendno_pk PRIMARY KEY, 3 name VARCHAR2(25) CONSTRAINT friend_name_nn NOT NULL, 4 phone VARCHAR2(15), 5 city VARCHAR2(10) DEFAULT 'GIRNE'); Table created. Column declarations are separated by a comma. If constraint names (shown in italic in the example) are not specified, ORACLE will assign an alphanumeric identifier (like SYS_C0026055) for each one of such constraints and use this identifier when it generates error messages: An example error message is given below:

ORA-00001: unique constraint (USER50.SYS_C0026055) violated In line 5 of the above command a default value is specified for the city. This means that if the city value is omitted in an insert statement by default it will be 'GIRNE'. If you want to assign NOT NULL to city, you have to do this explicitly! Example 2 : Consider the following command that creates the s_dept table SQL>CREATE TABLE s_dept 2 ( id NUMBER(7) 6 CONSTRAINT s_dept_id_pk PRIMARY KEY (id), 3 name VARCHAR2(25) CONSTRAINT s_dept_name_nn NOT NULL, 4 region_id NUMBER(7) 5 CONSTRAINT s_dept_region_id_fk REFERENCES s_region(id), 6 CONSTRAINT s_dept_name_region_id_uk UNIQUE (name, region_id)); In the above command, on line 5, you see a foreign key constraint declaration. This constraint forces the region_id column to take only the values that are stored in the id column of the s_region. The table that contains the foreign key is called the child table and the table that contains the referenced column is called the parent table. In this case s_dept is the child and s_region is the parent. You have to make sure that the referenced column (or columns) in the parent table have UNIQUE constraint. (Remember: PRIMARY KEY is UNIQUE and NOT NULL!!!) The table constraint on line 6, ensures that the combination of the values for name and region_id of a department will be unique in the whole table. ALTERING AN EXISTING TABLE Another command that you might find useful when creating a table is the ALTER TABLE command. Modifications allowed without any restrictions include: --Adding a new column to the table. --Deleting a foreign key constraint from a table. --Deleting a primary key constraint from a table, which also removes any references to it from other tables in the database with CASCADE clause. --Increasing the size of a column. For example, VARCHAR2(15) can be changes to VARCHAR2(20). --Renaming columns. --Renaming constraints. Modifications allowed with restrictions include: --Adding a foreign key constraint is allowed only if the current values are null or exist in the references table's primary key. --Adding a primary key constraint is allowed if the current values are not null and are unique. --Column size may be decreased if existing data can be stored with the new column width. --Adding a unique constraint is possible if the current data values are unique. --Adding a check constraint is possible if the current data values comply with the new constraint. --Adding a default value is possible if there is no data in the column. Modifications not allowed include:

--Changing a column's name. --Changing a constraint's name. The format for the ALTER TABLE command to add a new column is given below ADD columnname datatpe; To modify a column, you use the ALTER TABLE command with the modify clause. Column modification includes changes to columns data type, size, default value and NOT NULL column constraint. The format is given below: MODIFY ( <column_name> <datatype> [DEFAULT <expression> ] [NOT NULL] {, <column_name> <datatype> [DEFAULT <expression> ] [NOT NULL]} ); You can increase the width or precision of a column. You can decrease width of columns or change data type of a column only if the column contains no data. A change in the default value affects only the subsequent changes. You can add a NOT NULL constraint only if the column contains no NULL values. Example 3: Add a new column to the friend table SQL> ALTER TABLE friend 2 ADD ( bday date); Example 4: Increase the size of the name field of the friend table to 5o characters. SQL> ALTER TABLE friend 2 MODIFY ( name VARCHAR2(50) ); The format for the ALTER TABLE command to add a new constraint is given below ADD [CONSTRAINT <constraint_name> ] <constraint_type> (<column_list>); where column_list is replaced by the list f the columns that the constraints applies to. Any constraint except for NOT NULL CONSTRAINT can be added using this command. NOT NULL constraint is added using the MODIFY clause of the ALTER TABLE command. Example 5: Add a UNIQUE constraint on the combination of the city and name attributes of the friend table of example 1. SQL > ALTER TABLE friend 2 ADD CONSTRAINT friend_name_city_uk UNIQUE(city,name); To drop a column of a given table the ALTER TABLE command is used as given below: DROP COLUMN column_name; To drop a constraint of a given table the ALTER TABLE command is used as given below:

DROP CONSTRAINT <constraint_name> [CASCADE] ; constraint_name is the name given in the CREATE TABLE command. If you do not remember the <constraint_name>, you can check the data dictionary views called USER_CONSTRAINTS and USER_CONS_COLUMNS. CASCADE keyword causes all dependent constraints to be dropped as well. If there are any other constraints that depend on the constraint that you are trying to drop, DBMS engine does not let you drop the constraint. For example you cannot drop a primary key constraint if there are any foreign key constraints referring to it, unless you use the keyword CASCADE. The primary key constraint and unique constraints can also be dropped using the following drop constraint clause: DROP PRIMARY KEY UNIQUE(<column_list>) CONSTRAINT constraintname [CASCADE] ; Example 6: a) SQL > ALTER TABLE friend 2 DROP PRIMARY KEY CASCADE; b) Drop the constraint you added in example 3. SQL > ALTER TABLE friend 2 DROP CONSTRAINT friend_name_city_uk; You can also enable or disable a constraint without dropping or recreating them. The format is: DISABLE ENABLE CONSTRAINT <constraint_name> [CASCADE]; A constraint is NOT enabled if there are any values in the table that violate it. If you need to add a new column to a table you can use the ALTER TABLE command with the ADD clause as follows ADD (<column_name> <data_type> [DEAFULT <expression>][<column_constraint>] {,<column_name> <data_type> [DEAFULT <expression>] [ <column_constraint>] }); You can add as many columns as you like in one ALTER TABLE statement. In SQL, if you want to delete a table, you DROP it. This is true for all schema objects. Anything created by the CREATE command is deleted by the DROP command. The format of the DROP table command is given below: DROP TABLE <table_name> [CASCADE CONSTRAINTS];

This will cause the table to be dropped. The CASCADE CONSTRAINTS clause is important if the table, you are trying to drop, is referenced by other tables. If you do NOT supply this clause in the DROP TABLE statement and if the table is referenced by other tables, DBMS engine will NOT drop the table. Example 7 : Drop the friend table. SQL > DROP TABLE friend; You can rename a table provided you are the owner of the table. The general syntax is: RENAME oldtablename TO newtablename; Example 8: Change the name of the friend table to myfriends. RENAME friend to myfriends; Truncating a table is removing all records/rows from the table. The structure of the table, however, stays intact. You must be the owner of the table with the DELETE TABLE privilege to truncate a table. The SQL language has a DELETE statement that can be used to remove one or more (or all) rows from a table, and it is reversible as long as it is not committed. The TRUNCATE statement, on the other hand, is not reversible. The syntax is: TRUNCATE TABLE tablename; Exercise Movies(movieid, title, director_name, rating, producing_studio, format) Rented(customerid, movieid) Customer(customerid, name, address, age, balance) These tables have obvious meanings. Movies is the set of movies owned by the video store. Each tuple contains the title of the movie, the name of the director, the rating (e.g., "PG" or "PG-13"), the studio that produced the movie (e.g., "Miramax"), and the format of the movie (e.g., "Video Cassette" or "DVD"). The attribute "movieid" is meant to be the key (presumably assigned by the store). Notice that a given movie that is available in many formats will have different movieids, one for each format. An alternate key for this relation are the two attributes (title, format). In other words, the title and format functionally determine all the other attributes in Movies, such as the movieid, director's name, rating, and studio. Do not worry about the fact that "year" is not a part of the key or the relation. Customer is a table that identifies the customers of the store, their name, dob, address (e.g., "123 Main Street, Blacksburg"), and balance (e.g., "$30" or "-$15"). Rented is a history of who has rented what in the past