+ All Categories
Home > Documents > Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Date post: 22-Dec-2015
Category:
View: 228 times
Download: 5 times
Share this document with a friend
54
Database Administration Database Administration ISQA 436 ISQA 436 SQL Review, SQL Review, Oracle Objects Oracle Objects and Data Types, and Data Types, SQL*Plus SQL*Plus
Transcript
Page 1: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Database AdministrationDatabase AdministrationISQA 436ISQA 436

SQL Review,SQL Review,Oracle ObjectsOracle Objects

and Data Types,and Data Types,SQL*PlusSQL*Plus

Page 2: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQLSQL

• Structured Query LanguageStructured Query Language• Declaritive language vs. proceduralDeclaritive language vs. procedural• Three types of SQL statementsThree types of SQL statements

– Data Manipulation Language (DML)Data Manipulation Language (DML)

– SELECT, INSERT, UPDATE, DELETESELECT, INSERT, UPDATE, DELETE

– Data Definition Language (DDL)Data Definition Language (DDL)

– CREATE/ALTER/DROP TABLE, VIEW, INDEXCREATE/ALTER/DROP TABLE, VIEW, INDEX

– Data Control Language (DCL)Data Control Language (DCL)

– GRANT, REVOKEGRANT, REVOKE

Page 3: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Data Manipulation Commands Data Manipulation Commands (DML)(DML)

• SELECTSELECT– Retrieve data from the databaseRetrieve data from the database

• INSERTINSERT– Add new rows to the databaseAdd new rows to the database

• UPDATEUPDATE– Modify data in the databaseModify data in the database

• DELETEDELETE– Remove rows from the databaseRemove rows from the database

Page 4: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SELECTSELECT• SELECT, SELECT, columnscolumns, FROM and , FROM and table namestable names are mandatory. are mandatory.

The rest are optional. The rest are optional.• SELECT *SELECT * will select all columns. will select all columns.

SELECT SELECT col1, col2, …col1, col2, …FROM FROM table1, table2, … table1, table2, … [ WHERE [ WHERE search_condition search_condition

ANDAND search_condition search_condition

OROR search_condition search_condition] ] [ GROUP BY [ GROUP BY group_by_expression group_by_expression ] ] [ HAVING [ HAVING search_condition search_condition ] ] [ ORDER BY [ ORDER BY order_expressionorder_expression [ ASC | DESC ]] [ ASC | DESC ]]

Page 5: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

JoinsJoins

• Joins are queries that select from two or Joins are queries that select from two or more tablesmore tables

• A table may be joined with itself in a self-A table may be joined with itself in a self-joinjoin

• Tables are joined on one or more columns Tables are joined on one or more columns to combine similar rows from eachto combine similar rows from each

• The join is done in the WHERE clause of The join is done in the WHERE clause of the SELECT statementthe SELECT statement

Page 6: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Join - ExampleJoin - ExampleSELECT first_name, last_name, department_nameSELECT first_name, last_name, department_nameFROM employees, departmentsFROM employees, departmentsWHERE employees.department_id = departments.department_id;WHERE employees.department_id = departments.department_id;

FIRST_NAME LAST_NAME DEPARTMENT_NAMEFIRST_NAME LAST_NAME DEPARTMENT_NAME------------ ------------ --------------------------- ------------ ---------------Nancy Greenberg FinanceNancy Greenberg FinanceDaniel Faviet FinanceDaniel Faviet FinanceJohn Chen FinanceJohn Chen FinanceIsmael Sciarra FinanceIsmael Sciarra FinanceJose Manuel Urman FinanceJose Manuel Urman FinanceLuis Popp FinanceLuis Popp FinanceShelley Higgins AccountingShelley Higgins AccountingWilliam Gietz AccountingWilliam Gietz Accounting

Page 7: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Join ExampleJoin Exampleselect a.first_name, a.last_name, b.last_name as select a.first_name, a.last_name, b.last_name as

managermanager

from employees a, employees bfrom employees a, employees b

where a.manager_id = b.employee_idwhere a.manager_id = b.employee_id

order by b.last_name;order by b.last_name;

FIRST_NAME LAST_NAME MANAGERFIRST_NAME LAST_NAME MANAGER

------------ ------------ ------------------------------------- ------------ -------------------------

William Smith CambraultWilliam Smith Cambrault

Elizabeth Bates CambraultElizabeth Bates Cambrault

Sundita Kumar CambraultSundita Kumar Cambrault

Alexander Hunold De HaanAlexander Hunold De Haan

