DBDev 02 (4) 2
DBDev 02 (4) 2
Chapter 2
3 / 90
Introduction to SQL
! SQL-99
◦ Most recent version
◦ Not all DBMSs fully comply with SQL-99
! SQL-92
◦ Almost all DBMSs support SQL-92 (SQL ANSI)
◦ Most vendors add extensions to the standard SQL
commands to make their DBs more powerful and easy to use
4 / 90
Introduction to SQL
! Data Definition Language (DDL) commands
◦ Used to create new DB objects
● User names
● Tables
◦ To modify or delete existing objects
◦ The command immediately change the DB, so you don’t need
to save the change explicitly
◦ Usually done by DBAs
◦ Some utilities can be used to execute DDL commands, they
will automatically generate the underlying SQL commands.
5 / 90
Introduction to SQL
! Data Manipulation Language (DML) commands
◦ To insert, update, delete, and view DB data
◦ Must explicitly saved, to make the new data visible to other
DB users
6 / 90
Introduction to SQL
! Reserved words
◦ All SQL commands
7 / 90
Oracle 10g User Accounts
! User account
◦ Created for each user
◦ Identified using unique username and password
◦ Each user can create tables and other data objects that
reside in his area of the DB, which is called a user schema
8 / 90
Defining Oracle 10g DB Tables
! Tables
◦ Primary data objects in RDB
◦ Table name, column names, data type, size
! Constraints
◦ Restrictions on data values that column can store
● Whether it is a primary key, accepts NULL
9 / 90
Defining Oracle 10g DB Tables
! Oracle naming standard
◦ Rules that Oracle corporation has established for naming all
database objects
◦ Objects must be 1 to 30 characters long
◦ Contain letters, numbers, and special symbols $, _, and #
◦ Begin with character
● Not allowed: book-5, #course, $price
10 / 90
Oracle 10g Data Types
! Data type
◦ Specifies kind of data that column stores
◦ Provides means for error checking
◦ Enable DBMS to use storage space more efficiently
◦ Basic types
● Character
● Number
● Date/time
● Large object
11 / 90
Character Data Types
! Stores characters and numbers not used for calculations
! VARCHAR2
◦ Variable-length character data
◦ Values in different rows can have a different number of characters
◦ Up to 4000 characters
◦ If the user, inserts a value smaller than the maximum, size, DBMS
stores only the actual character values without trailing blanks
◦ If a user inserts more characters ! error
◦ Supports ASCII only, NVARCHAR2 supports Unicode
◦ Syntax
columnname VARCHAR2(maximum_size)
◦ Example
s_last VARCHAR2(30)
12 / 90
Character Data Types
! CHAR
◦ Fixed-length character data
◦ Up to 2000 characters
◦ Data values for different rows all have the same number of characters
◦ Recommended to be used with values such as SR, JR, SO, FR, all have the
same length
◦ If more characters inserted ! error
◦ DBMS adds trailing blank spaces to fill the maximum size
◦ It uses storage space more efficiently than VARCHAR2, and DBMS
processes data retrieved from CHAR column faster
◦ Supports ASCII only, NCHAR supports Unicode
◦ Syntax
columnname CHAR[(maximum_size)] default is 1
◦ Example
s_class char(2)
13 / 90
Character Data Types
! LONG
◦ Not recommended
◦ Limitations
◦ Up to 2 GB of character data
14 / 90
Number Data Type
! Oracle 10g stores all numerical data using the NUMBER
data type.
! The NUMBER data type stores
◦ Negative
◦ Positive
◦ Fixed
◦ Floating-point
numbers between 10-130 and 10125, with precision up to 28
decimal places.
◦ Syntax
● columnname NUMBER [([precision,] [scale])]
◦ Precision is the total number of digits both to the left and to the
right of the decimal point
◦ Scale specifies the number of digits on the right side of the
decimal point
15 / 90
Number Data Types
! Integer numbers
◦ Whole number with no digits on the right side of the
decimal point
◦ Syntax (same as NUMBER but omit the scale value
● columnname NUMBER(precision)
◦ Use integers to declare surrogate keys
◦ f_id NUMBER(5)
◦ If you enter a value < specified precision ! DBMS does not display or
store leading zeros
◦ If you enter a value > specified precision ! error
◦ If you enter digits on the right side of the decimal point, the value
rounded to the nearest whole number
16 / 90
Number Data Types
! Fixed-point number
◦ Contains specific number of decimal places
◦ Column declaration specifies both precision and scale
◦ Example
● price NUMBER(5, 2)
● The number ranges between 0 and 999.99
17 / 90
Number Data Types
! Floating-point number
◦ Contains a variable number of decimal places
◦ The decimal point can appear anywhere, or can be omitted
◦ Syntax
columnname NUMBER
◦ Example
s_gpa NUMBER
18 / 90
Date and Time Data Types
! Datetime data subtypes
◦ Store actual date and time values
◦ DATE
◦ TIMESTAMP
19 / 90
Date and Time Data Types
! DATE
◦ Stores dates from 31 Dec 4712BC - 31 Dec 4712AD
◦ Default date format
● DD-MON-YY
◦ Default time format
● HH:MI:SS AM
● If time is not entered ! default time:12:00:00 AM
◦ Syntax:
columnname DATE
◦ Example:
s_dob DATE
20 / 90
Date and Time Data Types
! TIMESTAMP
◦ Stores date values similar to DATE data type, except it
also stores fractional seconds in addition to the century,
year, month, day, hour, minute, and second
◦ Syntax
columnname TIMESTAMP (fractional_seconds_precision)
◦ Example
sl_date_received TIMESTAMP(2)
◦ Example
● 04-SEP-06 09.26.01.123975
DD-Mon-YY HH.MM.SS.FFFFFF
● If you omit the fractional_seconds_precision specification, the default
value is six decimal places.
21 / 90
Date and Time Data Types
! INTERVAL YEAR TO MONTH
◦ Stores time interval expressed in years and months
◦ Syntax
+|– elapsed_years - elapsed_months
● Ex: +02-11 : specifies a positive time interval of 2 years
and 11 months.
22 / 90
Date and Time Data Types
◦ You use the following command to declare an
INTERVAL YEAR TO MONTH data column:
● INTERVAL YEAR [(year_precsion)] TO MONTH
● Ex: time_enrolled INTERVAL YEAR TO MONTH
23 / 90
Date and Time Data Types
! INTERVAL DAY TO SECOND
◦ Stores time interval expressed in days, hours, minutes, and
seconds
◦ Syntax
● +|– elapsed_days elapsed_hours:elapsed_minutes:elapsed_seconds
◦ Declaration
● Columnname INTERVAL DAY [( leading_precision)]
TO SECOND{(fractional_seconds_precision)]
● The default values for these expressions are 2 and 6 respectively.
● Ex: time_enrolled INTERVAL DAY TO SECOND
24 / 90
Large Object (LOB) Data Types
! Stores binary data such as:
◦ Digitized sounds or images
◦ References to binary files from word processor or
spreadsheet
! Syntax
◦ columnname Lob_data_type
◦ You don’t specify the size, the DB automatically allocate the
correct size
25 / 90
Large Object (LOB) Data Types
26 / 90
Constraints
! Rules that restrict data values that can be entered into
column
! Types of constraints:
◦ Integrity constraints: define primary and foreign keys
27 / 90
Levels of Constraints
! Table constraint: restricts the data value with respect
to all other values in the table.
◦ Example: primary key constraint which must be unique and
can’t appear in this column in more than one table row.
28 / 90
Levels of Constraints
! Constraint definitions should be placed either:
◦ At end of CREATE TABLE command after table columns
declared
◦ Within each column definition
29 / 90
Levels of Constraints
! Every constraint in a user schema must have a unique
constraint name that must adhere to the Oracle
naming standards:
30 / 90
Levels of Constraints
◦ This type of naming strategy makes it difficult to determine,
solely by its name, with which table the constraint is
associated.
31 / 90
Levels of Constraints
! The constraint naming convention uses the following
syntax:
tablename_columnname_constraintID
ConstraintID is a two character abbreviation that describes the
constraint.
32 / 90
Integrity Constraints
! Primary keys constraint
◦ Defines primary and foreign keys and their corresponding
table and column references.
33 / 90
Integrity Constraints
◦ Example (Constraint definition is independent of the column declaration):
CREATE TABLE location
(loc_id NUMBER(6),
bldg_code VARCHAR2(12),
room VARCHAR2(6),
capacity NUMBER(5),
CONSTRAINT location_loc_id_pk PRIMARY KEY (loc_id));
34 / 90
Integrity Constraints
! Foreign keys constraint
◦ Column constraint that specifies that the value a user inserted in a column
must exist as a primary key in a referenced table.
35 / 90
Integrity Constraints
! Example (independently of the column declaration)
CONSTRAINT faculty_loc_id_fk FOREIGN KEY (loc_id)
REFERENCES location (loc_id)
36 / 90
Integrity Constraints
! Composite keys constraint
◦ A primary key composed of two or more data columns, defined by
listing all of the columns that make up the composite primary key,
with each column name separated by a comma.
◦ Syntax
CONSTRAINT constraint_name
PRIMARY KEY (columnname1, columnname2, …)
◦ You should place the composite key definition after the commands
in the CREATE TABLE command that define the columns that
make up the key
37 / 90
Integrity Constraints
! Example
38 / 90
Integrity Constraints
! Value Constraints: column level constraints that
restrict the data values that users can enter into a
given column.
! Types:
1. CHECK
2. NOT NULL
3. DEFAULT
4. UNIQUE
39 / 90
1. CHECK Conditions
! Specify that a column value must be:
◦ a specific value, such as (M, F)
◦ Fall within a specific range ( 0 < x < 1000 )
40 / 90
1. CHECK Conditions
! The DBMS must be able to evaluate each expression
in a check condition as either true or false. You can
combine expressions using the logical operators
AND and OR.
41 / 90
1. CHECK Conditions
! Ex:
CONSTRAINT student_s_class_cc CHECK
((s_class = ‘FR’) OR (s_class = ‘SO’)
OR (s_class = ‘JR’) OR (s_class = ‘SR’))
! Ex:
CONSTRAINT course_credits_cc
CHECK((credits > 0) AND (credits < 12))
42 / 90
2. NOT NULL Constraints
! Specifies whether the user must enter a value for a
specific row, or whether the value can be NULL
(absent or unknown).
! Ex:
s_last VARCHAR2(30) CONSTRAINT student_last_nn NOT NULL
43 / 90
2. NOT NULL Constraints
! NOT NULL can also be set in the CREATE
statement:
CREATE TABLE employee
(fname VARCHAR2(8),
ssn VARCHAR2(9) NOT NULL
);
Desc employee
44 / 90
3. DEFAULT Constraints
! Specifies that a particular column has a default value
that the DBMS automatically inserts for every table
row.
! Ex:
s_state CHAR(2) DEFAULT ‘FL’
The DBMS will insert the default value only if the user inserts a NULL value into
the s_state column.
45 / 90
4. UNIQUE Constraints
! specifies that a column must have a unique value for
every table row.
! Ex:
CONSTRAINT term_term_desc_uk UNIQUE (term_desc)
46 / 90
Creating DB tables using SQL*Plus
! Start the application: SQL*Plus
! Log onto the Oracle 10g DB: username and password
! Type SQL commands at SQL prompt
! End each command with semicolon ;
! Press Enter to submit commands
47 / 90
Creating DB tables using SQL*Plus
! The SQL*Plus interpreter checks the command for
syntax errors
◦ If the command is error free ! the SQL interpreter
submits the command to the DB.
48 / 90
Creating DB tables using SQL*Plus
! When creating DB tables that contain foreign key
references to other tables, you must first create the
table in which the foreign key is a primary key.
◦ Ex: to create the STUDENT table, you must first create the
FACULTY table, as the F_ID column in the STUDENT
table is a foreign key that reference the F_ID column in the
FACULTY table.
49 / 90
SQL Command to Create the
LOCATION Table
50 / 90
Debugging SQL Commands
! Syntax error ! SQL*Plus interpreter displays
errors information that includes:
◦ Line number within the command that caused the error
◦ Position of the error within the line (Asterisk *)
◦ Causes of SQL command errors are not always readily
apparent
51 / 90
Debugging SQL Commands
◦ Error code and description of the error
● Has 3-char prefix (e.g ORA: indicates the error was generated by
the DBMS) which indicates which Oracle utility generates the
error.
● 5-digit code (00907 indicated missing closing parenthesis)
52 / 90
Debugging SQL Commands
53 / 90
Debugging SQL Commands
! A last resort debugging technique is to create the
table multiple times, each time adding a column
declaration repeating the process until you find the
declaration causing the error.
54 / 90
Table Deleting
! DROP TABLE tablename
55 / 90
Exiting SQL*PLUS
1. Type EXIT
2. File ! Exit
3. Close button
56 / 90
Creating a table with Foreign Key
Constraint
57 / 90
Viewing Information about Tables
! DESCRIBE tablename
58 / 90
Viewing Information about Tables
59 / 90
Viewing Information about Tables
! To view information about constraint other than the
NOT NULL constraint use Oracle 10g data
dictionary views.
60 / 90
Viewing Information about Tables
! The Oracle 10g DBMS automatically updates the data
dictionary tables as users create, update and delete DB
objects.
61 / 90
Viewing Information about Tables
! A view can serve to hide some table columns in
which the user has no interest or doesn’t have
required privileges to view.
62 / 90
Viewing Information about Tables
! Categories of data dictionary views:
63 / 90
Viewing Information about Tables
! General command to retrieve information from a
data dictionary view:
! SELECT view_columnname1, view_columnname2, …
FROM prefix_object;
◦ Prefix specifies the view category, and can have the value
USER, ALL, or DBA.
64 / 90
Viewing Information about Tables
! Example: the following command retrieves the names
of all of a user’s DB tables by retrieving the
TABLE_NAME column from the USER_TABLE
view:
! SELECT table_name
FROM user_tables;
65 / 90
Viewing Information about Tables
! Similarly, the following command uses the ALL prefix
and retrieve the names of all DB tables that a user
has either created or has been given object privileges
to manipulate:
! SELECT table_name
FROM all_tables;
66 / 90
Viewing Information about Tables
67 / 90
Viewing Information about Tables
! You can retrieve information about a variety of DB
objects using different data dictionary views.
Example: to retrieve the names of all of your DB
objects is:
SELECT object_name
FROM user_objects;
68 / 90
Viewing Information about Tables
! Use DESCRIBE to list the names of the columns in a
specific DB view.
69 / 90
Viewing Information about Tables
! Then you query the USER_CONSTRAINTS view to
determine the constraints that exists in your DB
tables.
70 / 90
To List the FACULTY table constraints:
71 / 90
Modifying and Deleting DB Tables
! Plan tables carefully to avoid having to change structure of
database tables later, which may lead to errors in the
retrieving applications.
72 / 90
Modifying and Deleting DB Tables
! Unrestricted action
◦ Some specifications of tables can always be modified
! Restricted action
◦ Table specifications that can be modified only in certain
situations
73 / 90
Unrestricted Actions when Modifying
Database Tables
74 / 90
Restricted Actions when Modifying
Database Tables
75 / 90
Deleting Tables
! Delete table with caution, because there is always a
chance that some DB application is still using it.
! Syntax
◦ DROP TABLE tablename;
76 / 90
Deleting Tables
! To drop a table that contains columns that other tables reference as
foreign keys, you have two options:
(Ex: you can’t drop LOCATION because the FACULTY table reference the
LOC_ID column as a foreign key)
1. Drop all the tables that contain the foreign key references.
● Ex: to delete the LOCATION table, you could first delete the FACULTY table, and
then you could delete the LOCATION table.
2. Delete all of the foreign key constraints that reference the table. To delete the
foreign key constraints that reference a table use:
77 / 90
Deleting Tables
! Trying to drop without cascade will lead to an error:
78 / 90
Renaming Tables
! Syntax
◦ RENAME old_tablename TO new_tablename;
! Ex:
◦ RENAME faculty TO nw_faculty;
79 / 90
Renaming Tables
! When renaming a table, objects that referenced the
old table, such as views, and stored procedures and
functions become invalid.
80 / 90
Adding Columns to Existing Tables
! Add new column to table
ALTER TABLE tablename
ADD(columnname data_declaration constraints);
Ex:
ALTER TABLE faculty
ADD (start_date DATE);
81 / 90
Modifying Existing Column Data
Definitions
! You can modify the data type of a column only if
existing data values in the column rows are
compatible with the new data type.
82 / 90
Modifying Existing Column Data
Definitions
! To change the maximum size parameter of a column:
83 / 90
Modifying Existing Column Data
Definitions
! Syntax
ALTER TABLE tablename
MODIFY(columnname new_data_declaration);
! EX:
ALTER TABLE faculty
MODIFY (f_rank CHAR(4));
84 / 90
Deleting a Column
! Syntax
ALTER TABLE tablename
DROP COLUMN columnname;
85 / 90
Renaming a Column
! Syntax
ALTER TABLE tablename
RENAME COLUMN old_columnname TO
new_columnname;
! Ex:
! ALTER TABLE faculty
RENAME COLUMN f_rank TO faculty_rank;
86 / 90
Adding and Deleting Constraints
! Adding new constraints is a restricted action.
! Syntax
ALTER TABLE tablename
ADD CONSTRAINT constraint_name
constraint_definition;
! Ex:
ALTER TABLE faculty
ADD CONSTRAINT faculty_f_pin_uk UNIQUE(f_pin);
87 / 90
Adding and Deleting Constraints
! Deleting constraints is an unrestricted action
! Syntax
ALTER TABLE tablename
DROP CONSTRAINT constraint_name;
! Ex:
ALTER TABLE faculty
DROP CONSTRAINT faculty_f_pin_uk;
88 / 90
Enabling and Disabling Constraints
! Useful during development, you may need to disable
it and then enable it when the project is completed.
89 / 90
Enabling and Disabling Constraints
! To disable existing constraint syntax:
ALTER TABLE tablename
DISABLE CONSTRAINT constraint_name;
! Ex:
ALTER TABLE faculty
DISABLE CONSTRAINT faculty_loc_id_fk;
! Ex:
ALTER TABLE faculty
ENABLE CONSTRAINT faculty_loc_id_fk;
90 / 90