Chapter 5 Relational Database Management Systems and SQL

92
Chapter 5 Relational Database Management Systems and SQL Spring 2014

description

Chapter 5 Relational Database Management Systems and SQL. Spring 2014. History of SQL. Proposed by E.F.Codd in his 1970 paper Used in System R, IBM’s research relational database in early 1970s-D.D. Chamberlin et al at IBM Research Center, San Jose, California - PowerPoint PPT Presentation

Transcript of Chapter 5 Relational Database Management Systems and SQL

Page 1: Chapter 5 Relational Database Management Systems and SQL

Chapter 5Relational Database Management Systems

and SQL

Spring 2014

Page 2: Chapter 5 Relational Database Management Systems and SQL

History of SQL• Proposed by E.F.Codd in his 1970 paper• Used in System R, IBM’s research relational database

in early 1970s-D.D. Chamberlin et al at IBM Research Center, San Jose, California

• Used in Oracle, released in late 1970s• Incorporated into IBM’s SQL/DS in 1981, and DB2 in

1983• Also used in Microsoft SQL Server, MySQL, Informix,

Sybase, PostGreSQL, Microsoft Access, and others

Page 3: Chapter 5 Relational Database Management Systems and SQL

Standards• ANSI and ISO published SQL standards in 1986, called

SQL-1• Minor revision, SQL-89• Major revision, SQL-2,1992• SQL-3, 1999, 2003, 2006, 2008- multi-part revision,

includes new data types, object-oriented (OO) facilities, user defined datatypes (UDTs), triggers, support for XML

• Most vendors support standard, but have slight variations of their own

Page 4: Chapter 5 Relational Database Management Systems and SQL

Components of SQL

• Data definition language - DDL• Data manipulation language - DML• Authorization language – grant privileges to

users

Page 5: Chapter 5 Relational Database Management Systems and SQL

Relational Database Architecture

• Separate external, logical, internal models• Logical level-base tables and indexes• Indexes, B+ or B trees – maintained by system• Relational views (external level) - derived from base

tables• Users see views or base tables, or combination• Internal level - files• SQL supports dynamic database definition-can

modify structures easilySee Figure 5.1

Page 6: Chapter 5 Relational Database Management Systems and SQL

Three level architecture for relational databases

Page 7: Chapter 5 Relational Database Management Systems and SQL

DDL Commands

CREATE TABLECREATE INDEXALTER TABLERENAME TABLEDROP TABLEDROP INDEX

Also – CREATE VIEW

Page 8: Chapter 5 Relational Database Management Systems and SQL

CREATE TABLE

CREATE TABLE base-table-name (

colname datatype [column constraints],

[,colname datetype [column constraints …]]

... ,

[table constraints]

[storage specifications]);

Page 9: Chapter 5 Relational Database Management Systems and SQL

Identifiers

• No SQL keywords

• Table name unique within the database

• Column name unique within the table

• In Oracle, identifiers must be at most 30 characters

long, begin with an alphabetic character, and contain

only alphanumeric characters (but _, $ and # are

permitted)

Page 10: Chapter 5 Relational Database Management Systems and SQL

Datatypes

• Each column must have a datatype specified

• Available datatypes vary from DBMS to DBMS

• Standards include various numeric types, fixed-length and varying-length

character strings, bit strings, and user-defined types

• Oracle types include CHAR(N), VARCHAR2(N), NUMBER(N,D), DATE, BLOB

(binary large object) and others

• SQL Server includes types of NUMERIC, BINARY, CHAR, VARCHAR DATETIME,

MONEY, IMAGE, and others

• Microsoft Access supports several types of NUMBER, as well as TEXT, MEMO,

DATE/TIME, HYPERLINK, YES/NO, and others

Page 11: Chapter 5 Relational Database Management Systems and SQL

MySQL Datatypes• VARCHAR• TINYINT• TEXT• DATE• SMALLINT• MEDIUMINT• INT• BIGINT• FLOAT• DOUBLE• DECIMAL• DATETIME• TIMESTAMP• TIME

YEAR CHAR TINYBLOB BLOB MEDIUMBLOB MEDIUMTEXT LONGBLOB LONGTEST ENUM SET BOOL BINARY VARBINARY

Page 12: Chapter 5 Relational Database Management Systems and SQL

Constraints

Column constraints – in-line constraints NOT

NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY,

REF, CHECK, and DEFAULT

Table constraints – out-of-line constraints

all of the above except NOT NULL

Page 13: Chapter 5 Relational Database Management Systems and SQL

Creating the Tables for the University Database

CREATE TABLE Student (stuId VARCHAR2(6),lastName VARCHAR2(20) NOT NULL,firstName VARCHAR2(20) NOT NULL,major VARCHAR2(10),credits NUMBER(3) DEFAULT 0,CONSTRAINT Student_stuId_pk PRIMARY KEY (stuId),CONSTRAINT Student_credits_cc CHECK ((credits>=0) AND (credits < 150)));

CREATE TABLE Faculty (facId VARCHAR2(6),name VARCHAR2(20) NOT NULL,department VARCHAR2(20),rank VARCHAR2(10),CONSTRAINT Faculty_facId_pk PRIMARY KEY (facId));

CREATE TABLE Class (classNumber VARCHAR2(8),facId VARCHAR2(6) NOT NULL,schedule VARCHAR2(8),room VARCHAR2(6),CONSTRAINT Class_classNumber_pk PRIMARY KEY (classNumber),CONSTRAINT Class_facId_fk FOREIGN KEY (facId) REFERENCES Faculty (facId) ON DELETE SET NULL,CONSTRAINT Class_schedule_room_uk UNIQUE (schedule, room));

CREATE TABLE Enroll (stuId VARCHAR2(6),classNumber VARCHAR2(8),grade VARCHAR2(2),CONSTRAINT Enroll_classNumber_stuId_pk PRIMARY KEY (classNumber, stuId),CONSTRAINT Enroll_classNumber_fk FOREIGN KEY (classNumber) REFERENCES Class (classNumber) ON DELETE CASCADE,CONSTRAINT Enroll_stuId_fk FOREIGN KEY (stuId) REFERENCES Student (stuId) ON DELETE CASCADE);