Clara Vishney ErrazurizClara Vishney Errazuriz

Danielle Greene ErrazurizDanielle Greene Errazuriz

Page 8: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SubqueriesSubqueries

• Subquery is a query within a querySubquery is a query within a query• Subqueries are necessary when a condition Subqueries are necessary when a condition

can’t be adequately defined in the WHERE can’t be adequately defined in the WHERE clauseclause

• Example, find employee with the highest Example, find employee with the highest salary:salary:

select first_name, last_name, salaryselect first_name, last_name, salaryfrom employeesfrom employeeswhere salary = where salary = (select max(salary) from employees);(select max(salary) from employees);

Page 9: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Correlated SubqueryCorrelated Subquery

• A A correlated correlated subquery joins the subquery subquery joins the subquery ((inner inner query) with the query) with the outerouter query. query.

• Example, find employees making more than Example, find employees making more than their department average:their department average:

SELECT first_name, last_name, salarySELECT first_name, last_name, salaryFROM employees aFROM employees aWHERE a.salary > (select avg(salary)WHERE a.salary > (select avg(salary) FROM employees e, departments dFROM employees e, departments d WHERE e.department_id = d.department_idWHERE e.department_id = d.department_id AND e.department_id = a.department_idAND e.department_id = a.department_id););

Page 10: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Subquery Exists ExampleSubquery Exists Example

• Combine subquery with EXISTS to Combine subquery with EXISTS to determine conditions of existence or non-determine conditions of existence or non-existenceexistence

• Find all products that have not sold:Find all products that have not sold:

SELECT product_id, product_nameSELECT product_id, product_name

FROM product_information pFROM product_information p

WHERE NOT EXISTS (SELECT order_id WHERE NOT EXISTS (SELECT order_id

FROM order_items oFROM order_items o

WHERE o.product_id = p.product_id);WHERE o.product_id = p.product_id);

Page 11: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Inline ViewInline View

• Oracle provides an optimization to the Oracle provides an optimization to the subquerysubquery

• The query can be included in the FROM The query can be included in the FROM clause as an clause as an inline view.inline view.

SELECT first_name, last_name, salarySELECT first_name, last_name, salaryFROM employees e,FROM employees e,(SELECT avg(salary) avg_sal, d.department_id(SELECT avg(salary) avg_sal, d.department_id FROM departments d, employees eFROM departments d, employees e where d.department_id = e.department_idwhere d.department_id = e.department_id GROUP BY d.department_id) dept_avgGROUP BY d.department_id) dept_avgWHERE e.salary > dept_avg.avg_salWHERE e.salary > dept_avg.avg_salAND e.department_id = dept_avg.department_id;AND e.department_id = dept_avg.department_id;

Page 12: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

• INSERTINSERT

INSERT INTO INSERT INTO table (col1, col2,…) table (col1, col2,…) VALUES (VALUES (val1, val2, …val1, val2, …))

• UPDATEUPDATE

UPDATE UPDATE table table SET SET col1 col1 = = val1, col2 val1, col2 == val2, … val2, …

WHERE [WHERE [conditioncondition]]

• DELETEDELETE

DELETE FROM DELETE FROM table table WHERE [WHERE [conditioncondition]]

Page 13: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

INSERTINSERT

• Two styles: with or without column names:Two styles: with or without column names:• Style 1 – insert values in order of columnsStyle 1 – insert values in order of columns

– as defined by CREATE TABLE – see object browser.as defined by CREATE TABLE – see object browser.– All columns must be included or NULLAll columns must be included or NULL

INSERT INTO item VALUES (21, 'Camoflage Pants', 'C', INSERT INTO item VALUES (21, 'Camoflage Pants', 'C', 'Khaki');'Khaki');

• Style 2 – indicate columns explicitly. Style 2 – indicate columns explicitly. (Not all columns need appear, but must match up with values)(Not all columns need appear, but must match up with values)

INSERT INTO item (itemno, itemname, itemtype) INSERT INTO item (itemno, itemname, itemtype) VALUES (22, 'Hunting Vest', 'C');VALUES (22, 'Hunting Vest', 'C');

Page 14: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

UPDATEUPDATE• Modify data in a tableModify data in a table• UPDATE locks rows during updateUPDATE locks rows during update• Without a WHERE clause, updates ALL rows!Without a WHERE clause, updates ALL rows!

– Give all employees a 10% raise:Give all employees a 10% raise:

UPDATE emp SET empsalary = 1.10*(empsalary);UPDATE emp SET empsalary = 1.10*(empsalary);

