Header image  
ORACLE & SQL  
line decor
  HOME :: BUSINESS :: COMPUTING :: LIFESTYLE :: PASTIME ::SCIENCES ::
line decor
   
 more oracle

    To fix a lost DBA Passwords:

    (SYS/SYSTEM) you need to connect to the linux
    system as the user with the "dba" group , i.e "oracle" and :


    version 8i use "sqlplus internal" then "alter user sys identified by xyz"


    version 9i use "sqlplus /nolog" then "connect as sysdba" then "alter user
    sys identified by xyz"

    Default Usernames and Passwords:

  • Username: SYS
    Password: change_on_install
    Created: when installing Oracle
    Description: (From Oracle Administrator's Guide) "All of the base tables and views for the database's data dictionary are stored in the schema SYS. These base tables and views are critical for the operation of Oracle. To maintain the integrity of the data dictionary, tables in the SYS schema are manipulated only by Oracle; they should never be modified by any user or database administrator, and no one should create any tables in the schema of the user SYS."
    To conclude that you should work with this username with appropriate respect and make experiments not on production systems.
  • Username: SYSTEM
    Password: manager
    Created: when installing Oracle
    Description: (From Oracle Administrator's Guide) "The SYSTEM username creates additional tables and views that display administrative information, and internal tables and views used by Oracle tools. Never create in the SYSTEM schema tables of interest to individual users."
    SYSTEM is a little bit "weaker" user than SYS, for example, it has no access to so called X$ tables (the very internal structure tables of Oracle).
    Although in real life you may be in a situation when some product or whatever want to create objects in above mentioned user's schemas. Be flexible, don't sacriface a product only because it will create some objects in SYS or SYSTEM schema.
  • Username: SCOTT
    Password: tiger
    Created: ???
    Description: Well known and often referenced sample schema. Every people should be heard about magical emp and dept tables. If You are a soooo big newbie or sooooooo careless and don't know how it looks like, here it is! To be more serious although it doesn't follow more or less strict naming rules, VERY MANY examples in Oracle docs and not only are based on this schema so You should know it!
  • Username: OUTLN
    Password: outln
    Created: when installing Oracle8i
    Description: (From Oracle8i Migration Release 3 (8.1.7)) "Oracle8i adds the OUTLN user schema to support Plan Stability. The OUTLN user acts as a place to centrally manage metadata associated with stored outlines."
    This user has DBA role. It is used for plan stability ie. to keep the same execution plans for the same queries even if your system configuration or statistics changes. Execution plans will be the same in different Oracle releases with different optimizers.
    Read more in Oracle8i Designing and Tuning for Performance, Chapter 10, Using Plan Stability.
  • Username: DBSNMP
    Password: dbsnmp
    Created: ???
    Description: Supports Oracle SNMP (Simple Network Management Protocol).
    Read more in Oracle SNMP Support Reference Guide Release 8.1.7
  • Username: TRACESVR
    Password: trace
    Created: automatically on most platforms, NOT NT.
    Description: Supports Oracle Trace.
    (From Oracle Trace User's Guide) "Use Oracle Trace to collect a wide variety of data, such as performance statistics, diagnostic data, system resource usage, and business transaction details."
    Read more in Oracle Trace User's Guide
  • Username: ORDSYS
    Password: ordsys
    Created: ???
    Description: Supports Oracle8i Time Series. (From Oracle8i Time Series User's Guide Release 8.1.5) "Oracle8i Time Series (in previous releases called the Oracle8 Time Series Cartridge) is an extension to Oracle8i that provides storage and retrieval of timestamped data through object types. Oracle8i Time Series is a building block for applications rather than being an end-user application in itself. It consists of data types along with related functions for managing and processing time series data."
    Read more in Oracle8i Time Series User's Guide Release 8.1.5
  • Username: ORDPLUGINS
    Password: ordplugins
    Created: ???
    Description: Supports Oracle interMedia. (From Oracle interMedia Audio, Image, and Video User's Guide and Reference Release 8.1.6) "Oracle interMedia is a single product that enables Oracle8i to store, manage, and retrieve text, documents, geographic location information, images, audio, and video in an integrated fashion with other enterprise information. Oracle interMedia extends Oracle8i reliability, availability, and data management to text and multimedia content in Internet, electronic commerce, and media-rich applications as well as online Internet-based geocoding services for locator applications."
    Read more in Oracle interMedia Audio, Image, and Video User's Guide and Reference Release 8.1.6
  • Username: MDSYS
    Password: mdsys
    Created: ???
    Description: Supports Oracle Spatial. (From Oracle Spatial User's Guide and Reference Release 8.1.7) "Oracle Spatial is an integrated set of functions and procedures that enables spatial data to be stored, accessed, and analyzed quickly and efficiently in an Oracle8i database. [..] The spatial attribute of a spatial feature is the geometric representation of its shape in some coordinate space. This is referred to as its geometry."
    Read more in Oracle Spatial User's Guide and Reference Release 8.1.7
  • Username: OAS_PUBLIC
    Password: manager
    Created: ???
    Description: Supports part of Oracle Application Server. Owner of PL/SQL Web Toolkit
    Read more in Oracle Application Server, Release 4.0.8.2
  • Username: WEBSYS
    Password: manager
    Created: ???
    Description: Supports part of Oracle Application Server. Owner of content service database objects
    Read more in Oracle Application Server, Release 4.0.8.2
  • Username: CTXSYS
    Password: ctxsys
    Created: ???
    Description: Supports Oracle ConText Cartridge
    (From Oracle8 ConText Cartridge QuickStart Release 2.3) "Oracle8 ConText Cartridge provides powerful search, retrieval, and viewing capabilities for text stored in an Oracle8 database. In addition, ConText provides advanced linguistic processing of English-language text."
    Read more in Oracle8 ConText Cartridge QuickStart Release 2.3

Logon: sqlplus sys/change_on_install

create user, give access to connect, and give access to create tables

create user oscar identified by oscar;

grant connect to oscar;

grant resource to oscar;

Read tables from another schema/user:

SELECT COUNT(*) FROM haggis.tat

Change a default Schema:

ALTER SESSION SET CURRENT_SCHEMA = scott;

Find another process and kill it.

SELECT sid, serial#, username,
TO_CHAR(logon_time,'Month dd hh24:mi:ss')
FROM sys.v_$session;

ALTER SYSTEM KILL SESSION '12,33'
-- 12,33 is the sid and serial#

Set a time out: The user scott is limited to 5 minute per connection. After this time he will be logged out, if he is running a query it will be abandoned.

ALTER SYSTEM SET RESOURCE_LIMIT=TRUE;
CREATE PROFILE oscarprofile
LIMIT CONNECT_TIME 5;


ALTER USER scott PROFILE oscarprofile;

Find my User UID

SELECT user, uid FROM dual


copy from elec_mgmt/elecmgmt@stockroom2 to shop_mgmt/shopmgmt@stockroom2 create shop_mgmt.temp
using select * from elec_mgmt.orders;

 

copy from sde_user/(password for whiterim)@WHITERIM -
to sde_user/(password for scooter)@scooter -(this line is optional)
create HYDNOSD -
using -
select * from SDE_USER.HYDNOSD;

 

copy from scott/tiger @ORCL92 -
to scott/tiger @ORCL92-
create new_emp –
using select * from emp;

 

ORACLE CHEAT SHEET

Written by

This is not meant to be a tutorial, and is not even yet complete, but merely meant to be a way to quickly find information needed to do the most common DBMS specific tasks. Eventually I hope to have an SQL cheat sheet that, with this, will cover Oracle basics.

DEFINITIONS(SPECIFIC TO ORACLE!!!!)
 

CLUSTERED INDEX

The indexes of several related tables physically tied together. This improves space and speed efficiency when the tables are generally used together. If the tables aren't generally used together, it may be a good idea to keep them separate.

DATABASE

An instance of the SQL server engine. May contain several schemas! (normally called an instance or a server)

SCHEMA

A collection of tables (normally called a database)

SYNONYM

An object that redirects reference to another object.  An object in database A might look like a table, but refer data inserted into it to a table in database B.  THAT table, in database a, is a synonym.

TABLE SPACE

A file that contains the objects defined.

 

ARCHITECHTURE

PAGE SIZE 8K
PHYSICAL STRUCTURESEPARATE FILES called TABLE SPACE.
BASED ON
MINIMUM SIZE
MAXIMUM SIZE
ALLOCATION
PAGE SPANNING
MINIMUM SIZE OF OBJECT
MINIMUM SIZE OF TABLE
MAXIMUM SIZE OF TABLE

HIERARCHY OF COLLECTIONS

DATABASE&SCHEMA.TABLE

SCHEMA.TABLE

TABLE

This means that if you are in the NUMONE schema, and want to insert values into NUMONEM from the NUMTWOJ table in the NUMTWO schema on the JUPITER database, you can type:

insert into NUMONEN select * from JUPITER&NUMTWO.NUMTWOJ

SHOW THE TABLES DEFINITION

desc TABLE_NAME;

SHOW THE NAMES OF TABLES MATCHING A PATTERN

select distinct table_name from all_tables where table_name like '%PATTERN%';

SHOW ALL OBJECT NAMES MATCHING A PATTERN

select distinct object_name from all_objects where object_name like '%PATTERN%';

SHOW ALL CONSTRAINTS FOR TABLE NAMES MATCHING A PATTERN

select * from all_CONS_COLUMNS where table_name like '%PATTERN%';

SHOW ALL STORED PROCEDURES/PACKAGES THAT MATCH A PATTERN

select distinct name, type from user_source where name like '%PATTERN%';

SHOW THE TEXT FOR A GIVEN STORED PROCEDURE/PACKAGE

select text from user_source where name='PROCEDURE NAME';

JOIN TWO ALPHA FIELDS

Ok, somebody should have realized that most languages that use || (such as C and PERL and JAVA) define it as meaning OR. Oh well, here it means concatenate.

||

ENSURE A NULL FIELD IS RETURNED AS 0

nvl(FIELD_NAME)

READ 10 ROWS FROM A TABLE

Unfortunately, nobody bothered to include a command to do this in SQL.  Oracle has a neat way of doing this and similar things!  They simply have several "psuedo columns".

select * from TABLE_NAME where rownum<=10

COPY THE STRUCTURE AND DATA OF A TABLE

create TABLE_NAME as select ...

Oh, you didn't want to copy the data as well?  Simply add a where clause onto the create stateent that is always false!

EXECUTE AN SQL BATCH FILE

@FILE_NAME

SQL*PLUS COMMANDS

Everything up to this point has been commands that would run under the Oracle server.  The following ones run only under SQL*PLUS.  SQL*PLUS is Oracles interactive SQL client.

Commands given in SQL*PLUS are treated as transactions, like in most similar products.  These transactions, unlike most other products, are not committed, except under certain circumstances.  Until it is commited, or rolled back, the session will treat the data as if it HAD been committed.

COMMIT A COMMANDS RESULTS

COMMIT

ROLLBACK A COMMANDS RESULTS

ROLLBACK

SPOOL OUTPUT TO A FILE

spool FILENAME

COMMANDS TO LOG/SPOOL....

spool off

TURN THE HEADING OFF/ON

set heading OFFON

EDIT BUFFER

This is almost as bad as the || discrepancy. Oracle asks you to end lines with ";" everywhere but in the editor. In the editor it will create an error condition. In the editor, you must place a "/" at the end of the batch instead.

ed

RUN BUFFER

When you edit the query, you edit what is in the buffer. The "/" command can be used as much as you want to run want is in the buffer.

/

Files in an Oracle Database

  • Data Files - the datafiles hold the tables, indexes, views, and procedures and other objects contained in the database.
     
  • Control Files - the control files hold the information about file names needed for the database to startup and shutdown.
     
  • Redo Log Files - these hold the record of all completed transactions in the database.

 
 
 


What is a Database backup?

A copy of all the files necssary to reconstruct the database in the case of a physical or media failure.  A complete database backup will be able to reconstruct the data files, control files and redo logs of a database.

Oracle database recovery will result in all files in the database restored to the same point in time.

In our DB2 environment we are able to recover at a tablespace level and because we have chosen to create only one table in a tablespace we are able to recover at the table level.  Tablespaces in the DB2 database may be restored to different points in time.
 

Table of Contents
 
 


Types of Backup

There are two kinds of database backups available to us physical backups and logical backups.

Physical Backup is an actual physical copy of the files of the database copied from one location to another.

Logical Backup is a copy of the data in the database but not a copy of the physical files.



 

Cold Backup

A cold backup is a physical backup.

During a cold backup the database is closed and not available to users.  All files of the database are copied (image copy).  The datafiles do not change during the copy so the database is in sync upon restore.
 

Used when:

Service level allows for some down time for backup



 

Hot Backup

A hot backup is a physical backup.  In a hot backup the database remains open and available to users. All files of the database are copied (image copy).  There may be changes to the database as the copy is made and so all log files of changes being made during the backup must be saved too.  Upon a restore, the changes in the log files are reapplied to bring the database in sync.

Used when:

A full backup of a database is needed
Service level allows no down time for the backup


Logical Backup

A logical backup is an extract of the database.  All SQL statements to create the objects and all SQL statements to populate the objects are included in the extract.  Oracle provides a utility export, to create the extract.   A partner utility, import, is used to bring the data back into the database.

A logical backup can be done at the table, schema(or proxy owner), or database level.  That is, we can extract only a list of specified tables, a list of specified schemas or the full database.

Used to:

Move or archive a database
Move or archive a table(s)
Move or archive a schema(s)
Verify the structures in the database

 
 

Table of Contents


Application Backup Options

 
 DBA's have the responsibility of restoring the database in the case of a media failure.  Oracle backups that we do now achieve that result.

Application Level Backup and Recovery may also be needed.  This kind of recovery must be planned for by the application developer and the DBA together.   Work with the DBA and have a plan for this from the beginning when designing your application.

Why application backups?

    • To recover data after running an errant batch program.

 

    • To recover data after user error.

What are the options?


Options:
 

Export/Import Utility

Export can be run for :
 

    • A list of tables
    • All tables owned by a certain oracle user id (proxy schema)
    • The entire database.

The export would be done before a batch job is run.  If batch job fails or is incorrect, table data can be imported from the export.
 

    • Data is restored to point in time when the export was taken
    • Transactions completed after that time are lost
    • Data integrity may be compromised if there is a relationship with a table or other system (DB2, other Oracle database) that is not restored to the same point in time.

Example 1

 
 
 
 
 
 
 
 
 


Application Logic

Design your application to allow for reversing destructive functions.

  • Use an effective date method of deleting records
  • Use a status flag on a record

Design your batch programs to allow for restarting in an elegant fashion.

  • Log the changes you've made during a batch run.
  • Use restart logic in a batch program.
     
     
     
     
     
     
     
     
     
     
     
     

Using a Separate Oracle Database for a System

In some cases a system may warrant its own separate database.

Evolution of DRMT's Thinking:

    • DRMT initially thought all systems would share one Oracle production database.
    • Then Oracle Financials came along.  That was put in a separate database, to ease backup, recovery and upgrade issues.  The same happened for PeopleSoft, for UAI, for Clarify, etc.
    • Now we think that vendor designed applications go in a separate database, but the ones that we build share a database.
    • Then we started thinking through the issues of application level recovery and
    • Realize that some DoIT developed applications will have a separate database too.

 
Points to Consider:

    • Database can be restored to any point in time
    • Additional resources in disk and server memory will be used
    • Sharing data with tables in other databases becomes more complicated than having all tables in one database.
    • Transactions completed after that time are lost
    • Data integrity can not be maintained across databases with Oracle constraints.

 
 
 


Questions  and Answers

1. Why does an Oracle database have to be recovered all together to the same point in time?
 A:  This is just the way it is in Oracle.  The referential integrity in a relational database can only be guaranteed if the entire database is consistant in relation to the last committed transaction.

2. How long does it take to do a forward recovery?
A: It depends on how much we lost and how long since the last physical backup.  The first step is to restore the last backup of what was lost.  If it's a 2GB file and our backup is on ADSM we have to
wait first for that to be restored (maybe 1 hour or more?) then we apply transaction logs to redo transactions.  If the backup is on disk, then the restore is quicker.  Our goal is to minimize the time of recovery.  For any production system we want to keep unplanned down time to under 2 hours.

3. Do we use hot or cold backup for production databases?
A: UWP1 is now using cold.  ISIS is now using cold.  Wiscworld email database used hot.  Clarify uses hot. It depends on the service level requirements.

4. Does a logical backup contain the data as well as the SQL needed to recreate the objects?
A:  Yes.  Both the DDL (data definition language, ie: CREATE TABLE etc.) to create the objects and the SQL to populate the object with data is included in an export.

5. Are there tools to see what integrity constraints and other relationships exisit between tables?
A: The Oracle system catalogs can give us some information.  However, there may be systems that you don't know about using your data.  This is not necessarily a relationship that's stored in the database.

6. Does PoepleSoft support batch programs undoing what they did?
A: PeopleSoft does use effective dates in most of their records.  I'm not familiar with specifics on the programming styles of batch programs in the system.   That's something we all have to learn.

  Table of Contents



 

Example 1
 

1. Export of Table A and Table B is taken at 10:30pm.

2. Batch job to update Table A and Table B is run at 11:00 pm.

3.  Users arrive at 7am and begin doing other daily updates and changes to system.

4. Users report problem with database at 8am.

5. Table A and Table B are restored from export at 8:30am.  Data is returned to its state as of 10:30pm the previous night.

6. Users must redo work between 7 and 8.  Batch job must be fixed and rerun.

Cheats

 

http://radio.weblogs.com/0128037/stories/2003/10/21/oracleScmInstallationCheatSheet.html

http://www.osmosislatina.com/oracle/part1.htm

http://www.osmosislatina.com/oracle/index.htm

http://home.earthlink.net/~adamshalon/oracle_password_cracker/

http://www.informit.com/isapi/product_id~%7B9AF62809-408D-401A-9144-B0A695B72424%7D/element_id~%7BAF8F47AB-B8E8-46DB-846D-97CF8155304D%7D/st~%7B340C91CD-6221-4982-8F32-4A0A9A8CF080%7D/content/articlex.asp

 


Pre-requisites: The copy is between 2 machines, both have to be on the same OS and have to have exactly the same database version installed.

1. Make sure the database you want to copy was closed with a SHUTDOWN IMMEDIATE, SHUTDOWN NORMAL or SHUTDOWN TRANSACTIONAL.
2. Copy init.ora and control files to create instance and be able to go in mount mode. Check the init.ora for the locations where the controlfiles have
to be, if those locations are not valid on the machine put the control files on
different places and adjust the init.ora accordingly.
3.a. Copy the datafiles (all of them).
  b. Copy the redo-logfiles (all of them).
4.a. (Unix only) Set the environment variables:
        ORACLE_SID - set to the database name you wish to create
        ORACLE_HOME - set to full pathname of the Oracle system home directory
        PATH - needs to include $ORACLE_HOME/bin
  b. (NT/2000 only) Do 'set ORACLE_SID='
        Use oradim to create the service for the instance.   For more information
on oradim please refer to (the part that refers to creating a new instance):

Creating a new 7.3, 8.0, 8.1 Instance/Database

5. Use servermanager (check the name to use for your version of oracle) or sqlplus (version 9i and above) to startup the database in mount mode.  
Do  
      CONNECT INTERNAL/
then
      STARTUP MOUNT    
Then do a rename of the copied datafiles if they are not in the same path as on the other machine. For all the files that are in the result of the query:newfullpath>\';
      SELECT NAME FROM V$DATAFILE;
do
      ALTER DATABASE RENAME FILE '\' to <

6.   Query the datadictionary for the old location of the redolog files using:
      SELECT MEMBER FROM V$LOGFILE;
If the new place is not the same as the old do:
    ALTER DATABASE RENAME FILE '\' to &
lt;newfullpath>\';
7.   Now open the database:
      ALTER DATBASE OPEN;

 

 

 

       

1.  Initiate a SQL*Plus session using the user ID and password for the user you created.

2.  True or False.  SQL*Plus commands access the database?

FALSE

3.  True or False.  Will the SELECT statement execute successfully?
        SQL>SELECT ename, job, sal Salary
            2    FROM emp;

TRUE

4.  True or False.  Will the SELECT statement execute successfully?
        SQL>SELECT *
           2    FROM salgrade;

TRUE

5.  There are four coding errors in this statement.  Identify them.
        SQL>SELECT empno,ename salary X 12 ANNUAL SALARY
           2    FROM emp;

A.  The EMP table does not contain a column called salary.  The column is called sal.
B.  The multiplication operator is *, not x as shown in line 2.
C.  The ANNUAL SALARY alias cannot include spaces.  The alias should read
           ANNUAL_SALARY or be enclosed in double quotation marks.
D.  A comma is missing after the column name ENAME.

6.  Show the structure of the DEPT table.  Select all data from the DEPT table.

SQL> DESCRIBE dept
SQL> SELECT *
     2    FROM dept;

7.  Show the structure of the EMP table.  Create a query to display the name, job, hire date and
     employee number for each employee with employee number appearing first.  Save your SQL
     statement to a file named plq7.sql.

SQL> DESCRIBE emp
SQL> SELECT empno, ename, job, hiredate
     2    FROM emp;
SQL> SAVE p1q7.sql

8.  Run your query in the plq7.sql file.

SQL> START p1q7.sql

9.  Create a query to display unique jobs from the EMP table.

SQL> SELECT DISTINCT  job
     2   FROM emp;

10.  Load plq7.sql into the SQL buffer.  Name the column headings Emp #, Employee, Job and
       Hire Date, respectively.  Show how you did this.

SQL> GET p1q7.sql
SQL> 1 SELECT empno "Emp #", ename "Employee",
SQL> i
   2i     job "Job", hiredate "Hire Date"
   3i
SQL> SAVE p1q7.sql REPLACE
SQL> START p1q7.sql

11.  Display the name concatenated with the job, separated by a comma and space, and name the column
       Employee and Title.  Show how you did this.

SQL> SELECT ename||', '||job "Employee and Title"
      2   FROM emp.

12.  Create a query to display all data from the EMP table.  Separate each column by a comma.  Name
       the column THE_OUTPUT.

SQL> SELECT empno||','||ename||','||job||','||
     2                   mgr||','||hiredate||','||sal||','||
     3                   comm||','||deptno THE_OUTPUT
     4   FROM emp;

Practice 2:

1.  Create a query to display the name and salary of employees earning more than
     $2,850.  Save your SQL statement to a file named p2ql.sql.  Run your query.

2.  Create a query to display the employee name and department number for employee
     number 7566.

3.  Modify p2ql.sql to display the name and salary for all employees whose salary
     is not in the range of $1500 and $2850.  Resave your SQL statement to file
     named p2q3.sql.  Rerun your query.

4.  Display the employee name, job, and start date of employees hired between
     February 20, 1981 and May 1, 1981.  Order the query in ascending order by
     start date.

5.  Display the employee name and department number of all employee in departments
     10 and 30 in alphabetical order by name.

6.  Modify p2q3.sql to list the name and salary of employees who earn more than
     $1500 and are in department 10 or 30.  Label the column Employee and Month
     Salary, respectively.  Resave your SQL statement to a file named p2q6.sql.
     Rerun your query.

7.  Display the name and hire date of every employee who was hired in 1982.

8.  Display the name and title of all employees who do not have a manager.

9.  Display the name, salary and commission for all employees who ear commissions.
     Sort data in descending order of salary and commissions.

10.  Display the names of all employees where the third letter of their name is an A.

11.  Display the names of all employees that have two Ls in their name and are in
       department 30 or their manager is 7782.

12.  Display the name, job and salary for all employees whose job is Clerk or
       Analyst and their salary is not equal to $1000,  $3000 or $5000.

13.  Modify p2q6.sql to display the name, salary and commission for all employees
       whose commission amount is greater than their salary increased by 10%.
       Rerun your query.  Resave your query as p2q13.sql.

Practice 3:

1.  Write a query to display the current date.  Label the column Date.

2.  Display the employee number, name, salary and salary increase by 15% expressed as a
     whole number.  Label the column New Salary.  Save your SQL statement to a file named
     p3q2.sql.

3.  Run the query in the file p3q2.sql.

4.  Modify your query p3q2.sql to add a column that will subtract the old salary from the new
     salary.  Label the column Increase.  Rerun your query.

5.  Display the employee's name, hire date and salary review date which is the first Monday after
     six months of service.  Label the column REVIEW.  Format the dates to appear in the format
     similar to "Sunday, the Seventh of September, 1981".

6.  For each employee display the employee name and calculate the number of months between
     today and the date the employee was hired.  Label the column MONTHS_WORKED.  Order
     your results by the number of months employed.  Round the number of months up to the closest
     whole number.

7.  Write a query that produces the following for each employee:  <employee name> earns <salary>
     monthly but wants <3 times salary>.  Label the column Dream Salaries.

8.  Create a query to display name and salary for all employees.  Format the salary to be 15
     characters long, left-padded with $.  Label the column SALARY.

9.  Write a query that will display the employee's name with the first letter capitalized and all
    others letters lowercase and the length of their name, for all employees whose name starts with
     J, A, or M.  Give each column an appropriate label.

10.  Display the name, hire date and day of the week on which the employee started.  Label
     the column DAY.  Order the results by the day of the week starting with Monday.

11.  Create a query that will display the employee name and commission amount.  If the employee
     does not earn commission, put "No Commission".  Label the column COMM.

12.  Create a query that displays the employees' names and indicates the amount of their salaries
     through asterisks.  Each asterisk signifies a hundred dollars.  Sort the data in descending order of
     salary.  Label the column EMPLOYEE_AND_THEIR_SALARIES.

13.  Write a query that displays the grade of all employees based on the value of the column JOB, as
     per the table shown below

JOB GRADE
PRESIDENT A
MANAGER B
ANALYST C
SALESMAN D
CLERK E
None of the above O

Practice 4:

1.  Write a query to display the name, department  number, and department name for all
     employees.

2.  Create a unique listing of all jobs that are in department 30.  Include the location of
     department 30 in the output.

3.  Write a query to display the employee name, department name and location of all employees
     who earn a commission.

4.  Display the employee name and department name for all employees who have a A in their
     name.  Save your SQL statement in a file called p4q4.sql.

5.  Write a query to display the name, job, department number, and department name for all
     employees who work in DALLAS.

6.  Display the employee name and employee number along with their manager's name and
     manager number.  Label the columns Employee, Emp#, Manager and Mgr#, respectively.
     Save your SQL statement in a file called p4q6.sql.

7.  Modify p4q6.sql to display all employees including King, who has no manager.
     Resave as p4q7.sql.  Run p4q7.sql.

8.  Create a query that will display the employee name, department number, and all the
     employees that work in the same department as a given employee.  Give each column an
     appropriate label.

9.  Show the structure of the SALGRADE table.  Create a query that will display the name, job,
     department name, salary, and grade for all employees.

10.  Create a query to display the name and hire date of any employee hired after the employee
     Blake.

11.  Display all employees' names and hire dates along with their manager's name and hire date for
     all employees who were hired before their managers.  Label the columns Employee, Emp
     Hiredate, Manager, and Mgr Hiredate, respectively.

Answer 2:

1.
SQL> SELECT ename, sal
     2    FROM emp
     3    WHERE sal> 2850;
SQL> SAVE p2q1.sql

2.
SQL> SELECT ename, deptno
     2    FROM emp
     3    WHERE empno=7566;

3.
SQL> EDIT p2q1.sql
SELECT ename, sal
FROM emp
WHERE sal NOT BETWEEN 1500 AND 2850
/
SQL> START p2q3.sql

4. 
SQL> SELECT ename, job, hiredate
     2    FROM emp
     3   WHERE hiredate BETWEEN
     4    TO_DATE('20-Feb-1981','DD-MON-YYYY') AND
     5    TO_DATE('01-May-1981','DD-MON-YYYY')
     6    ORDER BY hiredate;

5.
SQL> SELECT ename, deptno
     2    FROM emp
     3   WHERE deptno IN (10,30)
     4    ORDER BY ename;

6.
SQL> EDIT p2q3.sql
SELECT ename "Employees", sal "Monthly Salary"
FROM emp
WHERE sal > 1500
AND deptno IN (10,30)
/
SQL> START p2q6.sql

7.
SQL> SELECT ename, hiredate
     2    FROM emp
     3   WHERE hiredate LIKE '%82';

8.
SQL> SELECT ename, job
     2    FROM emp
     3   WHERE mgr IS NULL;

9.
SQL> SELECT ename, sal, comm
     2    FROM emp
     3   WHERE comm IS NOT NULL
     4    ORDER BY sal DESC, comm DESC;

10.
SQL> SELECT ename
     2    FROM emp
     3   WHERE ename LIKE '__A%';

11.
SQL> SELECT ename
     2    FROM emp
     3   WHERE ename LIKE '%L%L%'
     4    AND deptno=30
     5    OR mgr=7782;

12.
SQL> SELECT ename, job, sal,
     2    FROM emp
     3   WHERE job IN ('CLERK', 'ANALYST')
     4    AND sal NOT IN (1000, 3000, 5000);

13.
SQL> EDIT p2q6.sql
SELECT ename "Employees", sal "Monthly Salary", comm
FROM emp
WHERE comm > sal*1.1
/
SQL> START p2q13.sql

Answer 3:

1.
SQL> SELECT sysdate "Date"
     2    FROM dual;

2.
SQL> SELECT empno, ename, sal,
     2                   ROUND(sal*1.15,0) "New Salary"
     3    FROM emp
SQL> SAVE p3q2.sql

3.
SQL> START p3q2.sql

4. 
SQL> EDIT p3q2.sql
SELECT empno, ename, sal,
               ROUND(sal*1.15,0) "New Salary",
               ROUND(sal*1.15,0) -sal "Increase"
FROM emp
/
SQL> START p3q2.sql

5.
SQL> SELECT ename, hiredate
     2                   TO_CHAR(NEXT_DAY(ADD_MONTHS(hiredate,6),
     3                   'MONDAY'),
     4                   'fmDay, "the" Ddspth "of" Month, YYYY') REVIEW
     5    FROM emp

6.
SQL> SELECT ename, ROUND(MONTHS_BETWEEN
     2                   (SYSDATE, hiredate)) MONTHS_WORKED
     3    FROM emp
     4    ORDER BY MONTHS_BETWEEN(SYSDATE, hiredate);

7.
SQL> SELECT ename || ' earns'
     2                   || TO_CHAR(sal, 'fm$99,999.00')
     3                   || ' monthly but wants'
     4                   || TO_CHAR(sal*3,'fm$99,999.00')
     5                   || '.' "Dream Salaries"
     6   FROM emp;

8.
SQL> SELECT ename, job
     2                   LPAD(sal, 15, '$') SALARY
     3   FROM emp;

9.
SQL> SELECT INITCAP(ename) "Name",
     2                   LENGTH(ename) "Length"
     3    FROM emp
     4   WHERE ename LIKE 'J%'
     5    OR ename LIKE 'M%'
     6    OR ename LIKE 'A%'

10.
SQL> SELECT ename, hiredate
     2                   TO_CHAR(hiredate, 'DAY') DAY
     2    FROM emp
     3    ORDER BY TO_CHAR(hiredate-1,'d');;

11.
SQL> SELECT ename
     2                   NVL(TO_CHAR(comm),'No Commission') COMM
     3    FROM emp

12.
SQL> SELECT RPAD(ename,8)||'  '||RPAD(' ',sal/100+1,'*')
     2                   EMPLOYEE_AND_THEIR_SALARIES
     3    FROM emp
     4    ORDER BY sal DESC;

13.
SQL> SELECT job DECODE(job, 'CLERK',          'E',
     2                                                 'SALESMAN',  'D',
     3                                                 'ANALYST',     'C',
     4                                                 'MANAGER',    'B',
     5                                                 'PRESIDENT',  'A',
     6                                                                           '0') GRADE
     7   FROM emp;

Answer 4:

1.
SQL> SELECT e.ename, e.deptno, d.dname
     2    FROM emp e, dept d
     3    WHERE e.deptno=d.deptno;

2.
SQL> SELECT DISTINCT e.job, d.loc
     2    FROM emp e, dept d
     3    WHERE e.deptno=d.deptno
     4    AND e.deptno=30;

3.
SQL> SELECT e.ename, d.dname, d.loc
     2    FROM emp e, dept d
     3    WHERE e.deptno=d.deptno
     4    AND e.comm IS NOT NULL;

4. 
SQL> SELECT e.ename, d.dname
     2    FROM emp e, dept d
     3    WHERE e.deptno=d.deptno
     4    AND e.ename LIKE '%A%';

5.
SQL> SELECT e.ename, e.job, e.deptno, d.dname
     2    FROM emp e, dept d
     3    WHERE e.deptno=d.deptno
     4    AND d.loc='DALLAS';

6.
SQL> SELECT e.ename "Employee", e.empno "Emp#",
     2                   m.ename "Manager", m.empno "Mgr#"
     3    FROM emp e, emp m
     4    WHERE e.mgr=m.empno;
SQL> SAVE p4q6.sql

7.
SQL>EDIT p4q6.sql
SELECT e.ename "Employee", e.empno "Emp#",
               m.ename "Manager", m.empno "Mgr#"
FROM emp e, emp m
WHERE e.mgr=m.empno(+);
SQL> SAVE p4q7.sql

8.
SQL> SELECT e.deptno department, e.ename employee
     2                   c.ename colleague
     3    FROM emp e, emp c
     4    WHERE e.deptno=c.deptno
     5    AND e.empno<>c.empno
     6    ORDER BY e.deptno, e.ename, c.ename;

9.
SQL> DESCRIBE salgrade
SQL> SELECT e.ename, e.job, d.dname, e sal, s.grade
     2    FROM emp e, dept d, salgrade s
     3    WHERE e.deptno=d.deptno
     4    AND e.sal BETWEEN s.losal AND s.hisal;

10.
SQL> SELECT emp.ename, emp.hiredate
     2    FROM emp, emp blake
     3    WHERE blake.deptno='BLAKE'
     4    AND blake.hiredate<emp.hiredate;

11.
SQL> SELECT e.ename "Employee", e.hiredate "Emp Hiredate"
     2                   m.ename "Manager", m.hiredate "Mgr Hiredate"
     3    FROM emp e, emp m
     4    WHERE e.mgr=m.empno;
     5    AND e.hiredate< m.hiredate;


Sample Test (study guide)

 

1)      Organizing tables into groups is good for performance, security and ease of maintenance. In Oracle, when you arrange tables into logical groups, it is called:

 

a) Segments                        b) Extents                     c) Block

d) Tablespaces                    e) Partitions

 