Page 14: Chapter 5 Relational Database Management Systems and SQL

Indexes• Can create any number of indexes for tables• Stored in same file as base table• Facilitate fast retrieval of records with specific values

in a column• Keep track of what values exist for the indexed

columns, and which records have those values • B+ trees or B trees used – see Appendix A for review

of concepts• Overhead – system must maintain index

Page 15: Chapter 5 Relational Database Management Systems and SQL

CREATE INDEX CommandCREATE [UNIQUE] INDEX indexname ON basetablename

(colname [order] [,colname [order]]...) [CLUSTER] ;

Ex. CREATE INDEX Student_lastName_firstName_ndx ON Student (lastName, firstName);

• UNIQUE specification enforces unique values for indexed column or combination of columns

• Except when specified, column need not be unique• Order is ASC(default) or DESC• Can have major and minor orders• CLUSTER specification keeps records with same value for

indexed field together (only one per table)• Oracle automatically indexes primary key columns

Page 16: Chapter 5 Relational Database Management Systems and SQL

ALTER TABLE Command• To add a new columnALTER TABLE basetablename ADD columnname datatype;Ex. ALTER TABLE Student ADD COLUMN birthdate DATETYPE;

– Cannot specify NOT NULL, since existing records have no value for this field

• To drop a columnALTER TABLE basetablename DROP COLUMN columnname;Ex. ALTER TABLE Student DROP COLUMN major;

• To change a column’s propertiesALTER TABLE basetablename MODIFY COLUMN colname [new specifications];

• To rename a columnALTER TABLE Student RENAME COLUMN colname TO new-colname;

Page 17: Chapter 5 Relational Database Management Systems and SQL

Other Changes to Tables• To add a constraintALTER TABLE basetablename ADD CONSTRAINT constraint_defn;• To drop a constraintALTER TABLE basetablename DROP CONSTRAINT constraint_name;• To rename a table:RENAME TABLE old-table-name TO new-table-name;Ex: RENAME TABLE FACULTY TO TEACHERS;• To drop a table:DROP TABLE basetablename;Ex. DROP TABLE CLASS;• To drop an index:DROP INDEX indexname;Ex. DROP INDEX Student_lastName_fristName_ndx;

Page 18: Chapter 5 Relational Database Management Systems and SQL

SQL DML

• Non-procedural, declarative language• Can be interactive, can be embedded in host

language, or can be stand-alone programming language (SQL/PSMs)

• Basic commandsSELECTUPDATEINSERTDELETE

Page 19: Chapter 5 Relational Database Management Systems and SQL

University Database

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns Edward Art

63

S1013 McCarthy Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

FacultyfacId name department rankF101 Adams Art ProfessorF105 Tanaka CSC InstructorF110 Byrne Math AssistantF115 Smith History AssociateF221 Smith CSC Professor

EnrollStuid classNumber grad

eS1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B A

ClassclassNumber facId schedule roomARTR103A F101 MWF9 H221CSC201A F105 TuThF10 M110CSC203A F105 MThF12 M110HST205A F115 MWF11 H221MAT101B F110 MTuTh9 H225MAT103C F110 MWF11 H225

Page 20: Chapter 5 Relational Database Management Systems and SQL

