Database Programming Sections 7 & 8 – Data Manipulation Language (DML) transaction, INSERT, implicit, explicit, USER, UPDATE, DELETE, integrity constraint,

Slides:



Advertisements
Similar presentations
9 Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Advertisements

9 Creating and Managing Tables. Objectives After completing this lesson, you should be able to do the following: Describe the main database objects Create.
Creating Tables. 2 home back first prev next last What Will I Learn? List and provide an example of each of the number, character, and date data types.
Manipulating Data Schedule: Timing Topic 60 minutes Lecture
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
Creating Triggers.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
8 Copyright © Oracle Corporation, All rights reserved. Manipulating Data.
Oracle Data Definition Language (DDL)
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.
Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Lecture 2: Using DDL Statements to Create and Manage Tables & Indexes
10 Creating and Managing Tables Objectives At the end of this lesson, you will be able to: Describe the main database objects Create tables Describe.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
Objectives After completing this lesson, you should be able to do the following: Describe each data manipulation language (DML) statement Insert rows.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Manipulating Large Data Sets. Lesson Agenda ◦ Manipulating data using subqueries ◦ Specifying explicit default values in the INSERT and UPDATE statements.
4 Copyright © 2007, Oracle. All rights reserved. Manipulating Large Data Sets.
8 Copyright © Oracle Corporation, All rights reserved. Manipulating Data.
Copyright © 2004, Oracle. All rights reserved. MANIPULATING LARGE DATA SETS Oracle Lecture 10.
3 Copyright © 2006, Oracle. All rights reserved. Manipulating Large Data Sets.
Tables and Constraints Oracle PL/SQL. Datatypes The SQL Data Definition Language Commands (or DDL) enable us to create, modify and remove database data.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
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.
8 Copyright © 2007, Oracle. All rights reserved. Managing Schema Objects.
INSERT Statement. 2 home back first prev next last What Will I Learn? Give examples of why it is important to be able to alter the data in a database.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
SQL CREATING AND MANAGING TABLES lecture4 1. Database Objects ObjectDescription TableBasic unit of storage; composed of rows and columns ViewLogically.
Database Programming Sections 7–Multi-row sub queries, IN, ANY, ALL, Data Manipulation Language (DML) transaction, INSERT, implicit, explicit, USER, UPDATE,
Copyright © 2004, Oracle. All rights reserved. Lecture 2: Using DDL Statements to Create and Manage Tables & Indexes ORACLE.
DML Part 1 Yogiek Indra Kurniawan. All Files Can Be Downloaded at : Menu : “Perkuliahan”
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
DDL and Views. Database Objects Logically represents subsets of data from one or more tables View Generates numeric valuesSequence Basic unit of storage;
Database Programming Sections 7– Data Manipulation Language (DML) transaction, INSERT, implicit, explicit, USER, UPDATE, DELETE, integrity constraint,
Creating and Managing Tables 14. ObjectivesObjectives After completing this lesson, you should be able to do the following: After completing this lesson,
Including Constraints. What Are Constraints? Constraints enforce rules at the table level. You can use constraints to do the following: – Enforce rules.
Database Programming Sections 9 & 10 – DDL Data Definition Language,
Copyright © 2004, Oracle. All rights reserved. M ANIPULATING D ATA.
Installation Oracle 11g Express 2 double click the "setup" button to install the Oracle.
Database Programming Sections 7 & 8 – Data Manipulation Language (DML) transaction, INSERT, implicit, explicit, USER, UPDATE, DELETE, integrity constraint,
2 Copyright © 2009, Oracle. All rights reserved. Managing Schema Objects.
Insert, update, delete TCL. Data Manipulation Language – A DML statement is executed when you: Add new rows to a table Modify existing rows in a table.
SQL Creating and Managing Tables
Manipulating Data.
Manipulating Data Schedule: Timing Topic 60 minutes Lecture
Database Programming Sections 7 & 8 – Data Manipulation Language (DML) transaction, INSERT, implicit, explicit, USER, UPDATE, DELETE, integrity constraint,
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
Manipulating Data.
处理数据 Schedule: Timing Topic 60 minutes Lecture 30 minutes Practice
“Manipulating Data” Lecture 6.
(SQL) Manipulating Data
“Manipulating Data” Lecture 6.
Manipulating Data.
Oracle Data Definition Language (DDL)
Using DDL Statements to Create and Manage Tables
Chapter 2 Views.
1 Manipulating Data. 2 Objectives After completing this lesson, you should be able to do the following:  Describe each data manipulation language (DML)
Contents Preface I Introduction Lesson Objectives I-2
Using DDL Statements to Create and Manage Tables
IST 318 Database Administration
DATABASE ADMINISTRATION
Including Constraints
Presentation transcript:

Database Programming Sections 7 & 8 – Data Manipulation Language (DML) transaction, INSERT, implicit, explicit, USER, UPDATE, DELETE, integrity constraint, DDL commands

Marge Hohly2 Overview of remainder of lesson  Data Manipulation Language DML INSERT UPDATE DELETE MERGE  Default Values  Merge Statements  Creating Tables  Using Data Types  Data Definition Language DDL ALTER TABLE DROP TABLE RENAME TRUNCATE COMMENT  Define Constraints  Manage Constraints

Marge Hohly3 Using a subquery to copy a table  In order to experiment with the tables, make a copy of them: Select all rows from the EMPLOYEES table and insert them into the COPY_EMPLOYEES table. CREATE TABLE copy_employees AS (SELECT * FROM employees); Verify by: SELECT * FROM copy_employees; DESCRIBE copy_employees;  the integrity rules (primary keys, default values are not passed to the copy, only the column datatype definitions.)

Marge Hohly4 Explicitly inserting data  Executing one DML statement is considered a transaction.  The INSERT statement is used to add new rows to a table. To get the column names and default order, use:  The statement requires three values: the name of the table the name of the column in the table to populate a corresponding value for the column –  INSERT INTO copy_departments (department_id, department_name, manager_id, location_id) VALUES (70,’Public Relations’, 100, 1700);  INSERT INTO copy_departments (department_id, manager_id, location_id, department_name) VALUES (99, 100, 1700, ‘Advertising’)

Marge Hohly5 Implicitly inserting data  Omit the column names  Match exactly the default order in which columns appear in the table  Provide a value for each column  Data types need to match  Use DESCRIBE to check the table structure before adding is a good idea  INSERT INTO copy_departments VALUES (100,’Education’, 100, 1700);  using VALUES adds on row at a time

Marge Hohly6 Insert with NULL values  Implicit Method – omit the column from the column list Any column that is not listed obtains a null value in the new row – errors can occur – the row has been specified NOT NULL, uniqueness, foreign key violation INSERT INTO copy_departments (department_id, department_name) VALUES (30,’Purchasing’);  Explicit Method – specify the NULL keyword in the values clause INSERT INTO copy_departments VALUES (100, ‘Finance’, NULL, NULL);

Marge Hohly7 Inserting Special Values  Special values such as SYSDATE and USER can be entered in the VALUES list of an INSERT statement.  SYSDATE puts current date and time in a column  USER places current username (Oracle Application Express will put APEX_PUBLIC_USER)  INSERT INTO copy_employees (employee_id, last_name, , hire_date,job_id) VALUES(1001, USER, ‘Test’, SYSDATE, ‘IT_PROG’);

Inserting Special Values  Can add functions and calculated expressions as values  Example of inserting a system date and a calculated expression  INSERT INTO copy_f_orders (order_number, order_date, order_total,cust_id, staff_id) VALUES (1889,SYSDATE,87.92*1.08,123,19); Marge Hohly8

9 Inserting Specific date values  The default date before Oracle 9i was DD- MON-YY.  The default format from Oracle 9i on is DD- MON-RR century defaults to the current century default time of midnight (00:00:00) formats other than the default format use TO_DATE function  INSERT INTO copy_employees VALUES (114, ‘Den’, ‘Raphealy’, ‘DRAPHEAL’, ‘ ’, ’03-FEB-49’, ‘AC_ACCOUNT’, 11000, NULL, 100, 30);

