Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

CIS340:Database Systems

Lab#3
I.Arwa Najdi
Department of Computer Science and Information Technology
Faculty of Computers and Information Technology
University of Tabuk
Tabuk, Saudi Arabia

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Outlines:
Sorting records by Using the ORDER BY Clause
Displaying Table Structure
DEFAULT Option
Constraints
Modifying Tables
Delete tables
Update record
Delete record
Script file

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Lab 3 part 1
Sorting by Using the ORDER BY Clause

Sort retrieved row records with the ORDER BY


clause:
ASC: ascending order, default
DESC: descending order
The ORDER BY clause comes last in the SELECT
statement:

SELECT columns_name
FROM table_name
ORDER BY columne_name;

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Example: Using ORDER BY

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Example: Using ORDER BY

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Displaying Table Structure
DESCRIBE
Use DESCRIBE command to display the structure
of a table:

DESCRIBE table_name

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Example
DESCRIBE student

anajdi@ut.edu.sa
CIS340 (Spring 2013)
DEFAULT Option
The DEFAULT constraint is used to insert a default value into a
column.
The default value will be added to all new records, if no other value is
specified.
Specify a default value for a column during create table statement .
The default data type must match the column data type.
CREATE TABLE hire_dates
(id NUMBER(8),
hire_date DATE DEFAULT SYSDATE);
The following SQL creates a DEFAULT constraint on the "City" column when the
"Persons" table is created:
CREATE TABLE Persons
(P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes')

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Constraints
Data types are a way to limit the kind of data that can be
stored in a table.
For many applications, however, the constraint is very
important. For example, a column containing a product price
should probably only accept positive values. But there is no
data type that accepts only positive numbers.
Another issue is that you might want to constrain column
data. For example, in a table containing product information,
there should only be one row for each product number.
So , SQL allows you to define constraints on columns and
tables.
Constraints give you as much control over the data in your
tables as you wish. If a user attempts to store data in a
column that would violate a constraint, an error is raised.

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Constraints
Constraints prevent the deletion of a table if there are
dependencies.
The five types of integrity constraint are :
A NOT NULL constraint prohibits a database value from being
null.
A unique constraint prohibits multiple rows from having the
same value in the same column or combination of columns but
allows some values to be null.
A primary key constraint combines a NOT NULL constraint and a
unique constraint in a single declaration. That is, it prohibits
multiple rows from having the same value in the same column or
combination of columns and prohibits values from being null.
A foreign key constraint requires values in one table to match
values in another table.
A check constraint requires a value in the database to comply
with a specified condition.

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Constraints

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Primary key Constraint

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Foreign key Constraint

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Check Constraint

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Unique Constraint

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Not Null Constraint

anajdi@ut.edu.sa
CIS340 (Spring 2013)
How to Define Constraints?

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept
NULL values.
The following SQL enforces the "P_Id" column and the
"LastName" column to not accept NULL values:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL UNIQUE Constraint (Create Table)
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for
uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table
The following SQL creates a UNIQUE constraint on the "P_Id" column when
the "Persons" table is created:

CREATE TABLE Persons


(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record


in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can
have only ONE primary key

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL PRIMARY KEY Constraint on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "P_Id"
column when the "Persons" table is created:

CREATE TABLE Persons


(
P_Id int PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Let's illustrate the foreign key with an example. Look at the following two
tables:
PK The "Persons" table:

The "Orders" table: FK

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL FOREIGN KEY Constraint
Example (Con.)
Note that the "P_Id" column in the "Orders" table points
to the "P_Id" column in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY
KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY
in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions
that would destroy links between tables.
The FOREIGN KEY constraint also prevents that invalid
data form being inserted into the foreign key column,
because it has to be one of the values contained in the
table it points to.

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL FOREIGN KEY Constraint on CREATE TABLE
Example (Con.)
The following SQL creates a FOREIGN KEY on the "P_Id"
column when the "Orders" table is created:

:a÷gE→ss•
CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int REFERENCES Persons(P_Id)
)

µ
anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed
in a column.
If you define a CHECK constraint on a single column it allows only certain
values for this column.

SQL CHECK Constraint on CREATE TABLE


The following SQL creates a CHECK constraint on the "P_Id" column
when the "Persons" table is created. The CHECK constraint specifies
that the column "P_Id" must only include integers greater than 0.
CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Books table
Authors Table
Books Table
End of Lab 3 part 1
Lab 3 part 2
SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data
Definition Language (DDL).
The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also defines indexes
(keys), specifies links between tables. The most important DDL statements in SQL are:
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index .

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Modify table (Alter table command)
Delete table (Drop table command )

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Modifying Tables
You can modify tables using the SQL ALTER TABLE statement
The ALTER TABLE statement is used to:
rename an existing table
add, modify, or drop a column from an existing table.
Manage constraints
Renaming a table
ALTER TABLE table_name
RENAME TO new_table_name;

Adding column(s) to a table (Syntax #1)


ALTER TABLE table_name
ADD column_name column-definition;

Adding column(s) to a table (Syntax #2)


ALTER TABLE table_name ADD ( column_1 column-
definition, column_2 column-
definition, ... column_n column_definition );
anajdi@ut.edu.sa
CIS340 (Spring 2013)
Modifying Tables
Modifying column(s) in a table(Syntax #1)

ALTER TABLE table_name


MODIFY column_name column_type;

Modifying column(s) in a table(Syntax #2)


ALTER TABLE table_name MODIFY ( column_1
column_type, column_2
column_type, ... column_n column_type );

Drop column(s) in a table

ALTER TABLE table_name


DROP COLUMN column_name;

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Removing Tables
You can discard a table if you no longer find it useful. The DROP TABLE
statement removes the definition of the table from the database.
Deleting all of the records in a table is different from DROP TABLE. After
deleting all the records, the column and constraint information still
remains. But DROP TABLE results in the removal of the table definition
along with the rows.

DROP TABLE table_name;

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Updates data in a database (UPDATE command)
Deletes data from a database (DELETE command)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL UPDATE Statement
The UPDATE statement is used to update records in a table.
SQL UPDATE Syntax:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The


WHERE clause specifies which record or records that should
be updated. If you omit the WHERE clause, all records will be
updated!

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL UPDATE Example
The "Persons" table:

Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'

anajdi@ut.edu.sa
CIS340 (Spring 2013)
SQL UPDATE (Con.)
The "Persons" table will now look like this:

SQL UPDATE Warning


Be careful when updating records. If we had omitted the
WHERE clause in the example above, like this:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Updating Two Columns with a Subquery
Update employee 114
that of employee 205.

UPDATE 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;

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Updating Rows Based on Another Table
Use subqueries in UPDATE statements to update rows in a
table based on values from another table:

UPDATE copy_emp
SET department_id = (SELECT department_id
FROM employees
WHERE employee_id = 100)
WHERE job_id = (SELECT job_id
FROM employees
WHERE employee_id = 200);

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Removing a Row from a Table
You can remove existing rows from a table by using the
DELETE statement:
DELETE FROM table_name
WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The


WHERE clause specifies which record or records that should
be deleted. If you omit the WHERE clause, all records will be
deleted!

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Removing a Row from a Table
Specific rows are deleted if you specify the WHERE clause:
DELETE FROM departments
WHERE department_name =
'Finance';

All rows in the table are deleted if you omit the WHERE
clause:
DELETE FROM copy_emp;

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Inserting Row
Inserting Rows with Null Values:
Implicit method: Omit the column from the column list.
INSERT INTO departments (department_id,
department_name )
VALUES (30, 'Purchasing');

Explicit method: Specify the NULL keyword in the VALUES


clause.
INSERT INTO departments
VALUES (100, 'Finance', NULL, NULL);

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Inserting Special Values
The SYSDATE function records the current date and time.
INSERT INTO employees (employee_id,
first_name, last_name,
email, phone_number,
hire_date, job_id, salary,
commission_pct, manager_id,
department_id)
VALUES (113,
'Louis', 'Popp',
'LPOPP', '515.124.4567',
SYSDATE, 'AC_ACCOUNT', 6900,
NULL, 205, 100);

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Copying Rows from Another Table
Write your INSERT statement with a subquery:

INSERT INTO sales_reps(id, name, salary,


commission_pct)
SELECT employee_id, last_name, salary,
commission_pct
FROM employees
WHERE job_id LIKE '%REP%';

Do not use the VALUES clause.


Match the number of columns in the INSERT clause to
those in the subquery.

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Interacting with Script Files
Scripts :are text files which can be developed using a text
editor such as Notepad.
They can reduce the labor intensive activity of typing by
storing them for future reuse.
You find scripts in almost all computer-related activities, and
they are available for most programming languages

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Interacting with Script Files (Con.)
Scripts make the process of application development easier,
because with well developed scripts, errors are reduced, and
reading from a file is faster than one can type
In Oracle 10G XE, you can develop reusable SQL scripts and
save them for future use quite easily

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Interacting with Script Files (Con.)
Opening the SQL Script Editor
Log in to the database

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Interacting with Script Files (Con.)
Now click on the SQL icon

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Interacting with Script Files (Con.)
This window gives you access to all the SQL functionalities in
Oracle XE, SQL Commands, SQL Scripts, and Query Builder as
shown.

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Interacting with Script Files (Con.)
Click on the SQL Scripts icon, which opens up the following window

This screen will list all the scripts that exist in the database, showing the
name with which the script was saved, its owner, the user who updated
it, the last time it was updated, the number of bytes, the results, and
whether it has run previously

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Create script
Click on create to create script, write the script and click save

anajdi@ut.edu.sa
CIS340 (Spring 2013)
Create script (Con.)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
How to run saved script
(1)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
How to run saved script
(2)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
How to run saved script
(3)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
How to run saved script
(4)

anajdi@ut.edu.sa
CIS340 (Spring 2013)
anajdi@ut.edu.sa
CIS340 (Spring 2013)
Lab Exercise
Create table Employees that contain the following attributes:
empID integer
FirstName varchar (30)
LastName varchar(30)
Email varchar(30)
Provided that:
Columns "empID" and "FirstName" cannot include NULL, while
"LastName" can include NULL

Column "empID" must only include integers greater than 10


"empID" is used to uniquely identify each row in our table

anajdi@ut.edu.sa
CIS340 (Spring 2013)
b. Create another table named Employees_Salary has the
following columns and their constraints:

Note: ensure that the Emp_ID column is a foreign key which relates to a Emp_ID column
in Employees table.

You might also like