5 - DDL and DML PDF
5 - DDL and DML PDF
Materi 5
MK. Basisdata
Dosen : Roni Salambue, M.Si
1
Objectives
• Review a table structure
• Describe how schema objects are used by the Oracle database
• Create a table using the appropriate data type for each column
• Learn about data types and their uses.
• Explain and provide an example for each of the DDL statements -
ALTER, DROP, FLASHBACK, RENAME and TRUNCATE
• Explain a data manipulation language (DML) statements – INSERT,
UPDATE and DELETE to make changes to a database.
2
Outline
• Create tables
• Data types
• Modifying a table
• Insert statements
• Updating column values and deleting rows
3
Introduction
• As a Database Administrator (DBA), you will be expected to know how
to create tables as well.
• Your tables will be small compared to tables that hold millions of rows
and hundreds of columns, but creating a small table involves the
same SQL statements and syntax as creating a very large one.
4
Database Schema Objects
• A database can contain many different types of objects.
• The main database object types are:
• Table
• Index
• Constraint
• View
• Sequence
• Synonym
• Some of these object types can exist independently and others can
not.
5
Database Schema Objects
• Some of the object types take up space, known as storage, in the
database and others do not.
• Database objects taking up significant storage space are known as
Segments.
• Tables and Indexes are examples of Segments, as the values stored in
the columns of each row take up significant physical disk space.
• Views, Constraints, Sequences, and Synonyms are also objects, but
the only space they require in the database is in the definition of the
object—none of them have any data rows associated with them.
6
Table Creation
• All data in a relational database is stored in tables.
• When creating a new table, use the following rules for table names
and column names:
• Must begin with a letter
• Must be 1 to 30 characters long
• Must contain only A - Z, a - z, 0 - 9, _ (underscore), $, and #
• Must not duplicate the name of another object owned by the same user
• Must not be an Oracle Server reserved word
7
Naming Conventions
• It is best to use descriptive names for tables and other database
objects.
• If a table will store information about students, name it STUDENTS,
not PEOPLE or CHILDREN.
• Table names are not case sensitive.
• For example, STUDENTS is treated the same as STuDents or students.
• Table names should be plural, for example STUDENTS, not student.
• Creating tables is part of SQL's data definition language (DDL).
• Other DDL statements used to set up, change, and remove data
structures from tables include ALTER, DROP, RENAME, and TRUNCATE.
8
CREATE TABLE
• To create a new table, you must have the CREATE TABLE privilege and
a storage area for it.
• The database administrator uses data control language (DCL)
statements to grant this privilege to users and assign a storage area.
• Tables belonging to other users are not in your schema.
• If you want to use a table that is not in your schema, use the table
owner's name as a prefix to the table name:
11
Data Dictionary
• Two kinds of tables exists in an Oracle Database:
User tables and Data Dictionary tables.
• Select, insert, update, and delete data in the user
tables
• Select data in the Data Dictionary tables.
• User tables created by user containing the data:
employees, departments, jobs, etc.
• Data Dictionary tables: DICTIONARY,
USER_OBJECTS, USER_TABLES, USER_SEGMENTS,
USER_INDEXES, etc.
12
Data Dictionary
• The Data Dictionary tables are all owned by a
special Oracle user called SYS and only SELECT
statements should be used when working with any
of these tables.
• If any Oracle user attempts to do inserts, updates,
or deletes against any of the Data Dictionary
tables, the operation is disallowed as it might
compromise the integrity of the entire database.
13
Data Dictionary
• When you are using the Data Dictionary views in the SQL Commands
interface, you need to know the names of the Dictionary views you
are working with.
• In Oracle, this is quite simple: prefix the object type you are looking
for with a USER_xxx or an ALL_xxx, where xxx is the object type.
14
Data Dictionary
• So if you want to investigate indexes, then simply select from
USER_INDEXES; if you want information about sequences, then the
table is USER_SEQUENCES and so on.
15
Data Type Overview
• Each value manipulated by Database has a data type.
• A value's data type associates a fixed set of properties with the value.
• These properties cause the database to treat values of one data type
differently from values of another data type.
16
Data Type Overview
• Different data types offer several advantages:
• Columns of a single type produce consistent results.
• For example, DATE data type columns always produce date values.
• You cannot insert the wrong type of data into a column.
• For example, columns of data type DATE will prevent NUMBER type data from
being inserted.
• For these reasons, each column in a relational database can hold only
one type of data.
• You cannot mix data types within a column.
17
Common Data Types
• The most commonly used column data types for character and
number values are below.
• For character values:
• CHAR (fixed size, maximum 2000 characters)
• VARCHAR2 (variable size, maximum 4000 characters)
• CLOB (variable size, maximum 128 terabytes)
• For number values:
• NUMBER (variable size, maximum precision 38 digits)
18
Common Data Types
• The most commonly used column data types for date, time, and
binary values are below.
• For date and time values:
• DATE
• TIMESTAMP ….
• INTERVAL
• For binary values (eg. multimedia: JPG, WAV, MP3, and so on):
• RAW (variable size, maximum 2000 bytes)
• BLOB (variable size, maximum 128 terabytes)
19
Common Data Types
• For character values, it is usually better to use VARCHAR2 or CLOB
than CHAR, because it saves space.
• For example, an employee's last name is 'Chang'.
• In a VARCHAR2(30) column, only the 5 significant characters are
stored: C h a n g.
• But in a CHAR(30) column, 25 trailing spaces would be stored as well,
to make a fixed size of 30 characters.
• Number values can be negative as well as positive. For example,
NUMBER(6,2) can store any value from +9999.99 down to –9999.99.
20
DATE-TIME Data Types
• The DATE data type stores a value of centuries down to whole
seconds, but cannot store fractions of a second.
• '21-Aug-2003 17:25:30' is a valid value, but '21-Aug-2003
17:25:30.255' is not.
• The TIMESTAMP data type is an extension of the DATE data type
which allows fractions of a second.
• For example, TIMESTAMP(3) allows 3 digits after the whole seconds,
allowing values down to milliseconds to be stored.
21
DATE-TIME Data Types
• TIMESTAMP Example
22
ALTER TABLE
ALTER TABLE statements are used to:
• Add a new column
• Modify an existing column
• Define a DEFAULT value for a column
• Drop a column
• A newly added column always becomes the last column of the table.
• Also, if a table already has rows of data and you add a new column to
the table, the new column is initially null for all of the pre-existing the
rows.
23
ALTER TABLE: Adding a Column
• To add a new column, use the SQL syntax shown:
• For example:
ALTER TABLE tablename ADD (column name data type
[DEFAULT expression], column name data type
[DEFAULT expression], ...
ALTER TABLE my_cd_collection ADD (release_date
DATE DEFAULT SYSDATE);
ALTER TABLE my_friends ADD (favorite_game
VARCHAR2(30));
24
ALTER TABLE: Modifying a Column
• Modifying a column can include changes to a column's data type, size, and
DEFAULT value.
• Rules and restrictions when modifying a column are:
• You can increase the width or precision of a numeric column.
• You can increase the width of a character column.
• You can decrease the width of a NUMBER column if the column contains only null
values, or if the table has no rows.
• For VARCHAR types, you can decrease the width down to the largest value contained
in the column.
• You can change the data type only if the column contains null values.
• You can convert a CHAR column to VARCHAR2 or convert a VARCHAR2 COLUMN to
CHAR only if the column contains null values, or if you do not change the size to
something smaller than any value in the column.
• A change to the DEFAULT value of a column affects only later insertions to the table.
25
ALTER TABLE: Modifying a Column Example
• Example: a table has been created with two columns:
CREATE TABLE mod_emp(last_name VARCHAR2(20),
salary NUMBER(8,2));
• Which of these modification would be allowed, and which would not?
(Consider your answers both with and without rows of data in the table.)
ALTER TABLE mod_emp MODIFY (last_name VARCHAR2(30));
ALTER TABLE mod_emp MODIFY (last_name VARCHAR2(10));
ALTER TABLE mod_emp MODIFY (salary NUMBER(10,2));
ALTER TABLE mod_emp MODIFY (salary NUMBER(8,2)
DEFAULT 50);
26
ALTER TABLE: Modifying a Column Example
• Would be permitted with or without data as column width increased.
ALTER TABLE mod_emp MODIFY (last_name VARCHAR2(30));
• Would be permitted only if columns were empty, or the largest name was
10 or less characters
ALTER TABLE mod_emp MODIFY (last_name VARCHAR2(10));
• Would be permitted with or without data as column precision increased.
ALTER TABLE mod_emp MODIFY (salary NUMBER(10,2));
• Would be permitted with or without data as only a DEFAULT value added.
ALTER TABLE mod_emp MODIFY (salary NUMBER(8,2)
DEFAULT 50);
27
ALTER TABLE: Dropping a Column
• When dropping a column the following rules apply:
• A column containing data may be dropped.
• Only one column can be dropped at a time.
• You can't drop all of the columns in a table; at least one column must remain.
• Once a column is dropped, the data values in it cannot be recovered.
28
ALTER TABLE: Dropping a Column
• SQL Syntax:
ALTER TABLE tablename DROP COLUMN column name;
• For Example:
ALTER TABLE my_cd_collection DROP COLUMN
release_date;
ALTER TABLE my_friends DROP COLUMN
favorite_game;
29
DROP TABLE
• The DROP TABLE statement removes the definition of an Database
table.
• The database loses all the data in the table and all the indexes
associated with it.
• When a DROP TABLE statement is issued:
• All data is deleted from the table.
• The table's description is removed from the Data Dictionary.
30
DROP TABLE
• In the next slide, you will see that you may be able to restore a table
after it is dropped, but it is not guaranteed.
• Only the creator of the table or a user with DROP ANY TABLE privilege
(usually only the DBA) can remove a table.
• Syntax:
DROP TABLE tablename;
• Example:
DROP TABLE copy_employees;
31
FLASHBACK TABLE
• If you drop a table by mistake, you may be able to bring that table
and its data back.
• Each database user has his own recycle bin into which dropped
objects are moved, and they can be recovered from here with the
FLASHBACK TABLE command.
• This command can be used to restore a table, a view, or an index that
was dropped in error.
• The Syntax is:
FLASHBACK TABLE tablename TO BEFORE DROP;
32
RENAME
• To change the name of a table, use the RENAME statement.
• This can be done only by the owner of the object or by the DBA.
• Syntax:
RENAME old_name to new_name;
• Example:
RENAME my_cd_collection TO my_music;
• We will see later that we can rename other types of objects such as
views, sequences, and synonyms.
33
TRUNCATE
• Truncating a table removes all rows from a table and releases the storage
space used by that table.
• When using the TRUNCATE TABLE statement:
• You cannot roll back row removal.
• You must be the owner of the table or have been given DROP ANY TABLE system
privileges.
• Syntax:
TRUNCATE TABLE tablename;
• The DELETE statement also removes rows from a table, but it does not
release storage space.
• TRUNCATE is faster than DELETE because it does not generate rollback
information.
34
INSERT
• The INSERT statement is used to add a new row to a table.
• The statement requires three values:
• the name of the table
• the names of the columns in the table to populate
• corresponding values for each column
35
Copy Tables Before Inserting
• To keep your schema tables in their original state, you will make a
copy of each table.
• The table copies will not inherit the associated primary-to foreign-key
integrity rules (relationship constraints) of the original tables.
• The column data types, however, are inherited in the copied tables.
36
Syntax to Create a Copy of a Table
• Create table syntax:
CREATE TABLE copy_tablename AS (SELECT * FROM
tablename);
• For example:
CREATE TABLE copy_employees AS (SELECT * FROM
employees);
CREATE TABLE copy_departments AS (SELECT * FROM
departments);
37
Syntax to Create a Copy of a Table
• To verify and view the copy of the table, use the following DESCRIBE
and SELECT statements:
DESCRIBE copy_employees;
SELECT * FROM copy_employees;
DESCRIBE copy_departments;
SELECT * FROM copy_departments;
38
INSERT
• The syntax below uses INSERT to add a new department to the
copy_departments table.
• This statement explicitly lists each column as it appears in the table.
• The values for each column are listed in the same order.
• Note that number values are not enclosed in single quotation marks.
39
INSERT
• Another way to insert values in a table is to implicitly add them by omitting
the column names.
• One precaution: the values for each column must match exactly the default
order in which they appear in the table (as shown in a DESCRIBE
statement), and a value must be provided for each column.
• The INSERT statement in this example was written without explicitly
naming the columns.
• For clarity, however, it is best to use the column names in an INSERT clause.
40
UPDATE
• The UPDATE statement is used to modify existing rows in a table.
• UPDATE requires four values:
• the name of the table
• the name of the column(s) whose values will be modified
• a new value for each of the column(s) being modified
• a condition that identifies which rows in the table will be modified.
• The new value for a column can be the result of a single-row
subquery.
41
UPDATE
• The example shown uses an UPDATE statement to change the phone
number of one employee in the employees table.
• Note that the copy_employees table is used in this transaction.
UPDATE copy_employees
SET phone_number = '123456'
WHERE employee_id = 303;
42
UPDATE
• We can change several columns and/or several rows in one UPDATE
statement.
• This example changes both the phone number and the last name for
two employees.
UPDATE copy_employees
SET phone_number = '654321', last_name = 'Jones'
WHERE employee_id >= 303;
43
UPDATE
• Take care when updating column values.
• If the WHERE clause is omitted, every row in the table will be updated.
• This may not be what was intended.
UPDATE copy_employees
SET phone_number = '654321', last_name = 'Jones'
44
DELETE
• 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
45
DELETE
• The example shown uses the copy employee table to delete one
row—the employee with ID number 303.
46
Integrity Constraint Errors
• Integrity constraints ensure that the data conforms to a needed set of
rules.
• The constraints are automatically checked whenever a DML
statement which could break the rules is executed.
• If any rule would be broken, the table is not updated and an error is
returned.
47
Integrity Constraint Errors
• When will primary key - foreign key constraints be checked?
• The EMPLOYEES table has a foreign key constraint on department_id
which references the department_id of the DEPARTMENTS table.
• This ensures that every employee belongs to a valid department.
• In the DEPARTMENTS table, department_ids 10 and 20 exist but 15
does not.
48
Integrity Constraint Errors
• Which of the following statements will return an error?
1. UPDATE employees SET department_id = 15 WHERE
employee_id = 100;
49
Thank you
50