Inserting Date values  The default format model for date is DD- MON-RR.  Recall the century defaults to the nearest century (nearest to SYSDATE) with default time midnight (00:00:00)  TO_CHAR review: SELECT first_name, TO_CHAR(birthdate, ‘Month fmDD, RRRR’) FROM f_staffs WHERE id=12; Marge Hohly10

Inserting Date values  To INSERT a row with a non-default format for a date column, use the TO_DATE function to convert the date value (a character string ) to a date  INSERT INTO copy_f_staffs (first_name, last_name, birthdate, salary, staff_type) VALUES ('Sue', 'Jones', TO_DATE('July 1, 1980','Month fmDD, RRRR'), 25, 'clerk'); Marge Hohly11

Marge Hohly12 Date Example  INSERT INTO copy_employees VALUES (114, ‘Den’, ‘Raphealy’, ‘DRAPHEAL’, ‘ ’, ’03-FEB-49’, ‘AC_ACCOUNT’, 11000, NULL, 100, 30);  SELECT last_name, TO_CHAR(hire_date, ’Month dd, RRRR’) FROM copy_employees WHERE employee_id = 114;

Example  INSERT INTO copy_f_staffs (first_name, last_name, birthdate, salary, staff_type) VALUES ('Sue', 'Jones', TO_DATE('July 1, :20','Month fmDD, RRRR HH24:MI'), 2500, 'clerk'); Marge Hohly13

Inserting multiple rows  INSERT statement can be used to insert one row, but to insert multiple rows use a subquery  Use a subquery within the INSERT command to insert multiple rows Marge Hohly14

Marge Hohly15 Using a subquery to copy rows  Copy values from an existing table CREATE TABLE sales_reps (id number(5), name varchar2(15), salary number(10), commission_pct number (8));  No VALUES clause INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct FROM employees WHERE job_id LIKE ‘%REP%’;  NOTE: subquery is not in parentheses as in WHERE clause previously

Copy all the data from a table  INSERT INTO sales_reps SELECT * FROM employees;  This works ONLY if both tables have same number of columns, same types, and in the same order. Marge Hohly16

Marge Hohly17 UPDATE statements  The UPDATE statement is used to modify existing rows in a table. It requires four values: the name of the table  UPDATE copy_employees the name of the column in the table to populate  SET department_id a corresponding value or subquery for the column  SET department_id = 70 a condition that identifies the columns and the changes for each column  WHERE employee_id = 103; New value can be from a single-row subquery

Marge Hohly18 Updating one column  Specific row or rows are modified if you specify the WHERE clause. UPDATE copy_employees SET department_id = 70 WHERE employee_id = 103; (One row is updated)  WARNING: All rows in the table are modified if you omit the WHERE clause. UPDATE copy_employees SET department_id = 110; (All rows are updated)

UPDATING multiple columns  Can update one or more rows in a statement  UPDATE copy_f_customers SET phone_number = ‘ ’, city = ‘Chicago’ WHERE id<200;  If no WHERE clause all rows are updated in the table Marge Hohly19

Marge Hohly20 Update using subquery  UPDATE copy_employees SET department_id = (SELECT department_id FROM employees WHERE last_name = ‘Ernst’) WHERE employee_id = 103;

Marge Hohly21 Updating columns with subqueries  You can update one or more columns in the SET clause of an UPDATE statement by writing subqueries.  UPDATE copy_employees SET job_id = (SELECT job_id FROM employees WHERE employee_id =205), salary = (SELECT salary FROM employees WHERE employee_id =205) WHERE employee_id = 114;

Updating rows based on another table  Use a subquery to update data in one table with data in another table  UPDATE copy_f_staffs SET salary = (SELECT salary FROM f_staffs WHERE id = 9) WHERE id = 9; Marge Hohly22