– Move all employees in Personnel to Marketing:Move all employees in Personnel to Marketing:

UPDATE emp SET deptname = 'Marketing' UPDATE emp SET deptname = 'Marketing'

WHERE deptname = 'Personnel';WHERE deptname = 'Personnel';

Page 15: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

DELETEDELETE

• Remove entire rows from tableRemove entire rows from table• Again, without WHERE clause, deletes ALL rows!Again, without WHERE clause, deletes ALL rows!

DELETE FROM employees;DELETE FROM employees;

DELETE FROM employeesDELETE FROM employees

WHERE employee_id = 195;WHERE employee_id = 195;

Page 16: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Three options for deleting a tableThree options for deleting a table

1.1. DELETE FROM emp;DELETE FROM emp;

– Safest: Logs the delete transactions in a log file for undoSafest: Logs the delete transactions in a log file for undo

– Does not delete the tableDoes not delete the table

– Does not reclaim spaceDoes not reclaim space

2.2. TRUNCATE TABLE emp;TRUNCATE TABLE emp;

– Faster than delete, does not log transactionsFaster than delete, does not log transactions

– Does not delete the tableDoes not delete the table

– Reclaims spaceReclaims space

3.3. DROP TABLE emp;DROP TABLE emp;

– Fast, does not log deletionsFast, does not log deletions

– Deletes the table as well as the rowsDeletes the table as well as the rows

– Reclaims all spaceReclaims all space

Page 17: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Data Definition Language (DDL)Data Definition Language (DDL)

• CREATECREATE

– TABLETABLE

– VIEWVIEW

– INDEXINDEX• ALTERALTER

– TABLETABLE

– VIEW VIEW

– INDEXINDEX• DROPDROP

– TABLETABLE

– VIEWVIEW

– INDEXINDEX

Page 18: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

CREATE TABLECREATE TABLE

• Creates a Creates a base tablebase table

CREATE TABLE CREATE TABLE table_nametable_name

((col1_name col1_type col1_name col1_type DEFAULT DEFAULT constraints,constraints,

col2_name col2_type col2_name col2_type DEFAULT DEFAULT constraints,constraints,

……,,

PRIMARY KEY (PRIMARY KEY (pk_col1, pk_col2, …pk_col1, pk_col2, …),),

FOREIGN KEY (FOREIGN KEY (fk_col1, fk_col2, …fk_col1, fk_col2, …))

REFERENCES REFERENCES ref_table ref_table ((ref_col1, ref_col2,…ref_col1, ref_col2,…),),

CHECK (CHECK (check conditionscheck conditions));));

Page 19: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ConstraintsConstraints• Primary keyPrimary key CONSTRAINT pk_stock PRIMARY KEY(stkcode)CONSTRAINT pk_stock PRIMARY KEY(stkcode)

• Foreign keyForeign key CONSTRAINT fk_stock_nationCONSTRAINT fk_stock_nation FOREIGN KEY(natcode) REFERENCES nationFOREIGN KEY(natcode) REFERENCES nation

• UniqueUnique CONSTRAINT unq_stock_stkname UNIQUE(stkname)CONSTRAINT unq_stock_stkname UNIQUE(stkname)

• CheckCheck CONSTRAINT item_color_consCONSTRAINT item_color_cons

CHECK (itemcolor IN ('White', 'Brown', 'Khaki'))CHECK (itemcolor IN ('White', 'Brown', 'Khaki'))

Page 20: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

IndexIndex• An index is a sorted list of rows from a An index is a sorted list of rows from a

tabletable• Only a subset of one or more columns is Only a subset of one or more columns is

stored, along with the address of each row.stored, along with the address of each row.• Data retrieval is much faster with an index.Data retrieval is much faster with an index.• Types of indexTypes of index

– B-tree (most common)B-tree (most common)– bitmapbitmap– reversereverse– hashhash– clustercluster

Page 21: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Views - virtual tablesViews - virtual tables

• An imaginary table constructed by the DBMS when required – An imaginary table constructed by the DBMS when required – not a not a base table.base table.

• Only the definition of the view is stored, not the resultOnly the definition of the view is stored, not the result• Usually can’t be updated except in special circumstancesUsually can’t be updated except in special circumstances

CREATE VIEW CREATE VIEW view_nameview_name

((col1, col2, …col1, col2, …))

AS AS select statement;select statement;

Page 22: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Create View exampleCreate View example

CREATE VIEW emp_sal ASCREATE VIEW emp_sal AS

(SELECT first_name, last_name, salary FROM (SELECT first_name, last_name, salary FROM employees);employees);