SELECT StatementSELECT [DISTINCT] col-name [AS newname], [,col-name..]…FROM table-name [alias] [,table-name]…[WHERE predicate][GROUP BY col-name [,col-name]…[HAVING predicate]or[ORDER BY col-name [,col-name]…];

• Powerful command – equivalent to relational algebra’s SELECT, PROJECT, JOIN and more…

• Can be applied to one or more tables or views• Can display one or more columns (renaming if desired)• Predicate is optional, and may include usual operators and connectives• Can put results in order by one or more columns• Can group together records with the same value for column(s)• Can also use predefined functions• See list of examples, Section 5.4.1-5.4.3

Page 21: Chapter 5 Relational Database Management Systems and SQL

Simple retrieval with condition• Get names, IDs, and number of credits of

all Math majors.– Information appears in Student table

SELECT lastName, first Name, stuId, creditsFROM StudentWHERE major = ‘Math’;

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns

Edward Art

63

S1013 McCarthy

Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

lastName fristName

Stuid Credits

Chin Ann S1002 36McCarthy

Owen S1013 0

Jones Mary S1015 42

Page 22: Chapter 5 Relational Database Management Systems and SQL

All columns• Get all information about CSC Faculty.

– Information appears in Faculty table– Use asterisk for “all columns”

SELECT *FROM FacultyWHERE department= ‘CSC’;

FacultyfacId name department rank

F101 Adams Art ProfessorF105 Tanaka CSC InstructorF110 Byrne Math AssistantF115 Smith History AssociateF221 Smith CSC Professor

facId name department rankF105 Tanaka CSC InstructorF221 Smith CSC Professor

May want to avoid the “*” because columns may be added later that may produce incorrect results

Page 23: Chapter 5 Relational Database Management Systems and SQL

Retrieval without conditions• Get the course number of all courses in which students are enrolled

SELECT classNumberFROM Enroll;

EnrollStuid classNumber grade

S1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B A

classNumberART103AHST205AART103ACSC201AMTH103CART103AMTH103CCSC201AMTH101B

SELECT DISTINCT classNumberFROM Enroll;

classNumberART103ACSC201AHST205AMTH101BMTH103C

Page 24: Chapter 5 Relational Database Management Systems and SQL

Entire Table• Retrieve entire table

SELECT *FROM Student;

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns

Edward Art

63

S1013 McCarthy

Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

Stuid lastName fristName

Major Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns

Edward Art

63

S1013 McCarthy

Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

Page 25: Chapter 5 Relational Database Management Systems and SQL

ORDER BY and AS• Get names and IDs of all Faculty members, arranged in alphabetical

order by name. Call the resulting columns FacultyName and FacultyNumber

SELECT name AS FacultyName, facId AS FacultyNumber

FROM FacultyORDER BY name;

FacultyfacId name department rank

F101 Adams Art ProfessorF105 Tanaka CSC InstructorF110 Byrne Math AssistantF115 Smith History AssociateF221 Smith CSC Professor

FacultyName FacultyNumberAdams F101Byrne F110Smith F202Smith F221Tanaka F105

SELECT name AS FacultyName, facId AS FacultyNumber

FROM FacultyORDER BY name, department;

FacultyName FacultyNumberAdams F101Byrne F110Smith F221Smith F202Tanaka F105

Page 26: Chapter 5 Relational Database Management Systems and SQL

Multiple Conditions• Get names of all math majors who have more than 30

credits

SELECT lastName, firstNameFROM StudentWHERE major = ‘Math’ AND credits > 30;

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns

Edward Art

63

S1013 McCarthy

Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

lastName fristName

Jones MaryChin Ann

Page 27: Chapter 5 Relational Database Management Systems and SQL

SELECT using multiple tables• Natural Join• Find IDs and names of all students taking ART103A

SELECT Enroll.stuId, lastName, firstName

FROM Student, EnrollWHERE classNumber = ‘ART103A

AND Enroll.sutId = Student.stuId;

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns

Edward Art

63

S1013 McCarthy

Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

EnrollStuid classNumber grade

S1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B A

Stuid lastName fristName

S1001 Smith TomS1010 Burns

Edward

S1002 Chin Ann

Page 28: Chapter 5 Relational Database Management Systems and SQL

Natural Join with Ordering• Find stuId and grade of all students taking any course taught by Faculty

member whose facId is F110. Arrange in order by stuId

SELECT stuId, gradeFROM Class, EnrollWHERE facId = ‘F110’ AND

Class.classNumber = Enroll.classNumberORDER BY stuId ASC;

EnrollStuid classNumber grade

S1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B A

Stuid gradeS1002 BS1010 S1020 A

ClassclassNumber facId schedule roomARTR103A F101 MWF9 H221CSC201A F105 TuThF10 M110CSC203A F105 MThF12 M110HST205A F115 MWF11 H221MAT101B F110 MTuTh9 H225MAT103C F110 MWF11 H225

Page 29: Chapter 5 Relational Database Management Systems and SQL

Natural Join of three tables• Find course numbers and the

names and majors of all students enrolled in the courses taught by Faculty member F110

SELECT Enroll.classNumber, lastName, firstName, major

FROM Class, Enroll, StudentWHERE facId = ‘F110’ AND

Class.classNumber = Enroll.classNumber AND Enroll.stuId = Student.stuId;

EnrollStuid classNumber grade

S1001 ART103A AS1001 HST205A CS1002 ART103A D

S1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B A

ClassclassNumber facId schedule roomARTR103A F101 MWF9 H221CSC201A F105 TuThF10 M110CSC203A F105 MThF12 M110HST205A F115 MWF11 H221MAT101B F110 MTuTh9 H225MAT103C F110 MWF11 H225

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns

Edward Art

63

S1013 McCarthy

Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

Stuid lastName fristName

Major

S1001 Rivera Jane CSCS1002 Burns

Edward Art

S1005 Chin Ann Math

Page 30: Chapter 5 Relational Database Management Systems and SQL

Use of Aliases• Get a list of all courses that meet in the same room, with their schedules

and room numbers

SELECT Copy1.classNumber, COPY1.schedule, COPY1.room, COPY2.classNumber, COPY2.schedule

FROM Class COPY1, Class COPY2WHERE COPY1.room = COPY2.room AND

COPY1.classNumber < COPY2.classNumber;

ClassclassNumber facId schedule roomARTR103A F101 MWF9 H221CSC201A F105 TuThF10 M110CSC203A F105 MThF12 M110HST205A F115 MWF11 H221MAT101B F110 MTuTh9 H225MAT103C F110 MWF11 H225

ClassCOPY1.classNumber COPY1.schedule COPY1.room COPY2.classNumber COPY2.scheduleARTR103A MWF9 H221 HST205A MWF11

CSC201A TuThF10 M110 CSC203A MThF12MAT101B MTuTh9 H225 MAT103C MWF11

Page 31: Chapter 5 Relational Database Management Systems and SQL

Join without Equality Condition• Find all combinations of students and Faculty where the student’s major is

different from the Faculty member’s department

SELECT stuId, lastName, firstName, major, facId, name, department

FROM Student, FacultyWHERE Student.major <>

Faculty.department

StudentStuid lastName fristNam

eMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns Edward Art 63S1013 McCarthy Owen Math 0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

FacultyfacId name department rankF101 Adams Art ProfessorF105 Tanaka CSC InstructorF110 Byrne Math AssistantF115 Smith History AssociateF221 Smith CSC Professor

Stuid lastName fristName Major facId name departmentS1001 Smith Tom History F101 Adams Art

S1001 Smith Tom History F105 Tanaka CSCS1001 Smith Tom History F110 Byrne MathS1001 Smith Tom History F221 Smith CSCS1010 Burns Edward Art F115 Smith History… … … … … … …S1013 McCarthy Owen Math F221 Smith CSC

Page 32: Chapter 5 Relational Database Management Systems and SQL

Subqueries with Equality• Find the numbers of all the courses taught by Byrne of the Math

department

SELECT classNumberFROM ClassWHERE facId = (SELECT facId FROM Faculty WHERE name = 'Byrne' AND department = 'Math');

This produces the same resultsSelect classNumberFROM Class, FacultyWHERE name = 'Byrne' AND department = 'Math'

AND Class.facId = Faculty.facId;

Can use a subquery in place of a join, provided the result to be displayed is contained in a single table and the data retrieved from the subquery consists of only one column.

When you write a subquery involving two tables, you name only one table in each SELECT.

Page 33: Chapter 5 Relational Database Management Systems and SQL

Four Table Example• List each faculty, the course name and

the names of students in each class.

SELECT name, Class.classNumber, lastName, firstName

FROM Faculty, Class, Student, Enroll

WHERE Faculty.facId = Class.facId

AND Enroll.stuId = Student.stuId

AND Enroll.classNumber = Class.classNumber

ORDER BY name, Enroll.classNumber, lastName;

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns Edward Art

63

S1013 McCarthy Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

EnrollStuid classNumber grad

eS1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B AClass

classNumber facId schedule roomART103A F101 MWF9 H221CSC201A F105 TuThF10 M110CSC203A F105 MThF12 M110HST205A F115 MWF11 H221MAT101B F110 MTuTh9 H225MAT103C F110 MWF11 H225

FacultyfacId name department rankF101 Adams Art ProfessorF105 Tanaka CSC InstructorF110 Byrne Math AssistantF115 Smith History AssociateF221 Smith CSC Professor

Page 34: Chapter 5 Relational Database Management Systems and SQL

Example• List class schedule for each professor

SELECT name, classNumber, schedule, room

FROM Faculty, Class

WHERE Faculty.facId = Class.facId

ORDER BY name, schedule

StudentStuid lastName fristNa

meMajor Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns Edward Art

63

S1013 McCarthy Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

EnrollStuid classNumber grad

eS1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B AClass

classNumber facId schedule roomARTR103A F101 MWF9 H221CSC201A F105 TuThF10 M110CSC203A F105 MThF12 M110HST205A F115 MWF11 H221MAT101B F110 MTuTh9 H225MAT103C F110 MWF11 H225

FacultyfacId name department rankF101 Adams Art ProfessorF105 Tanaka CSC InstructorF110 Byrne Math AssistantF115 Smith History AssociateF221 Smith CSC Professor

Page 35: Chapter 5 Relational Database Management Systems and SQL

Subqueries using IN• Find the names and IDs of all Faculty members who teach a class in

Room H221.

SELECT name, facIdFROM FacultyWHERE facId IN (SELECT facId FROM Class WHERE room = ‘H221’);

In the WHERE line in the main query we use IN instead of =, because the result of the subquery is a set of values rather than a single value.

Comparison operator (=, etc.) is restricted to single value, the IN can have multiple values.

NOT IN will evaluate to true if the record has a field value which is not in the set of values retrieved by the subquery.

Page 36: Chapter 5 Relational Database Management Systems and SQL

Nested Subqueries• Get an alphabetical lis tof names and IDs of all students in any class

taught by F110.

SELECT lastName, firstName, stuIdFROM StudentWHERE stuId IN (SELECT stuId FROM Enroll WHERE classNumber IN (SELECT classNumber FROM Class WHERE facId = ‘F110’));

Since values to be displayed appear on one table, Student, can use a subquery.

In execution, the most deeply nested SELECT is done first, and it is replaced by the values retrieved. Then the next most nested SELECT is done.

Page 37: Chapter 5 Relational Database Management Systems and SQL

Queries using EXISTS• Find the names of all students enrolled in CSC201A.

SELECT lastName, firstNameFROM StudentWHERE EXISTS (SELECT * FROM Enroll WHERE Enroll.stuId = Student.stuId AND classNumber = ‘CSC201A’);

We can do this with a join or subquery using IN. Finds records in Enroll with stuId that is in Student. Use name of main query table (Student) in subquery. Usually

don’t do that, but in this case it is acceptable.

Page 38: Chapter 5 Relational Database Management Systems and SQL

Queries using NOT EXISTS• Find the names of all students not enrolled in CSC201A.

SELECT lastName, firstNameFROM StudentWHERE NOT EXISTS (SELECT * FROM Enroll WHERE Enroll.stuId = Student.stuId AND classNumber = ‘CSC201A’);

Page 39: Chapter 5 Relational Database Management Systems and SQL

Queries using UNION• Get IDs of all Faculty who are assigned to the history department or who

teach in Room H221.

SELECT facIdFROM FacultyWHERE department = “History”UNIONSELECT facIdFROM ClassWHERE room = “H221”;

Page 40: Chapter 5 Relational Database Management Systems and SQL

Queries using Functions• Find the total number of students enrolled in ART103A.

SELECT COUNT (DISTINCT stuId)FROM EnrollWHERE classNumber= “ART103A”;

DISTINCT used to eliminate duplicates before counting the number of students.

Built-in Functions:• COUNT• SUM• AVG• MAX• MIN

COUNT, MAX, MIN apply to both numeric and non numeric fieldsSUM, AVG apply to numeric only

Page 41: Chapter 5 Relational Database Management Systems and SQL

Queries using Functions• Find the number of departments that have faculty in them.

SELECT COUNT (DISTINCT department)FROM Faculty;

Find the average number of credits students have.SELECT Avg (credits)FROM Student;

Find the student with the largest number of credits.SELECT stuId, lastName, firstNameFROM StudentWHERE credits = (SELECT MAX (credits) FROM Student);

Find the ID of the student(s) with the highest grade in any course.SELECT stuIdFROM EnrollWHERE grade = (SELECT MIN(grade) FROM Enroll);

Page 42: Chapter 5 Relational Database Management Systems and SQL

Queries using Functions• Find the names and IDs of students who have less than the average number of credits.

SELECT lastName, firstName, stuIdFROM StudentWHERE credits < (SELECT AVG (credits) FROM Student);

Page 43: Chapter 5 Relational Database Management Systems and SQL

Query using Expression and a String Constant

• Assuming each course is three credtis, list, for each student, the number of courses he or she has completed.

SELECT stuId, ‘Number of courses = ‘, credits/3FROM Student;

Page 44: Chapter 5 Relational Database Management Systems and SQL

Queries using GROUP BY and HAVING

• For each course, show the number of students enrolled.

SELECT classNumber, COUNT(*)FROM EnrollGROUP BY classNumber;

Find all courses in which fewer than three students are enrolled.

SELECT classNumberFROM EnrollGROUP BY classNumberHAVING COUNT(*) < 3;

Page 45: Chapter 5 Relational Database Management Systems and SQL

Queries using LIKE

• Get details of all MTH courses.

SELECT *FROM ClassWHERE classNumber LIKE ‘MTH%’;

% character stands for any sequence of characters of an length >= 0._ character stands for any single character.

srtuId LIKE ‘S____’ means ther must be five charactes, the first must be S

schedule LIKE ‘%9’ means any sequence of characters, of length at least one, with the last character a nine.

name NOT LIKE ‘A% means the name cannot begin with an A.

Page 46: Chapter 5 Relational Database Management Systems and SQL

Queries using NULL

• Find stuId and classNumber of all students whose grades in that course are missing.

SELECT classNumber, stuIdFROM EnrollWHERE grade IS NULL;

Cannot use WHERE grade = NULL – will return unknown

Page 47: Chapter 5 Relational Database Management Systems and SQL

University DatabaseStudent

Stuid lastName fristName

Major Credits

S1001 Smith Tom History 9 0S1002 Chin Ann Math 36S1005 Lee Perry History 3S1010 Burns Edward Art

63

S1013 McCarthy Owen Math

0

S1015 Jones Mary Math 42 S1020 Rivera Jane CSC 15

FacultyfacId name department rankF101 Adams Art ProfessorF105 Tanaka CSC InstructorF110 Byrne Math AssistantF115 Smith History AssociateF221 Smith CSC Professor

EnrollStuid classNumber grad

eS1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B A

ClassclassNumber facId schedule roomARTR103A F101 MWF9 H221CSC201A F105 TuThF10 M110CSC203A F105 MThF12 M110HST205A F115 MWF11 H221MAT101B F110 MTuTh9 H225MAT103C F110 MWF11 H225

Page 48: Chapter 5 Relational Database Management Systems and SQL

UPDATE OperatorUPDATE tablenameSET columnname = expression [columnname = expression]... [WHERE predicate];

• Used for changing values in existing records• Can update, zero, one, many, or all records in a table• For null value, use SET columnname = NULL• can use a sub-query to identify records to be updated

Page 49: Chapter 5 Relational Database Management Systems and SQL

UPDATE Examples

• Updating a single Field of One RecordUPDATEStudentSET major = ‘Music’WHERE stuId = ‘S1020’;

• Updating Several Fields of One RecordUPDATEFacultySET department = ‘MIS’

rank = ‘Assistant’WHERE name = ‘Tanaka’;

Page 50: Chapter 5 Relational Database Management Systems and SQL

UPDATE Examples

• Updating Using NULLUPDATEStudentSET major = NULL

stuId = ‘S1013’WHERE name = ‘McCarthy’;

• Updating Several RecordsUPDATEEnrollSET grade = ‘A’WHERE classNumber = ‘CSC201A’;

Page 51: Chapter 5 Relational Database Management Systems and SQL

UPDATE Examples• Updating All Records

UPDATEStudentSET credits = credits + 3;

• Updating with a SubqueryUPDATEClassSET room = ‘B220’WHERE facId =

(SELECT facIdFROM FacultyWHERE name = ‘Tanaka’;

Page 52: Chapter 5 Relational Database Management Systems and SQL

INSERT OperatorINSERTINTO tablename [(colname [,colname]...)]VALUES (constant [,constant]...);

• Used for inserting new records into database, one at a time• Not necessary to name columns if values are supplied for all

columns, in proper order• To insert null value for a column, specify only the other

columns or write null as the value• Can specify DEFAULT as value if column has a default defined• Can specify values for some columns, in any order, as long as

values match order

Page 53: Chapter 5 Relational Database Management Systems and SQL

INSERT Examples• Insert a Single Record, with All Fields Specified

INSERTINTO Faculty (facId, name, department, rank)VALUES (‘F330’, ‘Jones’, ‘CSC’, ‘Instructor’);

• Insert a Single Record, without Specifying Fields INSERTINTO StudentVALUES (‘S1030’, ‘Hunt’, ‘Alice’, ‘Art’, 12);

Page 54: Chapter 5 Relational Database Management Systems and SQL

INSERT Examples• Insert a Record with a NULL Values in a Field

INSERTINTO Student (lastName, firstName, stuId, credits)VALUES (‘S1030’, ‘Maria’, ‘S1031’, 0);

Page 55: Chapter 5 Relational Database Management Systems and SQL

INSERT Examples• Create and fill a new table that shows each

course and the number of students enrolled in it.• Insert Multiple Records

CREATE TABLE Enrollment (classNumber CHAR(7) NOT NULL, Students SMALLINT)

INSERTINTO Enrollment (classNumber, Students)

SELECT classNumber, COUNT(*)FROM EnrollGROUP BY classNumber;

Page 56: Chapter 5 Relational Database Management Systems and SQL

DATE and SYSDATE• Oracle uses default format'dd-mon-yy‘• SYSDATE returns the current system date and time• TRUNC(SYSDATE) - time part is set to 00:00• TO_CHAR(datevalue, format string) returns part of date

specified by format stringEx. TO_CHAR(birthDate, ‘YYYY’) returns year of birthDate

• TO_DATE (string, format string) converts an appropriate string into a DATE formatEx. TO_DATE('01/01/2012', 'MM/DD/YYYY')

Page 57: Chapter 5 Relational Database Management Systems and SQL

Sequences in Oracle

• CREATE SEQUENCE seqname [START WITH n] [INCREMENT BY n];

• Default for n is 1• Useful for generating automatic numbering for

records• not tied to a particular table• seqname.NEXTVAL -generates new value• seqname.CURRVAL -returns current value• DROP SEQUENCE seqname - drops a sequence

Page 58: Chapter 5 Relational Database Management Systems and SQL

DELETE OperatorDELETEFROM tablenameWHERE predicate;

• Used for deleting existing records from database• Can delete zero, one, many, or all records• Operation may not work if referential integrity would

be lost• Can use a sub-query to target records to be deleted• If you delete all records from a table, its structure

still remains, and you can insert into it later

Page 59: Chapter 5 Relational Database Management Systems and SQL

DELETE Examples• Deleting a Single Record

DELETEFROM StudentWHERE stuId = ‘S1020’;

• Deleting Several RecordsDELETEFROM EnrollWHERE stuId = ‘S1020’;

Page 60: Chapter 5 Relational Database Management Systems and SQL

DELETE Examples• Deleting with a Subquery

DELETEFROM EnrollWHERE stuId =

SELECT stuIdFROM StudentWHERE lastName = ‘Mc Carthy’ AND firstName = ‘Owen’);

Page 61: Chapter 5 Relational Database Management Systems and SQL

Relational Views

• Can be subsets of base tables, or subsets of joins, or contain calculated data

• Reasons for views – Allow different users to see the data in different

forms– Provide a simple authorization control device– Free users from complicated DML operations– If database is restructured, view can keep the

user's model constant

Page 62: Chapter 5 Relational Database Management Systems and SQL

Create ViewCREATE [OR REPLACE] VIEW viewname

[(viewcolname,viewcolname]...)] AS SELECT colname [,colname]...