2)      Smallest unit of Disk I/O in a Database Management System

a)   Segment           b) Extent                       c) Bit

d) Block                  e) Record

 

3)      One or more contiguous Blocks

a)   Segment           b) Extent                       c) Bit

d) Cursor                e) Record

 

4)      In JDeveloper a ___________ contains several Projects

5)      To Establish an Oracle connection in Jdeveloper, we need to know _____________

And _________________________. We can obtain these names

By querying the view  V$Instance.

 

6)      Difference between Stored Procedure, Stored Function, Trigger and Anonymous Blocks.

___________________________________________

7)      What is a cursor in PL/SQL and Embedded SQL with C ? Why do I need it ?

What is the corresponding object in Java that performs the same function ?

8)      If your Database is slow, describe all the mechanisms that you know that the DBA should investigate to speed it up. Describe them in the order that you would try them.

 

9)      :What is the difference between 3NF and Boyce-Codd Normal Form ? Answer by giving an example of a Table that is in 3NF but is not in 4NF.

10) Give an example of a Table that is in 3NF and BCN, but not in 4NF. Then convert the table to 4NF.

11) Can a Foreign Key have Null Values                Yes                  No

 

12)  Can we update the value of a Primary Key ? Explain when and when not ?

13)  For Employee and Department Tables, In what order should we create the tables ?