SELECT * FROM emp_sal;SELECT * FROM emp_sal;

FIRST_NAME LAST_NAME SALARYFIRST_NAME LAST_NAME SALARY

-------------------- ------------------------- ------------------------------ ------------------------- ----------

Donald OConnell 2600Donald OConnell 2600

Douglas Grant 2600Douglas Grant 2600

Jennifer Whalen 4400Jennifer Whalen 4400

Michael Hartstein 13000Michael Hartstein 13000

Pat Fay 6000Pat Fay 6000

Susan Mavris 6500Susan Mavris 6500

Hermann Baer 10000Hermann Baer 10000

Page 23: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ORACLE DATABASE OBJECTSORACLE DATABASE OBJECTS• TableTable• IndexIndex• ViewView• Materialized ViewMaterialized View• SynonymSynonym• SequenceSequence• ProcedureProcedure• FunctionFunction• PackagePackage• TriggerTrigger

Page 24: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

TablesTables• Tables contain Tables contain rowsrows of data with a of data with a columncolumn for for

each datum.each datum.• Each column is of a specific data typeEach column is of a specific data type• Columns without data are Columns without data are NULLNULL• Each table has a Each table has a primary keyprimary key – a column that has – a column that has

unique values that identify rowsunique values that identify rows• Columns may have Columns may have foreign key foreign key references to a references to a

column in another table. The value in the column in another table. The value in the foreign table must exist and be identical.foreign table must exist and be identical.

Page 25: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

DUAL TableDUAL Table• ORACLE provides a special ORACLE provides a special dummy dummy table for table for

using select on data not contained in a table, such using select on data not contained in a table, such as SYSDATEas SYSDATE

SELECT SYSDATE FROM DUAL;SELECT SYSDATE FROM DUAL;

SYSDATESYSDATE------------------08-FEB-0408-FEB-04

SELECT 'This is a test' AS message FROM DUAL;SELECT 'This is a test' AS message FROM DUAL;

MESSAGEMESSAGE----------------------------This is a testThis is a test

Page 26: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

DUAL TableDUAL Table• The DUAL table has just one row with one The DUAL table has just one row with one

column, who’s value is ‘X’;column, who’s value is ‘X’;

SELECT * FROM DUAL;SELECT * FROM DUAL;

DD

--

XX

Page 27: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SYSDATE FunctionSYSDATE Function• The SYSDATE function returns the current date The SYSDATE function returns the current date

and time:and time:

SELECT SYSDATE FROM DUAL;SELECT SYSDATE FROM DUAL;

SYSDATESYSDATE

------------------

08-FEB-0408-FEB-04

Page 28: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ROWNUM ColumnROWNUM Column• Every Oracle query has a Every Oracle query has a pseudopseudo-column -column

named “rownum”named “rownum”• rownum can be used to limit output to a rownum can be used to limit output to a

certain number of rowscertain number of rowsSELECT * FROM customersSELECT * FROM customersWHERE rownum < 5;WHERE rownum < 5;

CUST_ID CUST_FIRST_NAME CUST_LAST_NAME CUST_ID CUST_FIRST_NAME CUST_LAST_NAME ---------- -------------------- ------------------------------ -------------------- -------------------- 10 Abigail Kessel 10 Abigail Kessel 20 Abner Everett 20 Abner Everett 30 Abraham Odenwalld 30 Abraham Odenwalld 40 Absolom Sampson 40 Absolom Sampson

4 rows selected.4 rows selected.

Page 29: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Materialized ViewsMaterialized Views

• Oracle has an object called a Oracle has an object called a materialized materialized viewview. It is a view that actually contains . It is a view that actually contains data.data.

• Data is updated periodicallyData is updated periodically• Useful for Useful for derived dataderived data, such as statistical , such as statistical

datadata

Page 30: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SYNONYMSSYNONYMS• Synonyms are aliases for objects, a name Synonyms are aliases for objects, a name

that can be referred to without the schema that can be referred to without the schema name.name.

• Synonyms are public or privateSynonyms are public or private– public = all users can use itpublic = all users can use it– private = only the owner can use itprivate = only the owner can use it– Example:Example:CREATE PUBLIC SYNONYM employees FOR employees;CREATE PUBLIC SYNONYM employees FOR employees;

– Now anyone can select from the employees Now anyone can select from the employees tabletable

SELECT * FROM employees;SELECT * FROM employees;

Page 31: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SequenceSequence• A sequence generates a sequential integer A sequence generates a sequential integer