FROM basetablename [,basetablename]... WHERE condition;

• Can create vertical subset of table, choosing only certain columns, with no WHERE, called value-independent view

• Can choose only certain rows, using WHERE, called value-dependent view

• Can use a join of tables to create view of combination• Can use functions or subqueries in SELECT

Page 63: Chapter 5 Relational Database Management Systems and SQL

Using Views• Can write new SQL statements using view

name in FROM line• Can create a view of a view• Can sometimes insert/update a view

– requires that the primary key be in the view

– Actually updates underlying table• Can modify existing view by using Create or

replace

Page 64: Chapter 5 Relational Database Management Systems and SQL

VIEW Examples• Choosing a Vertical and Horizontal Subset of a

tableCREATE VIEW HISTMAJ (last, first, StudentId)

AS SELECT lastName, firstName, stuIdFROM StudentWHERE major = ‘History’;

• Choosing a Vertical Subset of a TableCREATE VIEW ClassLoc

AS SELECT ClassNumber, sechedule, roomFROM Class;

Page 65: Chapter 5 Relational Database Management Systems and SQL

Active Databases-Constraints• DBMS monitors database to prevent illegal states,

using constraints and triggers• Constraints

– can be specified when table is created, or later– IMMEDIATE MODE: constraint checked when each INSERT,