Updating Rows Based on the Same Table  Updating can be done with a correlated subquery  In a correlated subquery you are updating a row in a table based on a select from the same table.  UPDATE copy_employees e SET e.department_id = (SELECT d.department_id FROM departments d WHERE e.department_id = d.department_id); Marge Hohly23

Marge Hohly24 DELETE statement  The DELETE statement is used to remove existing rows in a table. The statement requires two values: the name of the table the condition that identifies the rows to be deleted DELETE FROM copy_employees WHERE employee_id = 200; If you omit the WHERE clause all rows will be deleted

Marge Hohly25 Subquery Delete  Use subqueries in DELETE statements to remove rows from a table based on values from another table.  DELETE FROM copy_employees WHERE department_id = (SELECT department_id FROM departments WHERE department_name = ‘Shipping’);

Deleting rows based on another table  A subquery can be used to remove rows from one table based on values from another table  DELETE FROM emp WHERE plant_id = (SELECT plant_id FROM locations WHERE plant_loc = ‘AnyVilla’); Marge Hohly26

Correlated subquery DELETE  DELETE FROM copy_employees e WHERE e.manager_id = (SELECT d.manager_id FROM departments d WHERE e.department_id = d.department_id HAVING count(d.department_2) > 2 GROUP BY d.manager_id); Marge Hohly27

Marge Hohly28 Integrity Constraints  Integrity constraints define certain data quality requirements that the data in the database needs to meet. If a user tries to insert data that doesn’t meet these requirements an error will occur.  Types of Integrity constraints NOT NULL – each row in the column must have a value PRIMARY KEY – unique and not null FOREIGN KEY – A foreign key constraint (also called referential integrity constraint) on a column ensures that the value in that column is found in the primary key of another table. CHECK – value meets certain conditions salary CHECK < UNIQUE – no duplicate values in a column ( address)

Marge Hohly29 Integrity Constraint Errors  UPDATE employees SET department_id = 55 WHERE department_id = 110;  ORA-02291: integrity constraint (USCA_INST_SQL03_T01.EMP_DEPT_ FK) violated – parent key not found  There is no department_id = 55 in the departments table which is the parent table.

Marge Hohly30

Marge Hohly31

Marge Hohly32 Default Values  A column in a table can be given a default value.  Assigning default values prevents null values from existing in the column.  Default values can be: a literal value, ‘no commission assigned’ an expression, salary*1.15 SQL function, such as SYSDATE or USER  Default values must match the data type of the column

Marge Hohly33 Default Values Examples  Default Values Specified at the time the table is created: CREATE TABLE items( part_number VARCHAR2(10), description VARCHAR2(10), qty_on_hand NUMBER DEFAULT 0);  INSERT INTO items(part_number, description) VALUES (‘AB154’,’hammer’);

Marge Hohly34 Default Values - Examples  Use DEFAULT when inserting values: INSERT INTO items(part_number, description, qty_on_hand) VALUES (300,’Widget’, DEFAULT);  Use DEFAULT when updating values: UPDATE items SET qty_on_hand = DEFAULT WHERE part_number = 200;  Now check the results! SELECT * FROM items;

Marge Hohly35

Marge Hohly36 MERGE Statements  MERGE Statement Accomplishes an UPDATE and INSERT at the same time ** the ON clause specifies the match – if two id’s match make the following updates, otherwise insert the following as new rows MERGE INTO copy_emp c USING employees e ON (c.employee_id = e.employee_id) WHEN MATCH THEN UPDATE SET c.first_name = e.first_name c.last_name = e.last_name..... c.department_id = e.department_id WHEN NOT MATCHED THEN INSERT VALUES( e.employee_id, e.first_name, e.last_name, e.salary, e.commission_pct, e.manager_id, e.department_id);

Marge Hohly37 MERGE Example:  MERGE INTO copy_items c USING items i ON(c.part_number = i.part_number) WHEN MATCHED THEN UPDATE SET c.description = i.description, c.qty_on_hand = i.qty_on_hand WHEN NOT MATCHED THEN INSERT VALUES (i.part_number, i.description, i.qty_on_hand);

