1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem.

Slides:



Advertisements
Similar presentations
MySQL. To start go to Login details: login: labuser password:macimd15 – There.
Advertisements

Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
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.
1 Designing Tables for an Oracle Database System Database Course, Fall 2003.
1 Reminder We have covered: –Creating tables –Converting ER diagrams to table definitions Today we’ll talk about: –Altering tables –Inserting and deleting.
Introduction to Structured Query Language (SQL)
1 Designing Tables for an Oracle Database System Database Course, Fall 2005.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation Adding columns Changing columns’ definition Dropping columns.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation –Adding columns –Changing columns’ definition –Dropping columns.
Introduction to Structured Query Language (SQL)
1 Designing Tables for an Oracle Database System Database Course, Fall 2004.
ORACLE Using ORACLE 8 SQL using ORACLE 8 PL/SQL using ORACLE 8.
Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial Password: UWPstudent Password is case sensitive.
Oracle Data Definition Language (DDL)
ASP.NET Programming with C# and SQL Server First Edition
SQL data definition using Oracle1 SQL Data Definition using Oracle.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
10 Copyright © 2009, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
1 Copyright © 2006, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
SQL: DDL John Ortiz Cs.utsa.edu.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
Intro to SQL| MIS 2502  Spacing not relevant › BUT… no spaces in an attribute name or table name  Oracle commands keywords, table names, and attribute.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Creating Tables and Inserting Records -- Not easy to edit! -- check constraints! Create table test1 ( C1 char(5) primary key, C2 Varchar2(15) not null.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
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.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Oracle 11g: SQL Chapter 4 Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
9 Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Schema Objects.
INCLUDING CONSTRAINTS lecture5. Outlines  What are Constraints ?  Constraint Guidelines  Defining Constraint  NOT NULL constraint  Unique constraint.
SQL CREATING AND MANAGING TABLES lecture4 1. Database Objects ObjectDescription TableBasic unit of storage; composed of rows and columns ViewLogically.
The Oracle Database System. Connecting to the Database At the command line prompt, write: sqlplus In the beginning your password.
IS 380 Introduction to SQL This lectures covers material from: database textbook chapter 3 Oracle chapter: 3,14,17.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
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.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Including Constraints. What Are Constraints? Constraints enforce rules at the table level. You can use constraints to do the following: – Enforce rules.
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
Basic SQL*Plus edit and execute commands SQL*Plus buffer and built-in editor holds the last SQL statement Statements are created in free-flow style and.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
SQL. Internet technologies – Ohad © Database  A database is a collection of data  A database management system (DBMS) is software designed to assist.
1 Designing Tables for a Database System. 2 Where we were, and where we’re going The Entity-Relationship model: Used to model the world The Relational.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Creating and Managing Tables. Database Objects ObjectDescription TableBasic unit of storage; composed of rows and columns ViewLogically represents subsets.
2 Copyright © 2009, Oracle. All rights reserved. Managing Schema Objects.
SQL and SQL*Plus Interaction
SQL Creating and Managing Tables
Designing Tables for a Database System
DB Review.
ORACLE SQL Developer & SQLPLUS Statements
SQL Creating and Managing Tables
SQL Creating and Managing Tables
Designing Tables for a postgreSQL Database System
SQL data definition using Oracle
Oracle Data Definition Language (DDL)
SQL-1 Week 8-9.
Using SQL*Plus.
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
Turn on spool and save to file a.txt
Including Constraints
Presentation transcript:

1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem

2 Technical Basics

3 Connecting to the Database At the command line prompt, write: sqlplus In the beginning your password is the same as your login. You can change your password with the command: password To disconnect use the command: quit

4 Connecting to the Database

5 Running SQL Files Instead of typing SQL commands into the SQLPLUS terminal, you can load commands from a file Use the from SQLPLUS to load the file file.sql Invoke the SQLPLUS command with the extra to load the file at connection:

6 Spooling the Output Output can be placed in a file: spool myFile.out Spooling can be turned off with: spool off

7 Tables Creation

8 Creating a Table The basic format of the CREATE TABLE command is: CREATE TABLE TableName( Column1 DataType1 ColConstraint, … ColumnN DataTypeN ColConstraint, TableConstraint1, … TableConstraintM );

9 An Example If you issue the command describe Cars you get: Name Null? Type LICENSE NUMBER COLOR VARCHAR2(15) CREATE TABLE Cars( LicenseNUMBER, Color VARCHAR2(15)); Note that the definition is case insensitive

10 Data Types CHAR(n)String of length n (n <= 2000) VARCHAR2(n)Variable length string of size <= n (n <= 4000) DATEValid dates CLOBCharacter large object (<= 4Gb) NUMBERUp to 40 digits NUMBER(n)Number of size n NUMBER(n,m)Number of size n with m digits after decimal place

11 Constraints in Create Table Adding constraints to a table enables the database system to enforce data integrity. However, adding constraints also makes inserting data slower. Different types of constraints: * Not Null* Default Values * Unique * Primary Key * Foreign Key* Check Condition

12 Not Null Constraint CREATE TABLE Employee( SSNNUMBER NOT NULL, Fname VARCHAR2(20), LnameVARCHAR2(20), GenderCHAR(1), SalaryNUMBER(5) NOT NULL, DeptNUMBER );

13 Default Values CREATE TABLE Employee( SSNNUMBER NOT NULL, Fname VARCHAR2(20), LnameVARCHAR2(20), GenderCHAR(1) DEFAULT(‘F’), SalaryNUMBER(5) NOT NULL, DeptNUMBER );

14 CREATE TABLE Employee( SSNNUMBER UNIQUE NOT NULL, Fname VARCHAR2(20), LnameVARCHAR2(20), GenderCHAR(1) DEFAULT(‘F’), SalaryNUMBER(5) NOT NULL, DeptNUMBER, constraint Emp_UQ UNIQUE(Fname, Lname) ); Unique Constraint The name of the constraint

15 Primary Key Constraint CREATE TABLE Employee( SSNNUMBER PRIMARY KEY, Fname VARCHAR2(20), LnameVARCHAR2(20), GenderCHAR(1) DEFAULT(‘F’), SalaryNUMBER(5) NOT NULL, DeptNUMBER, constraint Emp_UQ UNIQUE(Fname, Lname) ); Primary Key implies NOT NULL and UNIQUE. There can only be one primary key.

16 Another Table CREATE TABLE Department( DeptNumNUMBER PRIMARY KEY, Name VARCHAR2(20), ManagerIdNUMBER ); Shouldn’t all department numbers in Employee appear in Department?

17 Foreign Key Constraint (Referential Integrity) CREATE TABLE Employee( SSNNUMBER PRIMARY KEY, Fname VARCHAR2(20), LnameVARCHAR2(20), GenderCHAR(1) DEFAULT(‘F’), SalaryNUMBER(5) NOT NULL, DeptNUMBER, constraint Emp_UQ UNIQUE(Fname, Lname), FOREIGN KEY (Dept) REFERENCES Department(DeptNum) ); Must be unique

18 Alternative Notation CREATE TABLE Employee( SSNNUMBER PRIMARY KEY, Fname VARCHAR2(20), LnameVARCHAR2(20), GenderCHAR(1) DEFAULT(‘F’), SalaryNUMBER(5) NOT NULL, DeptNUMBER REFERENCES Department(DeptNum), constraint Emp_UQ UNIQUE(Fname, Lname) );

19 Understanding Foreign Keys The constraint on the last table should be read as: “The field Dept in Employee is a foreign key that references the field DeptNum in Department ” Meaning: Every non-null value in the field Dept in Employee must appear in the field DeptNum in Department. What happens to Employees in department 312 when Department 312 is removed from the Department table?

20 Deleting a Referenced Value If nothing additional is specified, then Oracle will not allow Department 312 to be deleted if there are Employees working in this department. If the constraint is written as FOREIGN KEY (Dept) REFERENCES Department(DeptNum) ON DELETE CASCADE then Employees working in 312 will be deleted automatically from the Employee table

21 Cyclic Foreign Keys CREATE TABLE Department( DeptNumNUMBER PRIMARY KEY, Name VARCHAR2(20), ManagerIdNUMBER REFERENCES Employee(SSN) ); Do you see a problem in inserting data now? We should revise the Department table:

22 Solution to Cyclic Constraints Add one of the constraints later on (after insertion): ALTER TABLE Department ADD(FOREIGN KEY (ManagerId) REFERENCES Employee(SSN));

23 Check Conditions A check condition is a Boolean expression: “And”s and “Or”s of conditions of the type X > 5… On a column: it can refer only to the column On a table: it can refer only to multiple columns in the table

24 Check Constraints CREATE TABLE Employee( SSNNUMBER PRIMARY KEY, Fname VARCHAR2(20), LnameVARCHAR2(20), GenderCHAR(1) DEFAULT(‘F’) CHECK(Gender = ‘F’ or Gender = ‘M’), SalaryNUMBER(5) NOT NULL, CHECK (Gender = ‘M’ or Salary > 10000) );

25 Table Alteration

26 Altering Tables Table definition can be altered after its creation Adding columns Changing columns’ definition Dropping columns Adding constraints And more… Use the reserved word ALTER

27 Altering Tables (continues) Adding a column: ALTER TABLE Employee ADD ( Mname VARCHAR2(20), Birthday DATE ); Changing columns’ definition: ALTER TABLE Emplyee Modify ( Mname VARCHAR2(10) ); Cannot be NOT NULL unless the table is empty

28 Altering Tables (continues) Dropping columns: ALTER TABLE Employee DROP COLUMN Mname; Dropping multiple columns: ALTER TABLE Employee DROP (Mname, Birthday); Adding constraints: ALTER TABLE Department ADD( FOREIGN KEY (ManagerId) REFERENCES Employee(SSN));

29 Deleting a Table To delete the table Employee : DROP TABLE Employee;

30 User’s Table List ORACLE may print tables that hold some general information about the tables in your database Such Tables are: Tab, Cat, User_Tables (too detailed...) To see the list of all your tables you can print: SELECT * FROM Cat; SELECT tname FROM Tab; SELECT table_name from User_Tables;

31 Table Data Maintenance

32 The Employee Table > Describe Employee Name Null? Type SSN NUMBER FNAME VARCHAR2(20) LNAME VARCHAR2(20) GENDER CHAR(1) SALARY NOT NULL NUMBER(5)

33 Inserting a Row To insert a row into the Employee table: INSERT INTO Employee(SSN, Fname, Lname, Salary) VALUES(121, ‘Sara’, ‘Cohen’,10000); The remaining columns get default values (or NULL) Order is not important

34 Some More Details… The fields needn’t be specified if values are specified for all columns and in the order defined by the table Example: INSERT INTO Employee VALUES(121, ‘Sara’, ‘Cohen’, `F’, 10000);

35 Deleting Rows General format: DELETE FROM Table WHERE Cond; Deletes all rows satisfying Cond from Table For example, to remove the employee with SSN 121 from the Employee table: DELETE FROM Employee WHERE SSN = 121;

36 Deleting Rows (continues) To remove all male employees having a salary greater than shekels: DELETE FROM Employee WHERE Gender = ‘M’ AND Salary > 15000; We will later discuss WHERE clauses… Case sensitive

37 Updating Rows (continues) We can update fields of rows in a table General format: UPDATE Table SET Field1=value1,,,FieldN=valueN WHERE Cond Now we can reduce salaries instead of firing employees: UPDATE Employee SET Salary = WHERE Gender = ‘M’ AND Salary > 15000;

38 The ORACLE Bulk Loader A tool that provides easy insertion of large amounts of rows into tables. The idea: the field values of the rows are kept in a file, the format of which is defined by us. For example, it can automatically load 3 employees from the file myEmployees.dat that contains the following lines: Sara|Cohen|121 Benny|Kimelfeld|134 Yaron|Kanza|156

39 The Control File The control file is the direct input of the loader A simple control file: LOAD DATA INFILE [APPEND] INTO TABLE FIELDS TERMINATED BY ' ‘ ( )

40 The Control File (continues) : The name of the data file : The name of the table into which the data will be loaded (appended if APPEND is specified, or else the table must be empty) : A string that separates two field values of a row The attributes are separated by commas and enclosed in parentheses

41 The Control File (continues) As an example, the following control file loads the employees from myEmployees.dat: LOAD DATA INFILE myEmployees.dat INTO TABLE Employees FIELDS TERMINATED BY '|' (Fname, Lname, SSN) The attributes that are unspecified will be set to NULL

42 The Data File The Bulk Loader considers every single line to represent one row in the table Even an empty line! (which will usually result in an error) Spaces are not ignored in the data file! thus the rows ‘sara| cohen|121’ and ‘sara|cohen|121’ define different functionalities The NULL value is implied by the NULL keyword or the empty string

43 The Data File (continues) The control and the data files can be combined into one.ctl file using the following format: LOAD DATA INFILE * INTO TABLE Employees FIELDS TERMINATED BY '|' (Fname, Lname, SSN) BEGINDATA Sara|Cohen|121 Benny|Kimelfeld|134 Yaron|Kanza|156

44 The Bulk Invocation To invoke the bulk loader, issue the following command directly from the Unix shell: sqlldr control= log= bad= All fields are optional File names that have no extension are automatically extended (by.dat,.log or.bad) Erroneous lines in the data file are ignored and written into badFile, and any other relevant information is written into logFile.

45 Bulk Loader Important Remarks Before using the Bulk Loader, make sure your personal ORACLE environment is properly set up The tables you fill using the Bulk Loader should be created prior to the loader invocation Before invoking the Bulk Loader you have to make sure that NO SQLPLUS SESSIONS ARE OPENNED!

46 Table Printing and Formatting

47 Format Example Consider the following table print:

48 Format Example (continues) Absolutely not readable! Solution: we write some commands in a format file and we get:

49 Printing a Table To print a table use the sql command: SELECT * FROM table_name;

50 Add a Title We can add a title to a table printing page using the command: TTITLE ‘title’

51 Change a Column’s Heading We can change a column’s heading using the command : COLUMN ‘col_name’ HEADING ‘heading’

52 Define a Column Size We can define the size of a column: COLUMN ‘col_name’ format ‘format’ Format Examples: a18 : an ASCII text of size : a number with 4 digits, a decimal point, minus sign (for negative numbers) and 0 before the dot for numbers smaller than 1 We can ask ORACLE to cut words to fit the defined space using the command: COLUMN ‘col_name’ truncated

53 Define a Column Size

54 The Whole Picture