DELETE, UPDATE is performed– DEFERRED MODE: postpones constraint checking to end of

transaction – write SET CONSTRAINT name DEFERRED– Can use ALTER TABLE table-name DISABLE CONSTRAINT

constraint -name, – and later ALTER TABLE table-name ENABLE CONSTRAINT

constraint - name

Page 66: Chapter 5 Relational Database Management Systems and SQL

Triggers• More flexible than constraints• Use ECA model:

– event, some change made to the database– condition, a logical predicate – action, procedure done when the event occurs and the condition is

true, also called firing the trigger• Can be fired before or after insert, update, delete• Trigger can access values it needs as :OLD. and :NEW.

– prefix :OLD refers to values in a tuple deleted or to the values replaced in an update

– prefix :NEW refers to the values in a tuple just inserted or to the new values in an update.

• Can specify whether trigger fires just once for each triggering statement, or for each row that is changed by the statement

Page 67: Chapter 5 Relational Database Management Systems and SQL

Trigger SyntaxCREATE OR REPLACE TRIGGER trigger_name[BEFORE/AFTER] [INSERT/UPDATE/DELETE] ON table_name[FOR EACH ROW] [WHEN condition]BEGIN

trigger bodyEND;• Can disable triggers using ALTER TRIGGER name DISABLE;• Later write ALTER TRIGGER name ENABLE;• Can drop triggers using DROP TRIGGER name;• See examples in Figure 5.4 and Figure 5.5