valuevalue• Note – sequence numbers may be Note – sequence numbers may be skipped.skipped.• Useful for serial numbersUseful for serial numbers

CREATE SEQUENCE customers_seq START WITH 1000 CREATE SEQUENCE customers_seq START WITH 1000 INCREMENT BY 1INCREMENT BY 1;;

• Use nextval to get the next incremental Use nextval to get the next incremental numbernumber

INSERT INTO employees VALUES (employees_seq.nextval, INSERT INTO employees VALUES (employees_seq.nextval, 'John', 'Doe', 'jdoe', '555-1212', TO_DATE(SYSDATE), 'John', 'Doe', 'jdoe', '555-1212', TO_DATE(SYSDATE), 'PU_CLERK', 2500, null, null, 30); 'PU_CLERK', 2500, null, null, 30);

Page 32: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SCHEMASCHEMA• Generally: A data model diagramGenerally: A data model diagram• Oracle: a collection of database objects Oracle: a collection of database objects

belonging to a single userbelonging to a single user• The schema has the name of the ownerThe schema has the name of the owner• Normally, only the owner has access to the Normally, only the owner has access to the

schemaschema• Other users can access using the user name Other users can access using the user name

prefix if they have been granted privileges:prefix if they have been granted privileges:select * from hr.employees;select * from hr.employees;

Page 33: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Miscellaneous SQL notesMiscellaneous SQL notes• In Oracle, SQL statements are terminated In Oracle, SQL statements are terminated

with a semi-colon ;with a semi-colon ;• By convention, uppercase SQL reserved By convention, uppercase SQL reserved

words and lowercase data-specific words words and lowercase data-specific words ((not mandatorynot mandatory):):SELECT last_name FROM employees SELECT last_name FROM employees

WHERE employee_id = 197;WHERE employee_id = 197;

• Object names are not case-sensitive, but Object names are not case-sensitive, but string literals are:string literals are:SELECT employee_id FROM EMPLOYEESSELECT employee_id FROM EMPLOYEES

WHERE last_name = ‘Smith’;WHERE last_name = ‘Smith’;

Page 34: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ORACLE DATATYPESORACLE DATATYPES

CHAR(size)CHAR(size) Fixed-length character stringFixed-length character string

VARCHAR2(size)VARCHAR2(size) Variable-length character stringVariable-length character string

NUMBER(p,s)NUMBER(p,s) Floating point number with Floating point number with precision = p and scale = sprecision = p and scale = s

DATEDATE A date and timeA date and time

CLOBCLOB Large character string, up to 4GBLarge character string, up to 4GB

BLOBBLOB Large binary object, up to 4GBLarge binary object, up to 4GB

BFILEBFILE Pointer to an external filePointer to an external file

ROWIDROWID Internal row addressInternal row address

Page 35: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ORACLE DATATYPES - NUMBERORACLE DATATYPES - NUMBER

• NUMBER(p,s)NUMBER(p,s)– precision is number of digits to storeprecision is number of digits to store– scale is number of digits to the scale is number of digits to the rightright of the of the

decimal placedecimal place– p is an integer between 1 and 38 (inclusive)p is an integer between 1 and 38 (inclusive)– s is an integer between -84 and 127 (inclusive)s is an integer between -84 and 127 (inclusive)– s = 0 is a decimal integers = 0 is a decimal integer– negative s pads zeroes to the left of the decimal negative s pads zeroes to the left of the decimal

pointpoint– specifying neither p nor s assumes maximum specifying neither p nor s assumes maximum

valuesvalues

Page 36: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

NUMBER EXAMPLESNUMBER EXAMPLES

Actual DataActual Data Specified asSpecified as Stored asStored as

1234567.891234567.89 NUMBERNUMBER 1234567.891234567.89

NUMBER(9)NUMBER(9) 12345681234568

NUMBER(9,2)NUMBER(9,2) 1234567.891234567.89

NUMBER(9,1)NUMBER(9,1) 1234567.91234567.9

NUMBER(6,2)NUMBER(6,2) Exceeds precisionExceeds precision

NUMBER(9, -2)NUMBER(9, -2) 12346001234600

.00123456.00123456 NUMBER(6,8)NUMBER(6,8) .00123456.00123456

NUMBER(6,6)NUMBER(6,6) .001235.001235

NUMBER(4,6)NUMBER(4,6) Exceeds precisionExceeds precision

Page 37: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ORACLE DATEORACLE DATE

• Dates and times are stored internally as a Dates and times are stored internally as a number in Oraclenumber in Oracle

