You are on page 1of 11

Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2

Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

INSERT (Inserting an Individual Row)


INSERT INTO TableName [ (ColumnList) ]
VALUES (ValueList)

1. Add a row to the ZIPCODE Table with the following values: zip: 11111, city: Westerly, state:
MA, created_by: current user, created_date: 18-Jan-2010, modified_by: current user,
modified_date: system date.

INSERT INTO zipcode (zip, city, state, created_by, created_date, modified_by, modified_date)
VALUES ('11111', 'Westerly', 'MA', USER, to_date('18-Jan-2010', 'DD-MON-YYYY'), USER,
SYSDATE);
OR
INSERT INTO zipcode
VALUES ('11111', 'Westerly', 'MA', USER, to_date('18-Jan-2010', 'DD-MON-YYYY'), USER,
SYSDATE);
Key Points
 ColumnList is optional (though it is good practice to include it)
 ValueList must be in same order as columns in zipcode and must have matching datatypes.
 Text literals (eg ‘Westerly’) must be in single quotes.
 Insertion of date requires To_date function. (Mask can be removed if date in same format as
underlying table)
 Sysdate used to insert current date.
 User used to insert name of user currently logged in.

Not all columns of ZIPCODE require values (check ZIPCODE to verify which are ‘nullable’ values)

CITY and STATE can be left as null.


The foll inserts values into the 5 (of the 7) required fields:
INSERT INTO zipcode (zip, created_by, created_date, modified_by, modified_date)
VALUES ('11111', USER, to_date('18-Jan-2010', 'DD-MON-YYYY'), USER, SYSDATE)
Or you can insert NULL values into the columns:
INSERT INTO zipcode
VALUES ('11111', NULL, NULL, USER, to_date('18-Jan-2010', 'DD-MON-YYYY'), USER,
SYSDATE)

1
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

INSERT (Inserting Multiple Rows)

 Another method for inserting data is to select data from another table via a subquery (which
may return multiple rows).
Example: Create table INTRO_Course by running script in file ‘Create_Intro_Course_table’

CREATE TABLE intro_course


(course_no NUMBER(8),
description_tx VARCHAR2(50),
cost NUMBER(9,2),
prereq_no NUMBER(8),
created_by VARCHAR2(30),
created_date DATE,
modified_by VARCHAR2(30),
modified_date DATE);

 The following INSERT statement inserts data into INTRO_COURSE based on a query against
the rows of the COURSE table
INSERT INTO intro_course (course_no, description_tx, cost, prereq_no, created_by,
created_date, modified_by, modified_date)
SELECT course_no, description, cost, prerequisite, created_by, created_date, 'Nalini',
To_Date('01-JAN-2008', 'DD-MON-YYYY')
FROM course
WHERE prerequisite is NULL;
--4 rows inserted

Transaction Control

 It is important to control when a change becomes permanent.

 DML statements are controlled within the context of a transaction.

 A transaction is a DML statement or group of statements that logically belong together

 Transaction control is achieved through use of COMMIT, ROLLBACK and SAVEPOINT.

2
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

Commit

 Makes changes permanent.


 Allows other sessions to see the data (A session is an individual connection to the server. An
individual user may be connected to multiple concurrent sessions. If SQL Developer is invoked
multiple times, an individual session is established each time.)
 Locks for the changes rows are released and other users can perform changes on the rows.
 Instead of typing the COMMIT command, you can click on the COMMIT icon in SQL Developer:

Rollback

 Undoes any DML statements back to the last COMMIT.


 All pending changes are discarded and locks on affected rows are released.
 Instead of typing the ROLLBACK command, you can click on the ROLLBACK icon in SQL
Developer:

Savepoint

 Allows you to save the results of a DML transaction temporarily.


 Rollback can then refer to a particular SAVEPOINT and roll back the transaction up to that
point. Any statements issued after the SAVEPOINT are rolled back.

UPDATE

UPDATE TableName
SET columnName1 = dataValue1 [, columnName2 = dataValue2…]
[WHERE Condition]

 Always refers to a single table

2. Update the Final_Grade column in the Enrollment table to 90 for all students who enrolled in
January 2007.
UPDATE enrollment
SET final_grade = 90
WHERE enroll_date >= to_date('01/01/2007', 'DD/MM/YYYY') AND enroll_date <
to_date('01/02/2007', 'DD/MM/YYYY');
--11 rows updated

3
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

 Update the Final_Grade to null for all rows in the Enrollment table.

Update enrollment
Set final_grade = NULL
--226 rows updated