Page 68: Chapter 5 Relational Database Management Systems and SQL

RevClass

classNumber facId schedule room currentEnroll maxEnroll

ART103A F101 MWF9 H221 3 25CSC201A F105 TuThF10 M110 2 20CSC203A F105 MThF12 M110 0 20HST205A F115 MWF11 H221 1 35MTH101B F110 MTuTh9 H225 1 25MTH103C F110 MWF11 H225 2 25

RevEnrollstuId classNumber grade

S1001 ART103A AS1001 HST205A CS1002 ART103A DS1002 CSC201A FS1002 MTH103C BS1010 ART103AS1010 MTH103CS1020 CSC201A BS1020 MTH101B A

Figure 5.5 (a) Tables for Triggers

CREATE TRIGGER ADDENROLLAFTER INSERT ON RevEnrollFOR EACH ROW

UPDATE RevClassSET currentEnroll = currentEnroll +1WHERE RevClass.classNumber =:NEW.classNumber;

 Figure 5.5(b) Trigger for Student Enrolling in a Class

Page 69: Chapter 5 Relational Database Management Systems and SQL

CREATE TRIGGER DROPENROLLAFTER DELETE ON RevEnrollFOR EACH ROW

UPDATE RevClassSET currentEnroll = currentEnroll -1WHERE RevClass.classNumber = OLD.classNumber;

 Figure 6.5(c) Trigger for Student Dropping a Class

CREATE TRIGGER SWITCHENROLLAFTER UPDATE OF classNumber ON RevEnrollFOR EACH ROW

BEGINUPDATE RevClassSET currentEnroll = currentEnroll + 1 WHERE RevClass.classNumber =:NEW.classNumber;UPDATE RevClassSET currentEnroll = currentEnroll -1WHERE RevClass.classNumber = :OLD.classNumber;

END; Figure 5.5(d) Trigger for Student Changing Classes

Page 70: Chapter 5 Relational Database Management Systems and SQL