14)  In what order should we drop the tables ?

15)  A view in Oracle corresponds to what in MS-Access ?

 

16)  Give two reasons why one would want to create a view ?

 

 

17) What is the difference between a view and a materialized view ? When do you want one or another ?

 

18)  Concurrency and SQL questions in:

http://science.kennesaw.edu/~mguimara/3310/tfinal.doc

 

Concurrency questions in the sample test  at coffee.Kennesaw.edu

 

19) What are three the conditions that would make a field interesting to index on ?

 

 

20) List 3 different types of indexes and describe when to use it and when to not use it.

 

21) Explain the Clause ON DELETE/UPDATE  RESTRICT/CASCADE/SET NULL.

      In other words, where and when is this clause applied ?

 

22) Explain the clause For Update and NOWAIT.

 

23) What are the three blocks (parts) of an SQL program ?

 

24) Convert the code on page 649 to Object-Relational DBMS.

25) The purpose of this assignment is to give you experience in the use of object-relational database (ORDBMS) concepts. Using the UML diagram of the Art Museum enterprise on the following page, you are to develop a database application using Oracle 8i that allows you to add objects to object tables, modify attribute values of objects, establish and modify relationships between objects, execute triggers and methods, and query information about objects. To simplify the assignment, you will be using the SQL Plus environment to create the appropriate database schema, populate the database, and execute queries.