DELETE
DELETE FROM TableName
[ WHERE Condition ]

3. Delete all rows from the Grade table. Confirm that all rows are deleted.
DELETE FROM grade
--2004 rows deleted

4. Issue a ROLLBACK command to undo the deletion. Verify that all rows are back in the Grade
table.

5. Delete rows from the Grade table for the student with ID 102. Confirm that all rows are deleted.
DELETE FROM grade
WHERE Student_ID = 102;

The SQL Developer Data Tab

 SQL Developer’s GUI allows you to insert, update and delete data directly with the Data tab.
 INSERT: The INSERT ROW icon allows you to add a new blank row and type the data in
directly:

4
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

 UPDATE: Updating of records can be performed directly on the data grid.

 DELETE: Deletion is performed by clicking the DELETE icon:

The record is marked for deletion by the –ve number:

 Changes are made permanent when you click the COMMIT icon, or rolled back when you click
the ROLLBACK icon.

Note: If you go back to previous labs and re-execute those queries, you might find that the results
are different than they were before. Therefore, if you want to reload the tables and data, you can
run the rebuildStudent.sql script.

Creating Tables
You can create a table in one of 2 ways:
 Specify columns and datatypes explicitly (create a table ‘from scratch’) OR
 Create a table based on an existing table
Create Table Syntax:

CREATE TABLE TableName


(columnName datatype [column_constraint_clause]
[table_constraint_clause] )

5
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

Examine the following script to create the Intro_Course table we considered previously:
CREATE TABLE intro_course CREATE TABLE TableName
(course_no NUMBER(8), (columnName datatype)
description_tx VARCHAR2(50),
cost NUMBER(9,2), Note: Everything in square brackets is
prereq_no NUMBER(8), optional
created_by VARCHAR2(30),
created_date DATE,
modified_by VARCHAR2(30),
modified_date DATE);

Table Naming Convention


 Must be unique within a database schema (i.e. no other database object can have the same
name)
 Must be <= 30 characters.
 Cannot include spaces or hyphens (but can have underscores)
 Must begin with a letter
 Good practice that it describes the nature of the data contained.
 For consistency, choose either singular or plural names for all your tables.

Commonly used data types


 Character data: Varchar(2) (variable length data) & char (fixed length data)
 Numeric data: Number
 Date & Time data: Date

6. Write and execute a CREATE TABLE statement to create an empty table called
NEW_STUDENT that contains the following columns: first name, last name, the description of
the first course the student takes, and the date the student registered in the programme.
(Determine the data type and length necessary for each column based on the tables in the
STUDENT schema.)
Create Table New_Student
(first_name VARCHAR2(25),
last_name VARCHAR2(25),
description VARCHAR2(50),
registration_date DATE)
6
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

Integrity Constraints
 The following CREATE Table statement creates a table called TAB 1 with several types of
COLUMN constraints:
Create Table tab1
(col1 NUMBER(10) PRIMARY KEY,
col2 NUMBER(4) NOT NULL,
col3 VARCHAR2(5) REFERENCES zipcode(zip) ON DELETE CASCADE,
col4 DATE DEFAULT SYSDATE,
col5 VARCHAR2(20) UNIQUE,
col6 NUMBER CHECK(col6 < 100) )
 PRIMARY KEY Constraint
 i.e Entity Integrity constraint
 Ensures that all values are NOT NULL and UNIQUE

 NOT NULL Constraint


 Need to define this for columns that must always contain a value

 FOREIGN KEY Constraint


 i.e. Referential Integrity constraint (ensures that values in FK correspond to values in PK)
 ON DELETE CASCADE indicates that when a parent row is deleted, the corresponding
row(s) in child table will be deleted as well.
 ON DELETE SET NULL indicates that when a parent row is deleted, the corresponding
zipcode in child table is set to null (assuming col3 allows null values)
 DEFAULT column option (not a constraint)
 If no value is supplied, SYSDATE is automatically inserted by default
 Default value can be provided for any column, except primary key
 UNIQUE Constraint
 Eg phone or social security numbers; email addresses, etc
 Allows null values (unlike primary key)
 CHECK Constraints
 Enforce logical expressions which must evaluate to either True or False
 In eg, col 6 is constrained to a value < 100
 Eg: state VARCHAR2(20) CHECK( state IN (‘NY’, ‘NJ’, ‘CA’) )
7
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