CREATE TRIGGER ENROLL_REQUESTBEFORE INSERT OR UPDATE OF classNumber ON RevEnrollFOR EACH ROWWHEN

((SELECT maxEnrollFROM RevClassWHERE RevClass.classNumber = :NEW.classNumber)

< (SELECT currentEnroll + 1FROM RevClassWHERE RevClass.classNumber = :NEW.classNumber))

RequestClosedCoursePermission(:NEWstuId, :NEW.classNumber, RevClass.currentEnroll, RevClass.maxEnroll);  Figure 5.5(e) Trigger for Checking for Over-enrollment Before Enrolling Student

Page 71: Chapter 5 Relational Database Management Systems and SQL

Ending Transactions

• COMMIT makes permanent changes in the current transaction

• ROLLBACK undoes changes made by the current transaction

Page 72: Chapter 5 Relational Database Management Systems and SQL

SQL/PSM

• Persistent Stored Modules-used to create internal routines within database space

• Can be saved with database schema and invoked • Oracle uses PL/SQL, accessed within SQL*Plus• Provides complete programming language facilities-

declarations, control, assignment, functions, procedures, temporary relations, etc.

• Can also use Java in internal routines in Oracle

Page 73: Chapter 5 Relational Database Management Systems and SQL

PL/SQL Procedures• Create procedures-can write in SQL*Plus window:

CREATE [OR REPLACE] PROCEDURE procedure_name (formal parameter_list) {AS/IS}declarations of local variables and constantsBEGIN

executable statements[EXCEPTION exception handling]

END;/• Parameters may be IN, OUT, or IN OUT• To debug, write show errors, make corrections, and compile• To execute

EXECUTE procedure_name(actual_ parameter_ list);

Page 74: Chapter 5 Relational Database Management Systems and SQL

PL/SQL Functions

• Create procedures-can write in SQL*Plus window:CREATE [OR REPLACE] FUNCTION function_name (parameter list)

RETURNS SQLdatatype {AS/IS}declarations of local variablesBEGIN

function code (must include a RETURN statement)[EXCEPTION exception handling]

END;/• Parameters can be IN only, no OUT or IN OUT• A function is invoked by using its name, typically in an assignment

statement• Example: SET newVal = MyFunction(val1, val2);

Page 75: Chapter 5 Relational Database Management Systems and SQL

Elements of PL/SQL

• Declarations– identifier datatype [:= initial value];

• Body of code– SQL DML (but not DDL) statements

SELECT ..INTO variables FROM...WHERE;UPDATE..SET…= ; – assignment statements for declared variables

var := value;

– control statementsIF…THEN…ELSE…END IF; CASE…WHEN…END CASE; FOR…LOOP…END LOOP; WHILE… DO… END WHILE, REPEAT…UNTIL…END REPEAT; FOR …DO… END FOR

– error handling

Page 76: Chapter 5 Relational Database Management Systems and SQL

Cursors• Needed when processing multiple records• symbolic pointer to a multiset• retrieves one row at a time• Declaring a cursor

cursorname IS query;• Opening the cursor, executes the query

OPEN cursorname;• Fetching the next row (usually in a loop)

FETCH cursorname INTO hostvariables;• Closing the cursor

CLOSE cursorname;

Page 77: Chapter 5 Relational Database Management Systems and SQL

Error Handling in PL/SQLEXCEPTION

WHEN exception1 THEN …WHEN exception2 THEN ……WHEN OTHERS THEN …END;

•Examples of predefined exceptionsNO_DATA_FOUND, DUP_VAL-ON-INDEX

•Usual code for other exceptionswhen others then DBMS_OUTPUT.PUT_LINE('Error-' || SQLERRM);

•User-defined exceptions-declare, give condition, give actionexception_name EXCEPTION;if (exception_condition) then RAISE exception_name…WHEN exception_name THEN action;

Page 78: Chapter 5 Relational Database Management Systems and SQL

Embedded SQL• SQL can be embedded in host languages, such as Visual Basic,

C, C++, Java, COBOL, Fortran…• Client-side programs• Host language provides control structures; SQL used for

database access• SQL statements preceded by EXEC SQL, end with ;• Executable SQL statement can appear wherever a host

language executable statement can appear• Pre-compiler for DB compiles SQL separately from program;

creates access module• Host language statements compiled as usual• Data exchange done using shared variables

Page 79: Chapter 5 Relational Database Management Systems and SQL

Shared Variables• Declared in SQL declaration section. Ex:

EXEC SQL BEGIN DECLARE SECTION;char stuNumber[5];…int stuCredits;char SQLSTATE[6];EXEC SQL END DECLARE SECTION;

• SQLSTATE can used for error conditions– ’00000’ means no error, while ‘02000’ means no tuple found for query– Value of SQLSTATE should be tested in host language, as in WHILE(SQLSTATE=‘00000’)

or UNTIL(SQLSTATE=‘02000’)• SQLCA, SQL communications area, can be used instead

– Ex. #include <sqlca.h> - in host program– Error codes returned, can test with

EXEC SQL WHENEVER <condition> <action>;

Page 80: Chapter 5 Relational Database Management Systems and SQL

Single-row Embedded SQL SELECTstuNumber = 'S1001';EXEC SQL

SELECT Student.lastName, Student.firstName, Student.major, Student.credits

INTO :stuLastName, :stuFirstName, :stuMajor, :stuCreditsFROM StudentWHERE Student.stuId = :stuNumber;

• INTO line lists shared variables declared previously• In SQL statements, use colon before shared variables to

distinguish them from database attributes; they may have the same or different names from attributes

• In the host language, use the shared variables without colon, exif(stuCredits>120)…

Page 81: Chapter 5 Relational Database Management Systems and SQL

Insert in Embedded SQL• Assign values to program shared variables• Use SQL INSERT, listing shared variables (now

preceded by colon) as valuesEx:

stuNumber = ‘S1050’;stuLastName = ‘Lee’;stuFirstName = ‘Daphne’;stuMajor = ‘English’;stuCredits = 0;EXEC SQL INSERT

