Sei sulla pagina 1di 77

Chapters (4, 5) SQL-99 Schema Definition, Constraints,

Queries, and Views

Week #4

DAT604 Database Design & Impl


SQL Introduction
• Originally called SEQUEL for System R
• SQL-86 (SQL1), SQL-92 (SQL2), SQL-99 (SQL3)
• SQL is considered to be the language standard for DBMS
• Conversion between different systems is easy
• No need to change application program
• Provides higher language declarative interface
• DDL, DML and DCL

DAT604 Database Design and Impl 2


Structured Query Language

• SQL statements :
• Data retrieval: SELECT
• Data Manipulation Language (DML): INSERT,
UPDATE, and DELETE.
• Data Definition Language (DDL): CREATE, ALTER,
DROP, RENAME, and TRUNCATE.
• Transaction control: COMMIT, SAVEPOINT, and
ROLLBACK.
• Data Control Language (DCL): GRANT and REVOKE.

DAT604 Database Design and Impl 3


Names !!
NAMING CONVENTIONS

• Table and Attribute name, ( 1 to 30 characters long)


• Names are not case sensitive
• Special characters ( $, underscore and # ) are allowed
• Spaces and hyphens are not allowed in a relation or
attribute name
• The table or attribute name must begin with a letter

DAT604 Database Design and Impl 4


DATA TYPES
VARCHAR2( # ) NAME
• Character data type to store variable length alphanumeric
data in a column
• Store variable length character data in an attribute ( 1 to
4000 )
• If the data are smaller than the specified size, trailing spaces
are not added to the value
• If a value longer than the specified size is entered, an error
is generated
• The longer values are not truncated

DAT604 Database Design and Impl 5


DATA TYPES
CHAR (#) SSN, PHONE#
• Character data type to store fixed length alphanumeric
data in a column
• Data type to store fixed length character data in an
attribute (1 to 2000)
• Uses storage more efficiently
• Processes data faster
• If the value smaller than the specified size is entered
trailing spaces are added to make its length equal to the
specified length
• An error occurs for a longer value than the specified size
DAT604 Database Design and Impl 6
DATA TYPES
NUMBER (p, s)
• Negative, positive, integer, fixed decimal, and floating
point numbers
• Precision is the total number significant digits in the
number (Both right and left hand side of the decimal
excluding decimal)
• Scale is the total number of digits to the right of the
decimal point
• Its precision (1 to 38) and scale can be specified
DATE (DD-MON-YY)
• Storing date and time values ( Jan 1, 4712 B.C. to Dec.
31, 9999 A.D. )

DAT604 Database Design and Impl 7


CONTRAINTS
• Integrity Constraints defines
• PRIMARY KEY
• FOREIGN KEY with the table and primary key it
references
• Value (Key) Constraints defines
• NOT NULL, UNIQUE and CHECK constraints
• Oracle identifies constraints with an internal name
(SYS_Cn format)
• User created name
<table name>_<attribute name>_<constraint type>

DAT604 Database Design and Impl 8


CONTRAINTS

CONSTRAINT dept_Deptid_pk PRIMARY KEY (Deptid),

CONSTRAINT dependent_emp_dep_pk PRIMARY KEY


(EmployeeId, DependentName),

CONSTRAINT dept_Emp_fk FOREIGN KEY (Dnum)


REFERENCES department (DNumber),

DAT604 Database Design and Impl 9


CONTRAINTS

Name VARCHAR2(15) NOT NULL,

DeptName VARCHAR2(15) CONSTRAINT dept_dname_uk


UNIQUE;

DAT604 Database Design and Impl 10


ORACLE TABLES
CREATE TABLE [schema.] tablename

(attribute1 datatype [CONSTRAINT constraint_name]


constraint_type…,

(attribute2 datatype [ CONSTRAINT constraint_name ]


constraint_type ,

[ CONSTRAINT constraint_name ] constraint_type ( attribute,
… ), );

DAT604 Database Design and Impl 11


ORACLE TABLES

CREATE TABLE TEST


(StudentId CHAR(5) PRIMARY KEY,
Last VARCHAR2 (15) NOT NULL,
First VARCHAR2 (15) NOT NULL,
BirthDate DATE,
MajorId NUMBER (3),
Phone CHAR (10));

DAT604 Database Design and Impl 12


SQL Query
SYNTAX

SELECT List of attributes


FROM Relationname
WHERE Condition(s);

• Column names (both tables) are separated by commas


• Condition includes attributes and constants
• Conditions can be added with AND, OR, NOT operators

DAT604 Database Design and Impl 13


Retrieving Data
• Syntax:

SELECT columnlist (In any order)


FROM tablename;

SELECT *
FROM tablename;

SELECT DISTINCT columnlist


FROM tablename;

DAT604 Database Design and Impl 14


RESTRICTING DATA (Continued…)
QUERY List last name of all the male employees who draw more than 30K salary.

SELECT Lname
FROM EMPLOYEE
WHERE Salary > 30000 AND Sex = ‘ M’;

FNAME LNAME SSN SALARY SEX

John Smith 123456789 30000 M

Franklin Wong 333445555 40000 M

Alicia Zelaya 999887777 25000 F

Jennifer Wallace 987654321 43000 F

Ramesh Narayan 666888444 38000 M

DAT604 Database Design and Impl 15


RESTRICTING DATA (Continued…)
QUERY List last name of all the employees who draw salary from 35K to 40K.

SELECT Lname
FROM EMPLOYEE
WHERE Salary BETWEEN 35000 AND 40000;

FNAME LNAME SSN SALARY SEX

John Smith 123456789 30000 M

Franklin Wong 333445555 40000 M

Alicia Zelaya 999887777 25000 F

Jennifer Wallace 987654321 43000 F

Ramesh Narayan 666888444 38000 M

DAT604 Database Design and Impl 16


RESTRICTING DATA (Continued…)
QUERY List last name of all the employees who draw salary from 35K to 40K.

SELECT Lname
FROM EMPLOYEE
WHERE Salary >= 35000 AND Salary <= 40000;

FNAME LNAME SSN SALARY SEX

John Smith 123456789 30000 M

Franklin Wong 333445555 40000 M

Alicia Zelaya 999887777 25000 F

Jennifer Wallace 987654321 43000 F

Ramesh Narayan 666888444 38000 M

DAT604 Database Design and Impl 17


RESTRICTING DATA (Continued…)
QUERY List last name of all the employees who draw salary from 35K to 40K.

SELECT Lname
FROM EMPLOYEE
WHERE Salary >= 35000 OR Salary <= 40000;
OPTION #2
FNAME LNAME SSN SALARY SEX

John Smith 123456789 30000 M

Franklin Wong 333445555 40000 M

Alicia Zelaya 999887777 25000 F

Jennifer Wallace 987654321 43000 F

Ramesh Narayan 666888444 38000 M

DAT604 Database Design and Impl 18


RESTRICTING DATA (Continued…)
QUERY List last name of all the employees who draw salary 35K, 25K and 40K.

SELECT Lname
FROM EMPLOYEE
WHERE Salary IN ( 35000, 40000, 25000 ) ;

FNAME LNAME SSN SALARY SEX

John Smith 123456789 30000 M

Franklin Wong 333445555 40000 M

Alicia Zelaya 999887777 25000 F

Jennifer Wallace 987654321 43000 F

Ramesh Narayan 666888444 38000 M

DAT604 Database Design and Impl 19


EQUIJOIN
SYNTAX

SELECT List_of_Attributes
FROM Relation_names
WHERE join condition(s);

• Column names (both tables) are separated by commas


• Table names separated by commas
• Joining condition includes attributes from each table
• Conditions can be added with AND, OR, NOT operators

DAT604 Database Design and Impl 20


JOIN Operations
JOIN

• Joining condition is a must to combines tuples from two


tables
• For joining n tables we need n-1 join conditions
• Join condition on Primary key and Foreign Key

DAT604 Database Design and Impl 21


SQL JOIN Operation (Continued . . .)
Query: List last name of the employees who manage departments. Also list the name
of the corresponding department.

DNAME DNUMBER MGRSSN MGRSTARTDATE


Research 5 333445555 1988-05-22

Administration 4 987654321 1995-01-01

Headquarters 1 888665555 1981-06-19

FNAME LNAME SSN SALARY SUPERSSN SEX


John Smith 123456789 30000 333445555 M

Franklin Wong 333445555 40000 888665555 M

Alicia Zelaya 999887777 25000 987654321 F

Jennifer Wallace 987654321 43000 888665555 F

Ramesh Narayan 666888444 38000 333445555 M

DAT604 Database Design and Impl 22


Query: List last name of the employees who manage departments. Also
list the name of the corresponding department.

DEPARTMENT

DNAME DNUMBER MGRSSN MGRSTARTDATE

EMPLOYEE
FNAME LNAME SSN SALARY SUPERSSN SEX

SELECT DEPARTMENT.Dname, EMPLOYEE.Lname


FROM DEPARTMENT, EMPLOYEE
WHERE DEPARTMENT.MGRSSN = EMPLOYEE.SSN;

DAT604 Database Design and Impl 23


More on JOINS !!!
ADDITIONAL CONDITIONS

• More than one condition using logical operator (AND, OR)

NON-EQUIJOIN

• The join condition other than EQUAL

DAT604 Database Design and Impl 24


ALIASING
Column Alias: SELECT Columnname [AS] alias . . .
• Changes the attribute name to a different column
heading
• Keyword used is AS
SELECT Fname AS “Name”, Lname AS
“Family_Name”
FROM EMPLOYEE ;

DAT604 Database Design and Impl 25


ALIASING
Table Alias:
• Appear in the FROM clause of the SELECT query
• Alias names can be used in SELECT clause
• It can be 1 to 30 character
SELECT e.Lname, s.Dname
FROM EMPLOYEE e, DEPARTMENT s
WHERE e.SSN = s.MGRSSN;

DAT604 Database Design and Impl 26


TABLE INFORMATION
Oracle keeps track of all the tables created by users using its
own system database (SQL statements)
• To view users tables
SELECT table_name FROM user_tables;
or
SELECT * FROM user_tables;
• To view the table’s structure
DESCRIBE table_name;
• To view all the tuples in a relation
SELECT * FROM table_name;

DAT604 Database Design and Impl 27


TABLE INFORMATION
• To view the constraint information

SELECT constraint_name, column_name


FROM user_cons_columns where TABLE_NAME =
‘EMPLOYEE’;

SELECT constraint_name, constraint_Type


FROM user_constraints where TABLE_NAME =
‘DEPT’;

DAT604 Database Design and Impl 28


Altering an Existing Table

Modifications allowed with restrictions :


• Adding a constraint (Foreign and Primary Key)
• Decrease an attribute’s size or change its data type

Modifications not recommended :


• Changing an attribute’s name or
• Removing an attribute.

DAT604 Database Design and Impl 29


Altering Table Statements
General Syntax:
ALTER TABLE TableName
ADD/MODIFY/DROP attribute DataType;

ALTER TABLE TableName


ADD/DROP CONSTRAINT ConstraintName
ConstraintType
(column, …) [REFERENCES TableName (ColumnName)];

DAT604 Database Design and Impl 30


Altering Table Statements
For example
ALTER TABLE student ADD SocSecNum CHAR(9);

ALTER TABLE student MODIFY Zip VARCHAR2(10);

ALTER TABLE student ADD CONSTRAINT student_facultyid_fk


FOREIGN KEY (FacultyId) REFERENCES faculty (FacultyId);

DAT604 Database Design and Impl 31


Adding a New Tuple
• DML Statement:
INSERT INTO tablename [(column1, column2, column3,…)]
VALUES (value1, value2, value3,…);

• For example:
INSERT INTO dept (DeptId, Deptname, Location,
EmployeeId)
VALUES (10, ‘Finance’, ’Charlotte’,123);
OR
INSERT INTO dept
VALUES (10, ‘Finance’, ’Charlotte’,123);
DAT604 Database Design and Impl 32
Null Values
• Explicit Method:
INSERT INTO dept (DeptId, DeptName, Location,
EmployeeId)
VALUES (60, ‘Personnel’, ‘Chicago’, NULL);

• Implicit Method:
INSERT INTO dept (DeptId, DeptNAme)
VALUES (50, ‘Production’);

DAT604 Database Design and Impl 33


Updating Existing Tuples
• The DML statement UPDATE is used to modify existing
data.
• Only one table can be updated at a time
General Syntax:
UPDATE tablename
SET column1 = newvalue [, column2 = newvalue,…]
[ WHERE condition ];
UPDATE student
SET MajorId = 600
WHERE StudentId = ‘00103’;

DAT604 Database Design and Impl 34


Deleting Existing Tuples
• General Syntax:

DELETE [FROM] tablename [WHERE condition];


• Use primary key in the condition

• For example:

DELETE FROM dept WHERE DeptId = 60;

DAT604 Database Design and Impl 35


Constraints: Enable/Disable
• Syntax:
ALTER TABLE tablename
DISABLE CONSTRAINT constraintname [CASCADE];

ALTER TABLE tablename


ENABLE CONSTRAINT constraintname;

ALTER TABLE student


DISABLE CONSTRAINT student_studentid_pk CASCADE;

DAT604 Database Design and Impl 36


SQL*PLUS Environment
• SQL*Plus provides the user with the SQL> prompt to write
queries or commands.
• Features of SQL*PLUS:
• Accepts ad hoc entry of statements at the prompt
• Accepts SQL statements from files
• Provides a line editor for modifying SQL queries
• Provides environment, editor, format, execution,
interaction, and file commands
• Formats query results and displays reports on the screen
• Controls environmental settings
• Accesses local and remote databases

DAT604 Database Design and Impl 37


Logging in To SQL*PLUS
• http://address:5560/isqlplus/

• A Log On window will pop up.


• Username
• Password
• Connect Identifier: XXXX

DAT604 Database Design and Impl 38


Logging in To SQL*PLUS

WYNE

DAT604 Database Design and Impl 39


Logging in To SQL*PLUS

DAT604 Database Design and Impl 40


Logging in To iSQL*PLUS

• Enter the iSQL*Plus URL in your web browser's Location


or Address field. The iSQL*Plus URL looks like:
• http://machine_name.domain:port/isqlplus
• http://127.0.0.1:5560/isqlplus/
http://localhost:5560/isqlplus/
• iSQL*Plus uses HTTP port 5560 by default.
• If iSQL*Plus is not available on port 5560, read the
$ORACLE_HOME/install/portlist.ini file on the computer
running the iSQL*Plus Application Server to find the port
on which iSQL*Plus is running.

DAT604 Database Design and Impl 41


• This is the LOGIN screen
DAT604 Database Design and Impl 42
• The screen after you login.
• You can write your SQL queries under “enter statements” and when
you hit “execute” button, it will execute the query.
• Other buttons are self explanatory.
DAT604 Database Design and Impl 43
Group Functions
Group (Aggregate) Functions:
 Perform operation on a group of rows
 Return single result

SUM (column) and AVG(column) Ignores NULL values


MAX(column |expression) Ignores NULL values
MIN(column |expression) Ignores NULL values
COUNT(*) Includes NULL
COUNT(column |expression) Ignores NULL

DAT604 Database Design and Impl 44


GROUPING DATA

SELECT column, groupfunction(column)


FROM tablename
[WHERE condition(s)]
[GROUP BY column | expression]
[ORDER BY column | expression [ASC/DESC]]

DAT604 Database Design and Impl 45


GROUPING DATA
• HAVING Clause
• Restricts groups
• WHERE
• Restricts rows

SELECT Building, COUNT(*) ROOMS


FROM location
WHERE UPPER(Building) <> ‘KENNEDY’
GROUP BY Building
HAVING COUNT(*) >= 4;

DAT604 Database Design and Impl 46


SQL OUTER JOIN Operation
STUDENT LAST FIRST STAR FACULTYID MAJOTID
Diaz Jose WN00 123 100
Tyler Mickey SPOO 555 500
Patel Rajesh WN00 111 400
Rickles Deborah FL00 555 500
Lee Brian WN00 345 600
Khan Amir WN00 222 200
FACULTY NAME FACULTYID ROOMID PHO DEPTID
Jones 111 11 525 1
Williams 222 20 533 2
Mobley 123 11 529 1
Vajpayee 235 12 577 2
Sen 345 12 579 3
Rivera 444 21 544 4
Changs 555 17 587 5
Collins 333 17 599 3
DAT604 Database Design and Impl 47
SQL OUTER JOIN Operation

SELECT table1.columnname, table2.columnname


FROM table1, table2
WHERE
table1.columnname (+) = table2.columnname;
OR
WHERE
table1.columnname = table2.columnname (+);

DAT604 Database Design and Impl 48


SQL OUTER JOIN Operation
QUERY: List names of all the students and their
advisors.

STUDENT LAST FIRST STAR FACULTYID


MAJOTID

FACULTY
NAME FACULTYID ROOMID PHO
DEPTID

SELECT Student.last, student.first, faculty.name


FROM Student, Faculty
WHERE Student.FacultyId = Faculty.FacultyID (+);

DAT604 Database Design and Impl 49


Multiple Tables: Outer Joins
STUDENT LAST FIRST STAR FACULTYID MAJOTID
Diaz Jose WN00 123 100
Tyler Mickey SPOO 555 500
Patel Rajesh WN00 111 400
Rickles Deborah FL00 555 500
Lee Brian WN00 345 600
Khan Amir WN00 222 200
FACULTY NAME FACULTYID ROOMID PHO DEPTID
Jones 111 11 525 1
Williams 222 20 533 2
Mobley 123 11 529 1
Vajpayee 235 12 577 2
Sen 345 12 579 3
Rivera 444 21 544 4
Changs 555 17 587 5
Collins 333 17 599 3
DAT604 Database Design and Impl 50
Multiple Tables: Outer Joins
SELECT Student.last, Student.first, Faculty.name
FROM Student, Faculty
WHERE Student.FacultyId = Faculty.FacultyID (+);

LAST FIRST NAME


Diaz Jose Mobley
Tyler Mickey Changs
Patel Rajesh Jones
Rickles Deborah Changs
Lee Brian Sen
Khan Amir Williams
DAT604 Database Design and Impl 51
Multiple Tables: Outer Joins
QUERY: List names of all the faculty members and the
students they are advising.

STUDENT
LAST FIRST STAR FACULTYID
MAJOTID
FACULTY
NAME FACULTYID ROOMID PHO
DEPTID
SELECT Student.last, Student.first, Faculty.name
FROM Student, Faculty
WHERE Student.FacultyId (+) = Faculty.FacultyID ;

DAT604 Database Design and Impl 52


Multiple Tables: Outer Joins
LAST FIRST STAR FACULTYID MAJOTID
STUDENT Diaz Jose WN00 123 100
Tyler Mickey SPOO 555 500
Patel Rajesh WN00 111 400
Rickles Deborah FL00 555 500
Lee Brian WN00 345 600
Khan Amir WN00 222 200
FACULTY NAME FACULTYID ROOMID PHO DEPTID
Jones 111 11 525 1
Williams 222 20 533 2
Mobley 123 11 529 1
Vajpayee 235 12 577 2
Sen 345 12 579 3
Rivera 444 21 544 4
Changs 555 17 587 5
Collins 333 17 599 3
DAT604 Database Design and Impl 53
Multiple Tables: Outer Joins
SELECT Student.last, Student.first, Faculty.name
FROM Student, Faculty
WHERE Student.FacultyId (+) = Faculty.FacultyID ;
LAST FIRST NAME
Patel Rajesh Jones
Diaz Jose Mobley
Khan Amir Williams
Vajpayee
Collins
Lee Brian Sen
Rivera
Tyler Mickey Changs
Rickles Deborah Changs
DAT604 Database Design and Impl 54
SET OPERATORS
• All set operation are implemented
• Only on Union Compatible relations
• Same degree of relations
• Same domain of attributes
• Operations are performed on results from two
independent queries
• The output from both queries must return the same
number of columns
• Respective columns must have the same domain

DAT604 Database Design and Impl 55


SET OPERATORS
General syntax:

SELECT Query1
Set Operator
SELECT Query2

DAT604 Database Design and Impl 56


SET OPERATORS
INTERSECT:
• Works on output from two separate queries
• Selects common tuples in outputs from two separate
queries

MINUS:
• Tuples from the first query result not present in the
second query result
• Sequence of the two queries is important

DAT604 Database Design and Impl 57


SET OPERATORS: UNION
• Takes output from two queries and return all tuples from
both results
• No duplication of tuples in result
• If union is performed on two large tables
• Use WHERE clause to filter tuples

DAT604 Database Design and Impl 58


SET OPERATORS: UNION
STUDENT LAST FIRST STAR FACULTYID MAJOTID
Diaz Jose WN00 123 100
Tyler Mickey SPOO 555 500
Patel Rajesh WN00 111 400
Rickles Deborah FL00 555 500
Lee Brian WN00 345 600
Khan Amir WN00 222 200
FACULTY NAME FACULTYID ROOMID PHO DEPTID
Jones 111 11 525 1
Williams 222 20 533 2
Mobley 123 11 529 1
Vajpayee 235 12 577 2
Sen 345 12 579 3
Rivera 444 21 544 4
Changs 555 17 587 5
Collins 333 17 599 3
DAT604 Database Design and Impl 59
SET OPERATORS: UNION
SELECT Last
FROM STUDENT
[WHERE condition]
UNION
SELECT Name
FROM FACULTY
[WHERE condition]

DAT604 Database Design and Impl 60


SET OPERATORS: UNION ALL
• Similar to the UNION operation
• Displays duplicate tuples as well
• The number of rows in the resulting relation will be
• Sum of the rows in the two resulting relations

DAT604 Database Design and Impl 61


NESTED QUERIES (SUB-QUERY)
• A subquery is usually a SELECT query within one of
the clauses in another SELECT query
• Some queries require that existing values in the
database be fetched and then used in a comparison
• Sub query must be enclosed within a pair of
parenthesis
• Sub-query used on the right hand side of the
condition
• Inner most query is executed first

• Single row and Multiple Row sub-query

DAT604 Database Design and Impl 62


NESTED QUERIES (SUB-QUERY)
• General syntax:

SELECT columnlist
FROM tablename
WHERE columnname OPERATOR
( SELECT columnlist
FROM tablename
WHERE condition);

DAT604 Database Design and Impl 63


Single Row Sub-Query
• Returns only one row of data
• If no row is returned by the subquery the value is NULL
• If more than one row is returned an error occurs
• Operators used can be =, < > (or !=), >, <, =<, <=

SELECT columnlist
FROM tablename
WHERE columnname OPERATOR
( SELECT columnlist
FROM tablename
WHERE condition);

DAT604 Database Design and Impl 64


Single Row Sub-Query
QUERY:
List first and last
names of all the
employees who
make more than
John Smith.

DAT604 Database Design and Impl 65


Single Row Sub-Query
QUERY:
List first and last names of all the employees who make
more than John Smith.
SELECT Fname, Lname
FROM Employee
WHERE Salary >
( SELECT Salary
FROM EMPLOYEE
WHERE Fname = ‘John’ AND
Lname = ‘Smith’);
DAT604 Database Design and Impl 66
Multiple Row Sub-Query
• The query return more than one rows
• OPERATORs used are:
• IN (Equal to any of the values in the list)
• ALL (Compare the given value to every value
returned by sub query)
• ANY (Compare the given value to each value
returned by the sub query)
• ANY and ALL OPERATORS can be used in
combination with <, =, >

DAT604 Database Design and Impl 67


List the names of employees whose salary is greater that the
salary of all the employees in department 5

SELECT LNAME, FNAME


FROM EMPLOYEE
WHERE SALARY > ALL
(SELECT SALARY
FROM EMPLOYEE
WHERE DNO = 5)

DAT604 Database Design and Impl 68


Retrieve the names of employees who have no dependents

SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE NOT EXISTS
(SELECT *
FROM DEPENDENT
WHERE SSN = ESSN)

DAT604 Database Design and Impl 69


Retrieve the names of managers who have at least one
dependent

SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE EXISTS
(SELECT *
FROM DEPENDENT
WHERE SSN = ESSN)

DAT604 Database Design and Impl 70


VIEWS
• A view is an Oracle object
• A logical view of data from a relation or relations
• In case of multiple relations user is free from
• Using join operation and join condition
• Restrict users to view a few attributes from the relation
• User of a view has no information about the actual relations
• Same data can be viewed differently with different views

71
DAT604 Database Design and Impl
VIEWS
• Simple View
• Based on one relation
• Does not contain group function or group data
• Data manipulation is always possible through it
• Complex View
• Based on one or more relations
• May contain group function and/or group data
• Data manipulation is not always possible through it

72
DAT604 Database Design and Impl
Creating a View
• Primary key constraint is not transferred
• NOT NULL the only constraint that gets transferred
• Populate new table with selected rows
• Sub query cannot use ORDER BY clause

General Syntax:
CREATE TABLE/VIEW tablename
AS
SELECT-FROM-WHERE;

DAT604 Database Design and Impl 73


Creating a View
CREATE TABLE DEPT4

AS
SELECT EMPLOYEEID, LNAME, FNAME
FROM EMPLOYEE
WHERE DNO = 4;

CRAETE VIEW TEST (First, Last, Department)

AS
SELECT Fname, Lname, DNO
FROM Employee
WHERE Dno= 4;

DAT604 Database Design and Impl 74


Creating a View
CREATE or REPLACE TABLE DEPT4

AS
SELECT EMPLOYEEID, LNAME, FNAME
FROM EMPLOYEE
WHERE DNO = 5
WITH CHECK OPTION;

DAT604 Database Design and Impl 75


Rules for Views

Rules for data manipulation on a view;

• No data manipulation on derived attributes


• No insertion of new tuples in view
• If base table contains attribute with NOT NULL
constraint
• Even if the attribute is not selected by the view
• If derived attributes exist in the view

DAT604 Database Design and Impl 76


Manipulating Views
• A user can list names of views
SELECT view_name from user_views

• A view can be removed without affecting the data in the


base relation or relations
DROP VIEW/TABLE view_name;

• When the base relations are altered the view needs to be


updates
ALTER VIEW view_name COMPILE;
• It can also be used to add constraints by using
MODIFY/DROP CONSTRAINT clause

DAT604 Database Design and Impl 77

Potrebbero piacerti anche