The database application that you create must meet the following requirements:

1. Exhibition, ArtObject and Artist must be implemented as object tables.

2. ArtObject must store a REF to Artist for the createdBy relationship (note that artist is a required value of ArtObject).

3. Artist must store a VARRAY of REFs to ArtObjects for the inverse of the createdBy relationship.

4. A trigger must be implemented on the ArtObject side of the createdBy relationship to update the inverse of the relationship when the artist of an object is initialized or modified. You can assume that the createdBy relationship will only be set on the ArtObject side of the relationship.

5. Exhibition must store a nested table of REFs to ArtObjects. You will need to implement procedures to add and remove individual objects to/from the nested table.

6. displayExhibit must be implemented as a function that returns an array of Exhibition object REFs as a derived inverse of the onExhibit relationship.

7. objectCount must be implemented as a function that returns the number of art objects in an exhibition.

8. For this assignment, you can assume that none of the objects will be deleted (otherwise you would have to write triggers to maintain inverses for delete operations).

9. For this assignment, you do not have to be concerned with implementing constraints on dates for exhibitions and artists.

Similar to the School Database example provided to you on the class Object Relational web page, you will create sql scripts to demonstrate the functionality of your project using the test sequence on the following page.

Test Script (must be executed in the specified order):

1. Create an artist with name Joe.