Table-Level vs Column-Level Constraints


 Constraints can be defined on 2 levels - column or table
 Column-level constraint refers to a single column, and is defined together with the column
 Table-level constraints apply to entire table. Defined after column-level constraints.
 ALL constraints, except NOT NULL, can be defined at table-level.
 A constraint name is optional and must be preceded by keyword CONSTRAINT.

Create Table tab1


(col1 NUMBER(10),
col2 NUMBER(4) CONSTRAINT tab1_col2_nn NOT NULL,
col3 VARCHAR2(5),
col4 DATE DEFAULT SYSDATE,
col5 VARCHAR2(20)UNIQUE,
col6 NUMBER CHECK (col6 < 100),
CONSTRAINT tab1_pk PRIMARY KEY(col1),
CONSTRAINT tab1_zipcode_fk FOREIGN KEY(col3) REFERENCES zipcode(zip))

Creating Tables Based on Other Tables


7. Create a table called JAN_07_ENROLLMENT, based on the January 2007 enrollment rows
in the Enrollment table. Verify that the table structure created is similar to that of the
Enrollment table.

CREATE TABLE jan_07_enrollment AS


Select *
FROM enrollment
Where enroll_date >= to_date('01/01/2007', 'DD/MM/YYYY') AND enroll_date <
to_date('01/02/2007', 'DD/MM/YYYY')

You can use the DESCRIBE command to verify that the table structure is similar to the
Enrollment table:
DESCRIBE jan_07_enrollment

8
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

Renaming Tables
 Syntax: RENAME oldName TO newName
8. Rename the JAN_07_ENROLLMENT table to JAN_07.
RENAME jan_07_enrollment TO JAN_07

Dropping Tables
 Removes the table and its data, along with any indexes, constraints, etc
 Syntax: DROP TABLE tablename [PURGE]
 From Oracle 10g, the table is moved into a recycle bin from which it can be recovered (Also
referred to as a flashback drop). If you do not want it moved to recycle bin, use PURGE.

9. Drop the JAN_07 table.


DROP TABLE JAN_07

 Restore the dropped JAN_07 table.


FLASHBACK TABLE JAN_07 TO BEFORE DROP

Using SQL Developer’s GUI to Create Tables


 In Connections Navigator, right-click TablesNew Table

9
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

Altering Tables
 After a table is created, you sometimes need to change its characteristics
 Use ALTER TABLE command, with ADD, DROP, MODIFY and RENAME

Adding Columns
 Add a new column to the table, tab1:

ALTER TABLE tab1


ADD (col7 VARCHAR2(30) NOT NULL)

NOTE: Can perform many ALTER TABLE


commands by right-clicking on the table name
in the Connections navigator and choosing Edit

Dropping Columns
 Drop 2 columns from the table, tab1:
ALTER TABLE tab1
DROP (col6, col7)

Renaming Columns
 Rename a column (col5) from the table, tab1:
ALTER TABLE tab1 RENAME COLUMN col5 TO last_column

Modifying Columns
 To modify data type, length and column defaults
10
Course: ISTM 5002/ 6002- DB Systems & Mgmt Activity: Oracle SQL Tutorial – Part 2
Lecturer: Nalini Singh Week: 6 (Jun 18th – Jun 24th)

 Change length of the col3 in the table, tab1, from 5 to 10 characters:


ALTER TABLE tab1
MODIFY (col3 VARCHAR2(10) )

 Change Data Type of the col2 in the table, tab1, from NUMBER to VARCHAR2:
ALTER TABLE tab1
MODIFY (col2 VARCHAR2(4) )

10. Alter the table NEW_STUDENT that you created in Q8 above by adding four columns. The
columns should be called PHONE, NUM_COURSES (with data type and length NUMBER(3)),
CREATED_BY and CREATED_DATE. Determine the other column data types and lengths
based on the STUDENT table. The PHONE, NUM_COURSES and CREATED_BY columns
should allow null values, with the CREATED_BY column defaulting to the user’s login name.
The CREATED_DATE column should not allow null values and should default to today’s date.

DESCRIBE new_student;
--Before making changes

ALTER TABLE new_student


ADD (phone VARCHAR2(15),
num_courses NUMBER(3),
created_by VARCHAR2(30) DEFAULT USER,
created_date DATE DEFAULT SYSDATE NOT NULL);

--After making changes


DESCRIBE new_student;

 Alter the NEW_STUDENT table to create a primary key consisting of the FIRST_NAME and
LAST_NAME columns.
ALTER TABLE new_student
ADD CONSTRAINT new_student_pk PRIMARY KEY (first_name, last_name)

11

You might also like