• To insert or select a date or time in a way To insert or select a date or time in a way that is readable, it has to be converted to or that is readable, it has to be converted to or from a string using a from a string using a date formatdate format..– Example: 09-FEB-2004 is in date format DD-Example: 09-FEB-2004 is in date format DD-

MON-YYYYMON-YYYY

Page 38: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ORACLE DATEORACLE DATE

• You can insert a date as a literal stringYou can insert a date as a literal string– Use date format DD-MON-YYYY (day-month-Use date format DD-MON-YYYY (day-month-

year)year)– Can’t insert the time this wayCan’t insert the time this way– Time will be 12:00:00 amTime will be 12:00:00 am

INSERT INTO employees (employee_id, first_name, INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id)last_name, email, hire_date, job_id)

VALUES (208, 'Brown', 'John', '[email protected]', VALUES (208, 'Brown', 'John', '[email protected]', '28-JAN-2004', 'SA_REP');'28-JAN-2004', 'SA_REP');

Page 39: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ORACLE DATEORACLE DATE

• DATE type includes date and time information.DATE type includes date and time information.• To insert a date, use the TO_DATE function and To insert a date, use the TO_DATE function and

specify the date, time and specify the date, time and date formatdate format as strings: as strings:

TO_DATE(’08-FEB-2004’, ‘DD-MON-YYYY’)TO_DATE(’08-FEB-2004’, ‘DD-MON-YYYY’)

TO_DATE(’08-FEB-2004 13:44:00’, ‘DD-MON-YYYY TO_DATE(’08-FEB-2004 13:44:00’, ‘DD-MON-YYYY HH24:MI:SS’)HH24:MI:SS’)

insert into employees (employee_id, first_name, insert into employees (employee_id, first_name, last_name, email, hire_date, job_id)last_name, email, hire_date, job_id)

values (207, 'Brown', 'John', '[email protected]', values (207, 'Brown', 'John', '[email protected]', TO_DATE('27-JAN-2004', 'DD-MON-YYYY'), 'SA_REP');TO_DATE('27-JAN-2004', 'DD-MON-YYYY'), 'SA_REP');

Page 40: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

ORACLE DATEORACLE DATE

• Likewise, when selecting a date from a Likewise, when selecting a date from a table, you can display the date in different table, you can display the date in different formats using the TO_CHAR function.formats using the TO_CHAR function.

select TO_CHAR(SYSDATE, 'DD/MM/YY HH:MI:SS PM') as select TO_CHAR(SYSDATE, 'DD/MM/YY HH:MI:SS PM') as "current time" FROM DUAL"current time" FROM DUAL

current timecurrent time

----------------------------------------

08/02/04 02:37:05 PM08/02/04 02:37:05 PM

Page 41: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

DATE FORMAT ELEMENTSDATE FORMAT ELEMENTSElementElement MeaningMeaning

DDDD Two-digit dayTwo-digit day

DAYDAY Day of week spelled outDay of week spelled out

MMMM Two-digit monthTwo-digit month

MONMON Three-character month, i.e. JANThree-character month, i.e. JAN

MONTHMONTH Month spelled out, i.e. JanuaryMonth spelled out, i.e. January

YYYY Two-digit year – beware: 98 = 2098Two-digit year – beware: 98 = 2098

YYYYYYYY Four-digit year – safest!Four-digit year – safest!

RRRR Two-digit year in 20Two-digit year in 20th th century, i.e. 98 = 1998century, i.e. 98 = 1998

HHHH Hour, 11 am and 11 pm are the sameHour, 11 am and 11 pm are the same

HH24HH24 Military hour, i.e. 14:00 = 2pmMilitary hour, i.e. 14:00 = 2pm

MIMI MinutesMinutes

SSSS SecondsSeconds

PMPM Show PM or AM for HHShow PM or AM for HH

See Table 8-6 on page 224 of textbook for complete listing

Page 42: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

DATE FORMAT ELEMENTSDATE FORMAT ELEMENTS• ExamplesExamples

SELECT TO_CHAR(SYSDATE, 'DAY MONTH DD, YYYY SELECT TO_CHAR(SYSDATE, 'DAY MONTH DD, YYYY HH:MI:SS PM') AS "current time" FROM DUAL;HH:MI:SS PM') AS "current time" FROM DUAL;

current timecurrent time--------------------------------------------------------------------------------SUNDAY FEBRUARY 08, 2004 04:38:05 PMSUNDAY FEBRUARY 08, 2004 04:38:05 PM