2. Create an artist with name Bob.

3. Create an artist with name Sue.

4. Create an exhibition with name EX1.

5. Create an exhibition with name EX2.

6. Create at art object with id AO1 (artist is Joe).

7. Create an art object with id AO2 (artist is Joe).

8. Create an art object with id AO3 (artist is Bob).

9. Create an art object with id AO4 (artist is Sue).

10. Create an art object with id AO5 (artist is Sue).

11. Create an art object with id AO6 (artist is Sue).

12. Schedule AO1, AO2, AO3 for EX1 (i.e., add these objects to the nested table in EX1).

13. Schedule AO3, AO4, AO5, AO6 for EX2.

14. Query: Display the idNo, title, year, type, and artist name for each art object.

15. Query: Display the name of each artist together with the idNo of their art objects.

16. Query: Display the name, startDate, and endDate of each exhibition together with the idNo of the art objects in the exhibit.

17. Query: For each exhibit, execute objectCount.

18. Query: For each artobject, execute displayExhibits.

19. Change the artist of AO4 to Bob.

20. Repeat the query in step 15.

21. Remove AO6 from the nested table in EX2.

22. Schedule AO6 for EX1

23. Repeat the query in 16.

24. Repeat the query in 17.

25. Repeat the query in 18.

 

Deliverables:

1. A disk with the .sql files needed to create the database and demonstrate the items above.

2. A hardcopy of the .sql files.

3. A hardcopy of the execution of your test script.