INTO Student (stuId, lastName, firstName, major, credits)

VALUES(:stuNumber,:stuLastName,:stuFirstName,:stuMajor, :stuCredits);

Page 82: Chapter 5 Relational Database Management Systems and SQL

Delete in Embedded SQL

• Use program shared variables to identify target tuple(s)

• Use SQL DELETE, identifying tuple(s) in WHERE line using shared variables (preceded by colon)

Ex:stuNumber = ‘S1015’;EXEC SQL DELETE

FROM StudentWHERE stuId = :stuNumber;

Page 83: Chapter 5 Relational Database Management Systems and SQL

Update in Embedded SQL

• Use program shared variables to identify target tuple(s)

• Use SQL UPDATE, identifying tuple(s) in WHERE line using shared variables preceded by colonEx:stuMajor = ‘History’;EXEC SQL UPDATE Student

SET CREDITS = CREDITS + 3WHERE major = :stuMajor;

Page 84: Chapter 5 Relational Database Management Systems and SQL

Error Handling using WHENEVER

• Can check each SQL transaction individually, or do error-handling for entire program using WHENEVER

EXEC SQL WHENEVER [NOT FOUND/SQLERROR/SQLWARNING][CONTINUE/DO/DO BREAK/ GO TO...];

Page 85: Chapter 5 Relational Database Management Systems and SQL

Using Cursors• Impedance mismatch: SQL SELECT can retrieve multiple rows, while host language

requires one row at a time• Declare a cursor:

EXEC SQL DECLARE cursorname [INSENSITIVE] [SCROLL] CURSOR FOR query[FOR {READ ONLY | UPDATE OF attributeNames}];

• Query is regular SQL query, using attributes names (not the shared variables)• Opening the cursor executes the SQL query

EXEC SQL OPEN cursorname;• Set up a loop in host language

Ex. WHILE (SQLSTATE = ‘00000’) • To retrieve each row of the results, use FETCH

EXEC SQL FETCH cursorname INTO hostvariables;• hostvariables are shared variables; preceded by colon• At end, close the cursor

EXEC SQL CLOSE cursorname;

Page 86: Chapter 5 Relational Database Management Systems and SQL

Cursor ExampleEXEC SQL DECLARE CSCstuCursor CURSOR FOR

SELECT stuId, lastName, firstName, major, creditsFROM studentWHERE major=‘CSC’;

EXEC SQL OPEN CSCstuCursor;WHILE (SQLSTATE = ‘00000’)

EXEC SQL FETCH CSCstuCursor INTO :stuNumber,:stuLastName, :stuFirstName,:stuMajor,:stuCredits //Process each record retrieved

END; //of WHILEEXEC SQL CLOSE CSCstuCursor;

Page 87: Chapter 5 Relational Database Management Systems and SQL

Update and Delete Using a Cursor

• Must declare cursor for update: FOR UPDATE OF variablename

• Once cursor is open and active, current of cursor refers to the tuple it is positioned at

• To update:EXEC SQL UPDATE tablenameSET attributename = newvalueWHERE CURRENT OF cursorname;

• To delete:EXEC SQL DELETE FROM tablenameWHERE CURRENT OF cursorname;

Page 88: Chapter 5 Relational Database Management Systems and SQL

Dynamic SQL• Can create a graphical front end that accepts queries

dynamically• At run time, user prompted to enter an SQL command• Command stored as string• PREPARE statement used to parse and compile string and assign

it to variable• EXECUTE command executes the code• Exchar userString[ ]=‘UPDATE Student SET credits = 36 WHERE stuId=

S1050’;EXEC SQL PREPARE userCommand FROM :userString;EXEC SQL EXECUTE userCommand;

Page 89: Chapter 5 Relational Database Management Systems and SQL

API, ODBC and JDBC

• DBMS can provide a library of functions available to host languages using an API

• ODBC/JDBC provide standardized connectivity using a common interface, allows common code to access different databases

• Most vendors provide ODBC or JDBC drivers that conform to the standard

• Requires four components: application, driver manager, driver, and data source (database)

Page 90: Chapter 5 Relational Database Management Systems and SQL

ODBC/JDBC Components • Application, using the standard API

– initiates the connection with the database– submits data requests as SQL statements to the DBMS– retrieves the results– performs processing– terminates the connection

• Driver manager – loads and unloads drivers at the application’s request– passes the ODBC or JDBC calls to the selected driver

• Database driver – links the application to the data source– translates the ODBC or JDBC calls to DBMS-specific calls– handles data translation needed because of any differences between the DBMS’s data

language and the ODBC/JDBC standard– Controls error handling differences that arise between the data source and the

standard. • Data source: database (or other source), DBMS and platform; provides the data

Page 91: Chapter 5 Relational Database Management Systems and SQL

System Catalog• Also called system data dictionary• Contains metadata• Automatically updated when new database objects created –

stores schema• Oracle data dictionary provides three views: USER, ALL, and

DBA.• View invoked by using the appropriate term as a prefix for the

object(s) named in the FROM clause in a query – USER view provides a user with information about all the objects

created by that user– ALL view provides information about objects user has permission to

access in addition to the one the user has created. – DBA view provides information about all database objects; available

to the database administrator

Page 92: Chapter 5 Relational Database Management Systems and SQL

Using Oracle Catalog -ExamplesDESCRIBE STUDENT;DESCRIBE USER_CONSTRAINTS;

SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAMEFROM USER_CONSTRAINTS;

SELECT TABLE_NAMEFROM USER_TABLES;

SELECT VIEW_NAMEFROM USER_VIEWS;

SELECT TRIGGER_NAME, TRIGGER_EVENT, TRIGGER_TYPEFROM USER_TRIGGERS;

SELECT *FROM USER_TAB_COLUMNS;

SELECT COLUMN_NAME, DATA_TYPEFROM USER_TAB_COLUMNSWHERE TABLE_NAME = ‘STUDENT’;