SELECT TO_CHAR(SYSDATE, 'MM+DD+RR HH24:MI:SS') SELECT TO_CHAR(SYSDATE, 'MM+DD+RR HH24:MI:SS') AS "current time" FROM DUAL;AS "current time" FROM DUAL;

current timecurrent time----------------------------------02+08+04 16:40:1602+08+04 16:40:16

Page 43: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

Oracle Date FunctionsOracle Date Functions• TO_CHAR converts date to a character stringTO_CHAR converts date to a character string• TO_DATE converts a character string to a dateTO_DATE converts a character string to a date• TRUNC returns date with no time (time is set to TRUNC returns date with no time (time is set to

00:00:00. Use this when you want to compare the 00:00:00. Use this when you want to compare the date and not the timedate and not the time

• ADD_MONTHS, returns date incremented by a ADD_MONTHS, returns date incremented by a specified number of montsspecified number of monts

• Addition: adding integers to a date adds that many Addition: adding integers to a date adds that many days to the datedays to the date

See Table 8-5 on page 220 for complete listSee Table 8-5 on page 220 for complete list

Page 44: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

insert into emp insert into emp

(first_name, last_name, email, job_id, hire_date)(first_name, last_name, email, job_id, hire_date)

valuesvalues

('Mark', 'Freeman', '[email protected]', 50, '06-OCT-('Mark', 'Freeman', '[email protected]', 50, '06-OCT-2004');2004');

1 row created.1 row created.

SELECT * FROM emp WHERE hire_date = SYSDATE;SELECT * FROM emp WHERE hire_date = SYSDATE;

no rows selectedno rows selected

SELECT * FROM emp WHERE hire_date = trunc(SYSDATE);SELECT * FROM emp WHERE hire_date = trunc(SYSDATE);

FIRST_NAME LAST_NAME…FIRST_NAME LAST_NAME…

-------------------- --------------------------------------------- -------------------------

Mark Freeman…Mark Freeman…

1 row selected.1 row selected.

TRUNC example

Page 45: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SELECT SYSDATE FROM DUAL;SELECT SYSDATE FROM DUAL;

SYSDATESYSDATE

------------------

06-OCT-0406-OCT-04

SELECT ADD_MONTHS(SYSDATE, 3) FROM DUAL;SELECT ADD_MONTHS(SYSDATE, 3) FROM DUAL;

ADD_MONTHADD_MONTH

------------------

06-JAN-0506-JAN-05

SELECT SYSDATE + 7 AS "Next Week" FROM DUAL;SELECT SYSDATE + 7 AS "Next Week" FROM DUAL;

Next WeekNext Week

------------------

13-OCT-0413-OCT-04

Date ArithmeticExamples

Page 46: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

PL/SQL ProceduresPL/SQL Procedures• PL/SQL stands for PL/SQL stands for procedural languageprocedural language..• A A procedureprocedures is a group of SQL statements s is a group of SQL statements

with programming logicwith programming logic• A A functionfunction is a procedure that returns a is a procedure that returns a

valuevalue• A A triggertrigger is a procedure that fires when a is a procedure that fires when a

database event occurs, such as an insert or database event occurs, such as an insert or updateupdate

• A A packagepackage is a named group of procedures is a named group of procedures and functionsand functions

Page 47: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*PlusSQL*Plus• Oracle’s command-line SQL interpreterOracle’s command-line SQL interpreter• Two kinds of commandsTwo kinds of commands

– SQL commandsSQL commands– SQL*Plus commandsSQL*Plus commands

• SQL*Plus commands are special formatting SQL*Plus commands are special formatting and control commands that are not part of and control commands that are not part of SQLSQL

• SQL*Plus commands are not case-sensitive SQL*Plus commands are not case-sensitive and can be abbreviatedand can be abbreviated

Page 48: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*Plus TransactionsSQL*Plus Transactions• By default SQL*Plus does not run in By default SQL*Plus does not run in autocommitautocommit

mode.mode.• DELETE’s, UPDATE’s and INSERT’s do not DELETE’s, UPDATE’s and INSERT’s do not

become permanent until a COMMIT statement is become permanent until a COMMIT statement is explicitely executedexplicitely executed

• This means you can use ROLLBACK to undo This means you can use ROLLBACK to undo changeschanges

• If you end a session with out committing, Oracle If you end a session with out committing, Oracle will automatically rollback your changeswill automatically rollback your changes

• Autocommit can be enaabled with the Autocommit can be enaabled with the SET SET

AUTOCOMMIT ONAUTOCOMMIT ON comand comand

Page 49: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*Plus Commands - DESCRIBESQL*Plus Commands - DESCRIBE

• DESCRIBEDESCRIBE– Lists the description of an Oracle objectLists the description of an Oracle object– Can be abbreviated as ‘DESC’Can be abbreviated as ‘DESC’

desc move_ccuserdesc move_ccuser

PROCEDURE move_ccuserPROCEDURE move_ccuser

Argument Name Type In/Out Default?Argument Name Type In/Out Default?

-------------- ----------------------- ------ ---------------------- ----------------------- ------ --------

CCUSER VARCHAR2 INCCUSER VARCHAR2 IN

TSPACE VARCHAR2 INTSPACE VARCHAR2 IN

Page 50: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*Plus Commands - DESCRIBESQL*Plus Commands - DESCRIBE

DESCRIBE employeesDESCRIBE employees

Name Null? TypeName Null? Type ---------------- -------- ----------------------------- -------- ------------- EMPLOYEE_ID NOT NULL NUMBER(6)EMPLOYEE_ID NOT NULL NUMBER(6) FIRST_NAME VARCHAR2(20)FIRST_NAME VARCHAR2(20) LAST_NAME NOT NULL VARCHAR2(25)LAST_NAME NOT NULL VARCHAR2(25) EMAIL NOT NULL VARCHAR2(25)EMAIL NOT NULL VARCHAR2(25) PHONE_NUMBER VARCHAR2(20)PHONE_NUMBER VARCHAR2(20) HIRE_DATE NOT NULL DATEHIRE_DATE NOT NULL DATE JOB_ID NOT NULL VARCHAR2(10)JOB_ID NOT NULL VARCHAR2(10) SALARY NUMBER(8,2)SALARY NUMBER(8,2) COMMISSION_PCT NUMBER(2,2)COMMISSION_PCT NUMBER(2,2) MANAGER_ID NUMBER(6)MANAGER_ID NUMBER(6) DEPARTMENT_ID NUMBER(4)DEPARTMENT_ID NUMBER(4)

Page 51: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*Plus Commands - spoolSQL*Plus Commands - spool

• spool opens a file and sends all output to the spool opens a file and sends all output to the filefile

• Filename cannot contain spacesFilename cannot contain spacesspool h:\test.outspool h:\test.out

• Turn off with the Turn off with the spool offspool off commandcommand

Page 52: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*Plus Commands - SETSQL*Plus Commands - SET• The SET command sets certain parameters The SET command sets certain parameters

affecting the output displayaffecting the output display• SET ECHO [ON/OFF]SET ECHO [ON/OFF]

– Controls display of SQL commands in reportsControls display of SQL commands in reports• SET HEADING [ON/OFF]SET HEADING [ON/OFF]

– Control display of column headingsControl display of column headings• SET LINESIZE SET LINESIZE intint

– Width of a line before wrappingWidth of a line before wrapping• SET PAGESIZE SET PAGESIZE intint

– Number of lines to print between headersNumber of lines to print between headers– Set to 0 turns off all heading and page breaksSet to 0 turns off all heading and page breaks

• SET UNDERLINE SET UNDERLINE charchar– Sets the underline character at column headings to Sets the underline character at column headings to charchar

Page 53: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*Plus Commands - SHOWSQL*Plus Commands - SHOW• The SHOW command displays parameter settingsThe SHOW command displays parameter settings• SHOW SGASHOW SGA

– Shows memory configurationShows memory configuration

• SHOW PARAMETER SHOW PARAMETER parameter nameparameter name– Shows setting of an init.ora parameterShows setting of an init.ora parameter

• SHOW ERRORSHOW ERROR– Displays PL/SQL error messagesDisplays PL/SQL error messages

• SHOW USERSHOW USER• SHOW SPOOLSHOW SPOOL• SHOW ALLSHOW ALL

Page 54: Database Administration ISQA 436 SQL Review, Oracle Objects and Data Types, SQL*Plus.

SQL*Plus Commands - HELPSQL*Plus Commands - HELP• HELP HELP topic topic displays information about other commandsdisplays information about other commands

help spoolhelp spool

SPOOLSPOOL ----------

Stores query results in an operating system Stores query results in an operating system file, or sends thefile, or sends the

file to a printer.file to a printer. In iSQL*Plus, output can be directed to a In iSQL*Plus, output can be directed to a file.file.

SPO[OL] [file_name[.ext] | OFF | OUT]SPO[OL] [file_name[.ext] | OFF | OUT]

Not available in iSQL*PlusNot available in iSQL*Plus


Recommended