Marge Hohly38

Marge Hohly39

Marge Hohly40

Marge Hohly41

Marge Hohly42

Marge Hohly43

Marge Hohly44

Marge Hohly45 CREATING TABLES  Naming Rules: Must begin with a letter Must be 1 to 30 characters in length Must only contain alpha/numeric,_,$,# Must be unique in your schema Must not be an Oracle Server reserved word

Marge Hohly46 Using Data Types  Most Common Data Types: VARCHAR2  Examples: Name, Address NUMBER  Examples: Price, Quatity DATE  Examples: DOB, Hire Date

Marge Hohly47 Creating Tables  CREATE TABLE name (column name DATATYPE(specifications for datatype) VARCHAR2(number of characters) – variable length data CHAR(size) – fixed length data NUMBER(precision, scale) – total number of decimal digits(1 to 38), right of decimal digits(- 84 to 127) For example, a scale of 2 means the value is rounded to the nearest hundredth (3.456 becomes 3.46); a scale of -3 means the number is rounded to the nearest thousand (3456 becomes 3000). DATE – date and time

Marge Hohly48 Creating Tables cont’d  Example: CREATE TABLE students (id VARCHAR2(5), lname VARCHAR2(15), fname VARCHAR2(15), GPA number(6), enroll_date date DEFAULT SYSDATE);  CREATE TABLE table (column datatype [DEFAULT expression], (column datatype [DEFAULT expression]….);

Marge Hohly49

Marge Hohly50

Marge Hohly51

Marge Hohly52

Marge Hohly53

Marge Hohly54

Marge Hohly55 ORACLE Data Dictionary  The data dictionary is a collection of tables created and maintained by the Oracle Server and contains information about the database.  All data dictionary tables are owned by the SYS user. Because the tables are difficult to understand, users access data dictionary includes names of the Oracle Server users, privileges granted to users, database object names, table constrains and auditing information.  You may browse the Oracle Data Dictionary to show objects you own. SELECT * FROM DICTIONARY; - returns 835 items SELECT table_name FROM user_tables; SELECT DISTINCT object_type FROM user_objects; SELECT * FROM user_catalog;

Marge Hohly56

Marge Hohly57 Using Data Types – Interval Year to Month  INTERVAL YEAR TO MONTH: Stores a period of time in years/months Note that the argument 3 in the create table and insert statements refers to precision  CREATE TABLE time_ex2 (school_year_duration INTERVAL YEAR (3) TO MONTH);  INSERT INTO time_ex2(school_year_duration) VALUES(INTERVAL ‘9’ Month(3));  SELECT TO_CHAR(SYSDATE + school_year_duration, ‘dd-Mon-yyyy’) FROM time_ex2;  Returned 9 month from today’s date

Marge Hohly58 Using Data Types- USING INTERVAL DAY TO SECOND  INTERVAL DAY TO SECOND: Stores a more precise period of time (days/hours/minutes/seconds) CREATE TABLE time_ex3(day_duration INTERVAL DAY(3) to SECOND); INSERT INTO time_ex3(day_duration) VALUES(INTERVAL ‘180’ DAY(3)); SELECT SYSDATE + day_duration “Half Year” FROM time_ex3;

Marge Hohly59 Using Time Data Types  TIMESTAMP: stores values with respect to universal time CREATE TABLE time_example (order_date TIMESTAMP WITH LOCAL TIME ZONE, ship_date DATE DEFAULT SYSDATE); INSERT INTO time_example VALUES(SYSDATE, SYSDATE); SELECT * FROM time_example;

Marge Hohly60

Marge Hohly61

Marge Hohly62

SET UNUSED  ALTER TABLE tablename SET UNUSED(column name);  Dropping a column can take a long time  Setting column unused is faster.  Makes column not able to be accessed - invisible Marge Hohly63

Marge Hohly64

Marge Hohly65

Marge Hohly66

Marge Hohly67