INFORMATION TECHNOLOGY SERVICES

CCTS Software, Web Applications, and Training

Introduction to SQL for Oracle

NORTHERN ARIZONA UNIVERSITY

Introduction to SQL & SQL*PLUS

© Northern Arizona University Software, Web Applications, and Training Phone (520) 523-1511 • Fax (520) 523-7407

T able of Contents
INTRODUCTION

MODULE

1 1 3 4

MODUL E

5 33 37 38 38 39 41 42 42

Intro to SQL and SQL*Plus Running SQL and SQL*Plus in Oracle Getting Help

Creating Tables Dropping and Altering Tables Creating Tables from Subqueries Creating Demo Tables

MODULE

2 5 6 8

Creating Views Inserting, Updating & Deleting Records Committing Changes Indexing Tables

Running Simple Queries in SQL Datatypes and Metadata Structuring Queries

Saving Queries & Running Saved-Queries 10 Operators Comparison Operators Arithmetic Operators Common Aggregate Functions 11 11 13 15 MODULE 6 44 45 46 50 52

Creating Sequences Creating Triggers

MODULE

3 19

Using MS-Access as a Front End SQL Loader SQLPlus Worksheet

Working with Dates & Date Functions

MODULE

4 25 28 30 31

GROUP BY Clause ORDER BY Clause HAVING Clause Joining Tables

S O L U T I O N S T O E X E R C I S E S A R E I N T H E A P P E N D I X .

.

We will start from the beginning. SQL*PLUS is proprietary to Oracle.nau. Web Applications. Web Applications. & Training (SWAT) team works with the Solution Center to provide our customers the best service possible. Please feel free to contact us anytime with your computing or computer training questions.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Introduction Introduction T I T S S O L U T I O N C E N T E R his course is designed to help you quickly learn the basics of SQL and SQL*PLUS queries. & Training Teams Phone: (520) 523-1511 Fax: (520) 523-9259 http://www. This course has no prerequisites and you will soon discover that basic SQL is easy to learn and use. About the Solution Center and the Software. & Training team. The Software. Web Applications. The mission of the Solution Center and the SWAT team is to maintain or increase the productivity of NAU staff and faculty by providing professional development and computing solutions from a central point of contact. so you need to have access to a computer running some version of Oracle8 or 9 to complete the exercises. One of the goals of the SWAT team is to provide you with the training and training materials you need to improve your computing skills. you should be able to perform simple operations using SQL. II . assuming that you have no experience with SQL and take you through the steps.edu/its This manual was created for you by the ITS Software. Personal Oracle8 was used as the point of reference in creating this manual. and acting as an advocate for our customers in obtaining NAU computing support services. By the end of this course.

I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S .

Explain basic SQL/SQL*PLUS terms and concepts. 3. 7. Identify SQL/SQL*PLUS statements. Perform simple table joins. and SQL Plus Worksheet in Oracle-related tasks. 2. Create and modify tables 6. students will be able to: 1. . 4. Use sequences and triggers to generate autonumbers. SQL Loader.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S ü 1 Course Objectives At the end of the course. Use SQL command syntax to write simple queries. Effectively use MS-Access. 5.

I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S .

In 1979. Release 8. Codd. and Full. Oracle Corporation ensures future compliance with evolving SQL standards by actively involving key personnel in SQL standards committees. Relational Software. Inc. Industry-accepted committees are the American National Standards Institute (ANSI) and the International Standards Organization (ISO). Today. When a new SQL standard is simultaneously published by these organizations. Intermediate. but the standards are technically identical. fully supports Entry SQL and has many features that conform to Transitional. SQL can be pronounced as “ess-cue-ell”. Transitional. By the late 1980’s there were over seventy-five SQL or SQL-like database management systems. E. 1 . Oracle SQL complies with industry-accepted standards. 1 S QL is an acronym for “Structured Query Language”. the names of the standards conform to conventions used by the organization. but many people refer to it as “sequel”. A conforming SQL implementation must support at least Entry SQL. Intermediate. Both ANSI and the ISO/IEC have accepted SQL as the standard language for relational databases. The paper." by Dr.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Module Intro to SQL and SQL*PLUS SQL and SQL*PLUS. The latest SQL standard is often called SQL92 (and sometimes SQL2). Oracle8. Codd's model is now accepted as the definitive model for relational database management systems (RDBMS). or Full SQL. SQL is accepted as the standard RDBMS language. (now Oracle Corporation) introduced the first commercially available implementation of SQL. "A Relational Model of Data for Large Shared Data Banks. SQL was developed by IBM to use Codd's model. was published in June 1970. SQL92 defines four levels of compliance: Entry. which is affiliated with the International Electrotechnical Commission (IEC). F.0.

Examples of DDL commands include: • • • • • CREATE a database object such as a table DROP (delete) a database object ALTER a database object GRANT privileges on a database object REVOKE privileges on a database object DML allows you to manipulate the contents of a database. replacing. insert. altering. You use DML to capture. and deleting rows in a table creating. Examples of DML commands include: • • • • SELECT columns of data in a table INSERT rows of data in a table DELETE rows of data in a table UPDATE SQL*PLUS What is the difference between SQL and SQL*Plus? SQL is the standard database query language that all relational databases use to manipulate data. including: • • • • • querying data inserting. all programs written in SQL are portable: they can often be moved from one database to another with very little modification. and delete data.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL provides commands for a variety of tasks. DDL commands create. so you can transfer all skills you have gained with SQL from one database to another. and dropping objects controlling access to the database and its objects guaranteeing database consistency and integrity SQL unifies all of the above tasks in one consistent language. SQL*Plus is a programming environment where you can use SQL. 2 . All major relational database management systems support SQL. change or remove database objects such as tables or users. In addition. updating. DDL and DML SQL statements fall into two main categories: Data Definition Language (DDL) and Data Manipulation Language (DML).

and much more. It uses SQL to get information from the Oracle data structure. dates. and select SQL Plus 8.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL*Plus is usually thought of as a kind of interactive query tool and report writer. go to Start|Programs|Oracle for Windows NT (or Windows 95). and lets you create polished. well-formatted reports by giving you easy control over titles.0. Running SQL*PLUS in Oracle To start SQL*Plus in Personal Oracle8. formatting of numbers. At the log on prompt. subtotals and totals. You should see the following information: You are now ready to begin entering SQL commands! 3 . type scott for username and tiger for the password. and text. Leave the host string blank. column heading.

Your Web browser should open to the following page: From here. go to your operating system command line and type: SQLPLUS username|password. and select Oracle Documentation. you will have to enter the new password. You should get a “user altered” message. The next time you log in. To test it log in with the following: Username: your_userid Password: your_userid Host: NAUDEV You should change your password once you have logged in to something more secure. Use the following SQL statement to change your password: SQL> alter user your_userid identified by new_password. you should be able to find your answer. Tip: In older versions of Oracle and in true client/server environments. The password and username are most likely your userid. you can access Help by typing “help” at the SQL prompt.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S To start SQL*Plus on a mainframe or network. Getting Help To access help in Personal Oracle8. Changing Your Password in NAUDEV You can also log into NAUDEV with your own account if one has been created for you. go to Start|Programs|Oracle for Windows NT (or Windows 95). 4 .

You should get this result: SQL> select table_name from all_tables. 2 O racle SQL*Plus comes with a demo database that contains several tables. 5 .I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Module Running Simple Queries in SQL Now that you have SQL up and running. let’s look at how to structure queries. Some of these tables already include data. type in the following at the SQL prompt: and hit “enter”. To see which tables are available. SQL> select table_name from all_tables. We will use these tables for our exercises. TABLE_NAME -----------------------------DUAL SYSTEM_PRIVILEGE_MAP TABLE_PRIVILEGE_MAP STMT_AUDIT_OPTION_MAP AUDIT_ACTIONS PSTUBTBL DEPT EMP BONUS SALGRADE USER_PROFILE LOCATION DEPARTMENT JOB EMPLOYEE SALARY_GRADE PRODUCT PRICE CUSTOMER SALES_ORDER ITEM 21 rows selected.

--------. Most 6 . Below is a list of all the tables that are available in the demo database. we will only use three: dept. however.000 Description Text string with variable length.--------1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999 Datatypes and Metadata The following datatypes can be used in Oracle: Datatype VARCHAR2(n) Parameters n=1 to 2.--------.--------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 DEPT Table DEPTNO --------10 20 30 40 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON SALGRADE Table GRADE LOSAL HISAL --------.--------.--------.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S An alternative SQL statement that displays all available tables as the previous example did is: SQL> select * from tab. For this course. and salgrade. emp. EMP Table EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB MGR HIREDATE SAL COMM DEPTNO --------.--------.

Raw binary data of variable length.s) LONG DATE p=1 to 38. you could not enter a number above 99. ENAME.999. Maximum length is 2 gigabytes. For regular text. Raw binary data of variable length. p = precision (total number of Digits). SQL will round up or down. as well as what types (datatypes) of information they contain. HIREDATE. We can also see what type of information must be entered into each column. Text string with variable length. We know this because of the NOT NULL listed next to it. only one. EMPNO must be a number not to exceed four digits. Text string with fixed length. Let’s look at the metadata for the emp table. Seldom used. For example. If you enter more than two decimal places. It let’s us know how a table is structured. like state abbreviations. For short Codes. For graphics.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S NUMBER(p. ENAME can be a maximum of ten letters. EMPNO. two must be behind a decimal point. SAL must be a number.99. s=-84 to 127 or FLOAT none none commonly used datatype. numbers. Valid date range from January 1. 7 . use the DESCRIBE command. This will let you know exactly what the names of your columns are. Of these columns.2) NUMBER(7. For files Like MS Word documents. DEPTNO. Therefore. It is also referred to as the data dictionary. Of those seven digits. SQL> describe emp Name Null? ------------------------------. or symbols in any combination. COMM. RAW(n) LONGRAW CHAR(n) Metadata n=1 to 255 none n=1 to 255 Metadata is the data about the data. SAL.-------EMPNO NOT NULL ENAME JOB MGR HIREDATE SAL COMM DEPTNO Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7. must have something entered into it. s = scale (number of digits to the right of the decimal place). not to exceed seven digits. 4712 AD. To view the metadata of a table. MGR. Number.2) NUMBER(2) This information tells us that we have eight columns in the emp table called EMPNO. For dates and times. JOB. 4712 BC to December 31.

List all the columns. A sample query might look like: select last_name. • 8 . Separate them with commas. all rows are chosen. You can do queries for all records that have null. When left out. WHERE (optional): Where some condition is true. If you have more than one table. however. list them all here. they are not null. limits. the basic structure is always the same. blank space. This is only needed for a query that summarizes data. even if they are from several tables. and connections between tables here. HAVING. or any cha racter is a value. Null is defined as nothing. When a datatype is set to “not null”. Structuring Queries Although SQL queries can become complicated. FROM: Put the table name here. salary from employees where salary > 20000 order by last_name • • • SELECT: Put the list of columns you want to see here. address. GROUP BY (optional): Tells how you want data grouped or summarized. In Oracle. separated with commas. A SQL query has five main parts (clauses): SELECT FROM WHERE (optional) GROUP BY (optional) ORDER BY (optional) A sixth clause. Null means nothing at all.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Null and Not Null As you may have noticed by now. Put comparisons. it means that a value other than nothing has to be entered. a zero. can also be discussed here. each datatype can be set to allow either null or not null values. List them with either AND or OR between each set.

If more than one table is listed. rows are returned in the order in which they are found in the table. column from table where clause group by clause order by clause having clause ORDER BY (optional): List columns to use for sort order here. but with some important distinctions that we’ll look at later.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S • Basic Query select column . we would have to select the specific columns. The following example shows how we would obtain all the information from the department table. If you want to see all the columns. DEPTNO --------20 30 30 20 30 30 10 20 10 30 20 30 20 10 9 . DEPTNO --------10 20 30 40 LOC ------------NEW YORK DALLAS CHICAGO BOSTON Eliminating Duplicate Rows Duplicate rows can be eliminated by using the DISTINCT keyword in the select clause. Notice the difference between the two select statements: SQL> select deptno from emp. enter an asterisk. loc 2 from dept. SQL> select deptno. they should be separated by a comma. SQL> select * from dept. • SELECT specifies which column(s) in a table you want to see. FROM specifies the names of the table or tables in which the columns listed in the SELECT clause are located. When left out. DEPTNO --------10 20 30 40 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON If we wanted to know just the department number and the location. HAVING (optional): Similar to WHERE.

The default file extension is .--------.--------7900 JAMES CLERK 7698 03-DEC-81 950 30 or 10 . DEPTNO --------- 10 20 30 3 Exercise 2. 2. position (job).1 1. Now display just the name (ename). display all the columns from the employee (emp) table.--------.--------.--------. 4. Most likely.--------. you will find it at C:/oracle8/BIN. Using SQL.--------.---------.--------7900 JAMES CLERK 7698 03-DEC-81 950 30 SQL> Then save it: SQL> save example Created file example SQL> In Personal Oracle 8. Saving and Running Queries Queries that will be run repeatedly can be saved as a file and then run later by typing in the name of the file. There are two ways to run the saved query: SQL> start example EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------. EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------. 3. the file is saved to the oracle8/BIN directory.--------.sql.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> select DISTINCT deptno from emp. write the query and execute it: SQL> select * 2 from emp 3 where ename='JAMES'.--------. 5.--------. Create a query to display unique (distinct ) jobs from the EMP table.--------. To save a file. Select all data from the DEPT table. and hire date (hiredate) of the employees. Show the structure (metadata) of the DEPT table.---------.

Remember that operator parameters are case sensitive. “Manager” is not the same as “manager”.--------. • Comparison operators = > < >= <= != <> equal to greater than less than greater than or equal to less than or equal to not equal to not equal to SELECT EMP_ID FROM EMPLOYEES WHERE POSITION = 'Manager'.--------7900 JAMES CLERK 7698 03-DEC-81 950 30 Either start or @ will run the saved query. 11 . we use operators. These conditions determine which rows are retrieved. The system will search for rows of data that meet the conditions (qualifications) you specified by the operators.--------. Comparison Operators SQL provides a variety of operators and keywords for expressing search conditions. you can later append more information to it by using the following command: SQL> save example append Finally. you can replace the saved file by using the replace command with save: SQL> save example replace Operators The WHERE Clause The WHERE clause is the part of the SELECT clause that specifies the search conditions. SELECT EMP_ID FROM EMPLOYEES WHERE SALARY >= 50000.---------. To set up these search conditions.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> @example EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------.--------.--------. You can also edit the saved query by entering edit followed by the filename: SQL> edit example Once the file has been saved.--------.

including dates. 12 . NOT IN) If you wanted to list all managers and staff: SELECT EMP_ID FROM EMPLOYEES WHERE POSITION IN ('Manager'. while numbers do not require this. SELECT EMP_ID FROM EMPLOYEES WHERE POSITION = 'Manager' AND (SALARY > 50000 OR BENEFIT > 10000). • Combinations or logical negations of conditions (AND. SELECT EMP_ID FROM EMPLOYEES WHERE SALARY BETWEEN 30000 AND 50000. 'Staff'). Any character string. OR. while “50000” was not.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Notice that “Manager” is placed in single quotes in the where clause. must be set off by single quotes. NOT) SELECT EMP_ID FROM EMPLOYEES WHERE SALARY < 40000 OR BENEFITS < 10000. • Ranges (BETWEEN and NOT BETWEEN) SELECT EMP_ID FROM EMPLOYEES WHERE SALARY NOT BETWEEN 30000 AND 50000. • • Unknown values (IS NULL and IS NOT NULL) example: where advance is null Character matches (LIKE and NOT LIKE) example: where phone not like ‘415%’ Let’s say you wanted to see all people whose last names started with "L" in the EMPLOYEES table: SELECT EMPLOYEEIDNO FROM EMPLOYEESTATISTICSTABLE WHERE LASTNAME LIKE 'L%'. SELECT EMP_ID FROM EMPLOYEES WHERE SALARY > 40000 AND POSITION = 'Staff'. • Lists (IN.

letter. SMITHY. and SMITHS. sal. The “%” is a wildcard that can represent any number of characters. To find those people with LastName's ending in "L". SQL> select ename. Arithmetic Operator Precedence (* / + -) • • • Multiplication and division take priority over addition and subtraction. ename like ‘SMITH_’ Arithmetic Operators would return SMITHE.--------SMITH 800 1300 ALLEN 1600 2100 WARD 1250 1750 JONES 2975 3475 MARTIN 1250 1750 BLAKE 2850 3350 CLARK 2450 2950 SCOTT 3000 3500 KING 5000 5500 TURNER 1500 2000 ADAMS 1100 1600 JAMES 950 1450 FORD 3000 3500 MILLER 1300 1800 14 rows selected. try '%L%'. or look at what-if scenarios. or if you wanted the "L" in the middle of the word. sal.--------. or punctuation) or set of characters that might appear after the "L". ENAME SAL SAL+500 ---------. Arithmetic operators allow you to modify the way data is displayed. Arithmetic operators can be used in any clause of a SQL statement except the FROM clause.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S The percent sign (%) is used to represent any possible character (number. perform calculations. 12*sal+200 13 . use '%L'. but not SMITHEY. Operators of the same priority are evaluated from left to right Parentheses are used to force prioritized evaluation and to clarify statements 2 from emp. Operator + * / Description Add Subtract Multiply Divide SQL> select ename. sal+500 2 from emp. The character “_” can be used to match exactly one character.

that value is said to be null. Null Values If a row lacks the data value for a particular column. SQL> select ename. 2.2 1.sql. There are two ways to create an alias. or to contain null.---------7902 800 7698 1600 300 3 Exercise 2. A null value is not the same as zero or a space. SQL> select mgr as manager.--------7902 800 7698 1600 300 SQL> select mgr. but NULL can be used as a qualifier.-----------SMITH 800 10800 ALLEN 1600 20400 WARD 1250 16200 JONES 2975 36900 MARTIN 1250 16200 BLAKE 2850 35400 CLARK 2450 30600 SCOTT 3000 37200 KING 5000 61200 TURNER 1500 19200 ADAMS 1100 14400 JAMES 950 12600 FORD 3000 37200 MILLER 1300 16800 14 rows selected.--------. and a space is a character.--------. Create a query to display the employee name and department number for employee number 7566. sal. sal.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S ENAME SAL 12*SAL+200 ---------. parentheses are used to raise the salary $100 per month and then multiply by twelve. One is to place the alias after “AS” in the select statement. Create a query to display the name and salary of employees earning more than $2850. Zero is a number.--------. comm"Commission" 2 from emp. MANAGER SAL COMM --------. sal. The other way is to place the alias in quotation marks. 14 . In the following example. In the first example we multiplied the monthly salary by twelve and then added a onetime bonus of $200.--------. MGR SAL Commission --------. ENAME SAL 12*(SAL+100) ---------. Save your SQL to statement to a file named q1. Run your query. This can be done by using a column alias. comm 2 from emp. Using Column Aliases You may want to display the heading of a column as something other than “12*(SAL+100)”. NULL is absolutely nothing at all. 12*(sal+100) 2 from emp.---------SMITH 800 9800 ALLEN 1600 19400 WARD 1250 15200 JONES 2975 35900 MARTIN 1250 15200 BLAKE 2850 34400 CLARK 2450 29600 SCOTT 3000 36200 KING 5000 60200 TURNER 1500 18200 ADAMS 1100 13400 JAMES 950 11600 FORD 3000 36200 MILLER 1300 15800 14 rows selected.

to just those rows specified by a WHERE clause. AVG. Common Aggregate Functions Oracle offers many functions for performing advanced and complicated manipulations with data. This query provides the total amount of commissions: 15 . The highest value in the expression. The average of values in the numeric expression. These functions are called aggregate functions and they include SUM.sql and run it. No matter how you structure the sets. The number of selected rows. Modify q1. Find out how much Turner will make annually if we give her a $75 dollar a month raise. and MIN. All group functions except COUNT(*) ignore nulls. MAX.sql to display the name and salary for all employees whose salary is not in the range of $1500 and $2850. List employees whose last names begin with “S”. but cause the heading “ename” to be displayed as “Last Name”. You apply aggregates to sets of rows: to all the rows in a table. you get a single value for each set of rows. 4. Aggregates are functions you can use to get summary values. 5. Resave the SQL statement as q2. In this course. Aggregate Function SUM(expression) AVG (expression) COUNT(expression) COUNT(*) MAX(expression) MIN(expression) SUM Result The total of values in the numberic expression. 6. The lowest value in the expression. we will concentrate on some of the more common functions. COUNT. Select all columns from the employee table. The number of non-null values in the expression.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S 3. (discussed in the next module). or to groups of rows set up in the GROUP BY clause.

COUNT takes an argument (a column or expression) and discovers all not-null occurrences of that argument. whether or not any particular column contains a null value. number 10): SQL> select count(deptno) 2 from emp 3 where deptno=10. Average Commission -----------------550 Let’s say that the commissions paid this month were indicative of commissions paid each month and we wanted to know what the average yearly commission might be: SQL> select avg(comm)*12 2 from emp. Accounting Employees -------------------3 COUNT(*) The apparent similarity of COUNT and COUNT(*) can lead to confusion. with a different heading: SQL> select avg(comm) "Average Commission" 2 from emp.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> select sum(comm) 2 from emp. AVG(COMM)*12 -----------6600 COUNT What if we wanted to know how many employees worked in the accounting department (dept. Let’s look at how each behaves in the following examples: SQL> select count(comm). count(*) 2 from emp. while COUNT(*) counts all rows. SUM(COMM) --------2200 AVG Here we have the average of commissions paid. COUNT(DEPTNO) ------------3 SQL> 2 3 4 select count(deptno) "Accounting Employees" from emp where deptno=10.--------4 14 16 . COUNT(COMM) COUNT(*) ----------. However. the two are really not the same.

MAX(SAL) --------5000 MIN MIN provides the lowest value in an expression. Look at the different results when SUM is used with and without DISTINCT.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S The results produced by the two functions are different because ten rows in the COMM column have null values. COUNT.--------SMITH 17-DEC-80 While subqueries are beyond the scope of this course. and therefore is not null. MAX and MIN can be used for things other than the lowest or highest amount. MIN(HIRED --------17-DEC-80 SQL> select ename. and COUNT(*) work with all types of data. ENAME HIREDATE ---------. because “0” is a value. Note that the commission listed as “0” was counted by COUNT. ENAME HIREDATE ---------. We can use max to find out who makes the highest salary: SQL> select max(sal) 2 from emp. hiredate 2 from emp 3 where hiredate=(select min(hiredate) from emp). For example we can use the following query to find out which employee has worked in the company the longest: SQL> select min(hiredate) 2 from emp. MIN. MAX MAX provides the highest value in an expression. hiredate 2 from emp 3 where hiredate='17-DEC-80'. MAX. SQL> select sum(sal) 2 from emp. You can use SUM and AVG with numeric columns only. SUM(SAL) 17 .--------SMITH 17-DEC-80 Essentially. I’ll point out that they exist and that one could have been used to obtain the same information in a single query using the following format: SQL> select ename. a subquery is nothing more than a query within a query Using DISTINCT and ALL With Functions DISTINCT can be used with a function to elimina te duplicate values.

Include the heading “Number of Clerks”. Sum. 18 . 1. Determine the number of clerks without listing them. 1. This option causes a group function to consider all values.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S --------29025 SQL> select sum(distinct sal) 2 from emp. Write a query to count the number of employees. SUM(DISTINCTSAL) ---------------24775 The difference in the two results comes from the fact that there are duplicate values of 1250 and 3000 in the SAL column. including all duplicates. and 3 is 2. For example. 3 Exercise 2. 2.5. the ALL average is 1. and average salary of all employees. the DISTINCT average of 1. 3.3 1. Minimum. and Average. If neither option is specified. Display the highest. the default is ALL. sum. lowest. Label the columns Maximum. DISTINCT ALL This option causes a group function to consider only distinct values the argument expression.

SYSDATE SYSDATE uses the computer’s operating system for the current date and time. hours. day. year. 4712 BC and December 31. You can list the SYSDATE by itself by using the DUAL table. 9999 AD. Valid Oracle dates are between January 1. Arithmetic with Dates You can perform calculations on dates using arithmetic operators. Operation date + number date .number date – date Result date date number of days Description Adds a number of days to a date Subtracts a number of days from a date Subtracts one date from another Adds a number of hours to a date date + number/24 date 19 . representing the century. It can be regarded as a hidden column that is in e very table. and seconds. It is used in calculations that need to compare past or future dates/times with the current date or time. which is a small but useful Oracle table created for testing functions or doing quick calculations. Try it. SYSDATE can be thought of as a function whose result is always the current date and time. The default display and input format for any date is DD-MON-YY.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Module 3 Working with Dates and Date Functions Oracle stores dates in an internal numeric format. SQL> select sysdate from dual. minutes. month.

The to_char function allows you to convert a date from this default format to one specified by you. but I wanted to at least make you aware of them.--------. We will not deal with them in this course. Function months_between (date1.’month’) round (‘25-jul-95’. hiredate) <200.’month’) trunc(‘25-jul-95’. months_between (sysdate.--------19-APR-87 140. next_day (hiredate. hiredate. It subtracts the current date (SYSDATE) from the date on which the employee was hired and divides the result by 365. hiredate) Tenure. add_months (hiredate. 6) Review.’year’) trunc (date [ . Date Functions Here is a list of a few date functions.’11-jan-94’) add_months (date.’year’) Description Number of months between two dates Add calendar months to date Next date of the day specified Last day of the month Round date Truncate date SQL> 2 3 4 5 select empno.937418 The preceding example displays the number of years that each employee in department 10 has worked. ‘fmt’]) trunc (‘25-jul-95’.40068 19-OCT-87 24-APR-87 23-MAY-87 139. ‘fmt’) Up to now. 20 . ‘fmt’]) round (‘25-jul-95’.6) next_day (date.--------. all date values were displayed in the DD-MON-YY format. ‘char’) next_day (‘01-sep-95’.27164 23-NOV-87 29-MAY-87 LAST_DAY( --------30-APR-87 31-MAY-87 EMPNO --------7788 7876 TO_CHAR to_char (date.120854 16. 'friday'). last_day (hiredate) from emp where months_between (sysdate. n) add_months (‘11-jan-94’.25 Years 2 from emp 3 where deptno = 10.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> select ename.561648 17. HIREDATE TENURE REVIEW NEXT_DAY( --------. ENAME ---------CLARK KING MILLER YEARS --------17. date2) months_between (‘01-sep-95’.’Friday’) last_day (date) last_day (‘01-sep-95’) round (date [. (sysdate-hiredate)/365.25 to calculate the number of years that a worker has been employed.

or A. S prefixes BC date with Last 3. or week Full name of day Name of day. three-letter abbreviation Roman numeral month Week of year or month Day of year. to_char (hiredate. 2. S prefixes BC date with BC/AD indicator BC/AD indicator with periods Quarter of year Month. or 1 digit(s) of year Year with comma in this position Year spelled out. S prefixes BC date with Year. month.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> select empno.YYY SYEAR or YEAR BC or AD B.D.C. EMPNO MONTH --------. 3-letter abbreviation 21 . two-digit value Full name of month Name of month. 'MM/YY') Month_Hired 2 from emp 3 where ename = 'KING'. Q MM MONTH MON RM WW or W DDD or DD or D DAY DY Description Century.----7839 11/81 Here are some valid date formats: Element SCC or CC Years in dates YYYY or SYYYY YYY or YY or Y Y.

ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES HIREDATE ------------------------------------------Seventeenth of December 1980 12:00:00AM Twentieth of February 1981 12:00:00AM Twenty-Second of February 1981 12:00:00AM Second of April 1981 12:00:00AM Twenty-Eighth of September 1981 12:00:00AM First of May 1981 12:00:00AM Ninth of June 1981 12:00:00AM Nineteenth of April 1987 12:00:00AM Seventeenth of November 1981 12:00:00AM Eighth of September 1981 12:00:00AM Twenty-Third of May 1987 12:00:00AM Third of December 1981 12:00:00AM 22 . dates can formatted further in the following ways: Element “of ” DD “of” MONTH TH SP SPTH or THSP De Quoted string is reproduce 23 of SEPTEMBER Ordinal number (DDTH for 4TH) Spelled-out number (DDSP for FOUR) Spelled-out ordinal numbers (DDSPTH for FOURTH) SQL> select ename. HH or HH12 or HH24 MI SS SSSSS Description Meridian indicator Meridian indicator with periods Hour of day or hour (1-12) or hour (0-23) Minute (0-59) Second (0-59) Seconds past midnight (0-86399) Finally.M. or P.M.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S The time portion of dates can also be formatted: Element AM or PM A. to_char (hiredate. 'Ddspth "of" Month YYYY HH:MI:SSAM') 2 Hiredate 3 from emp.

500 TO_DATE and TO_NUMBER Functions These two functions can be used to convert a character string to either a number or a date.999EEEE four Es) Multiply by 10 n times (n = no. of 9s after 9999V99 V) SQL> select to_char (sal.999 999999MI 999999PR Result 1234 001234 $1234 1234.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S FORD MILLER Third of December 1981 12:00:00AM Twenty-Third of January 1982 12:00:00AM 14 rows selected. The format model you choose will be based on the previously demonstrated format elements.999') Salary 2 from emp 3 where ename = 'TURNER'.00 1. It converts a number to a character datatype. To_char can be used with numbers in the same way.234E+03 123400 Scientific notation (format must specify 99. . SALARY -------$1. MI PR EEEE V Numeric position (number determine display width) Display leading zeros Floating dollar sign Decimal point in position specified Comma in position specified Minux signs to right (negative values) Parenthesize negative numbers of Example 9s 99999 099999 $999999 9999999. ‘fmt’) Element Description 9 0 $ .234 1234<1234> 1.99 999. 23 . '$99. to_char (number.

Substitute the date with your own birth date. 'Month dd. 1981'. 1981. ‘fmt’]) Example: Display the names and hire dates of all the employees who joined on February 22. hiredate 2 from emp 3 where hiredate = to_date ('February 22.--------WARD 22-FEB-81 Birthday Trick Use the following query to see what day you were born on.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S to_number (char) to_date (char[ . How many months has Turner been employed? 4. Write a query to display the current date. YYYY'). 2. 'Day') "Born on" from dual. ENAME HIREDATE ---------. such as the “4th of July”. SQL> select to_char(to_date('23-sep-63'). Display the name of every employee who was hired in 1982. Born on --------Monday 3 Exercise 3. Be careful to type everything exactly. 24 . Display it first as a numeral and then run a second query that spells it out.1 1. SQL> select ename. Label the heading “Today’s Date”. Now write a query to display the current date in a different format. 3.

GROUP BY divides a table into sets. You will receive an error message if you fail to include the column list. This can be done by using the GROUP BY clause.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Module Organizing & Grouping Data We’ll look at the GROUP BY. • You cannot use a column alias in the GROUP BY clause. so that they display the data in a more meaningful way. The HAVING clause works in a manner similar to the WHERE clause. You can then use the group functions to return summary information for each group. but with some important differences. you need to divide the table of information into smaller groups. • By default. You can use the GROUP BY clause to divide the rows in a table into groups. you cannot select individual results as well unless the individual column appears in the GROUP BY clause. and HAVING clauses in this module. GROUP BY The GROUP BY clause is usually used with an aggregate function such as SUM or AVG. Guidelines: • If you include a group function in a SELECT clause. rows are sorted by ascending order of the columns included in the GROUP BY list. ORDER BY. Until now. 4 T he GROUP BY and ORDER BY clauses can be used to organize your query results. At times. • You must include the columns in the GROUP BY clause. while aggregate functions produce summary values for each set. all aggregate functions have treated the table as one large group of information. You can override this by using the ORDER BY clause 25 . • Using a WHERE clause. as well as how to query data from multiple tables. you can exclude rows before dividing them into groups. GROUP BY doesn’t really have much use without aggregate functions.

SQL> select deptno. The GROUP BY clause specifies how the rows should by grouped.6667 2175 1566. AVG(SAL) --------1566. by default all rows are retrieved.6667 SQL> 2 3 4 select deptno.6667 When using the GROUP BY clause. DEPTNO --------10 20 30 AVG(SAL) --------2916. avg(sal) 2 from emp 3 group by deptno. The above example displays the department number and the average salary for each department.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> select deptno. The WHERE clause specifies the rows to be retrieved. • • • SQL> select avg(sal) 2 from emp 3 group by deptno. so the AVG function that is being applied to the salary column will calculate the average salary for each department. The rows are being grouped by department number.6667 2175 2916. Since there is no WHERE clause.6667 2175 1566. Here is how the SELECT statement above. make sure that all columns in the SELECT list that are not in the group functions are included in the GROUP BY clause. containing a GROUP BY clause is evaluated.6667 DEPTNO --------30 20 10 26 . avg(sal) from emp group by deptno order by avg(sal). avg(sal) 2 from emp 3 group by deptno. AVG(SAL) --------2916.6667 2175 1566.6667 You can also use the ORDER BY clause to rearrange the query results. DEPTNO --------10 20 30 AVG(SAL) --------2916. • The SELECT clause specifies the columns to be retrieved: − Department number column in the EMP table − The average of all the salaries in the group you specified in the GROUP BY clause The FROM clause specifies the tables that the database must access: the EMP table.

• • So the SUM function is being applied to the salary column for all job titles within each department number group. is evaluated: • The SELECT clause specifies the column to be retrieved: − Department number in the EMP table − Job title in the EMP table − The sum of all the salaries in the group you specified in the GROUP BY clause. sum(sal) 2 from emp 3 group by deptno. the rows are grouped by job title. For example. job. − Second. The GROUP BY clause specifies how you must group the rows: − First. job. The FROM clause specifies the tables that the database must access: the EMP table. 27 . containing a GROUP BY clause. SQL> select deptno. Here is how the SELECT statement above. You can return summary results for groups and subgroups by listing more than one GROUP BY column. The table below shows a report that displays the total salary being paid to each job title. The EMP table is grouped first by department number and then within that grouping it is grouped by job title.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Grouping by More Than One Column Sometimes there is a need to see results for groups within a group. the rows are grouped by department number. You can determine the default sort order of the results by the order of the columns in the GROUP BY clause. the two clerks in department 20 are grouped together and a single result (total salary) is produced for all salesmen within the group.--------CLERK 1300 MANAGER 2450 PRESIDENT 5000 ANALYST 6000 CLERK 1900 MANAGER 2975 CLERK 950 MANAGER 2850 SALESMAN 5600 9 rows selected. within each department. within the department number groups. DEPTNO --------10 10 10 20 20 20 30 30 30 JOB SUM(SAL) --------.

salesman).-----------10 3 20 5 30 6 You cannot use the WHERE clause to restrict groups. ORDER BY The ORDER BY clause arranges your query results by one or more columns.6667 20 2175 We’ll discuss the HAVING clause more in depth shortly. DEPTNO COUNT(ENAME) --------. The default order is ascending. 28 . Display the minimum.1 1. clerk. 2. where avg(sal) > 2000 * ERROR at line 3: ORA-00934: group function is not allowed here You can correct the above error by using the HAVING clause to restrict groups. avg(sal) from emp group by deptno having avg(sal) > 2000. avg(sal) 2 from emp 3 where avg(sal) > 2000 4 group by deptno.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Here is another example of the GROUP BY clause: SQL> select deptno. If you want the list to be sorted in descending order. manager. maximum. count(ename) 2 from emp 3 group by deptno.--------10 2916. Exercise 4. you have to use DESC in the ORDER BY clause. DEPTNO AVG(SAL) --------. SQL> 2 3 4 select deptno. president. Write a query to display the number of people with the same job. sum. Note the following error which results from a misuse of the WHERE clause SQL> select deptno. and average salary for each job type (analyst.

You could also add DESC to one or both of the columns in the ORDER BY clause to reverse sort the query result. 1981. ename 2 from emp 3 order by ename.2 1. You can have as many levels of sorts as you like. Display the employee name. empno 2 from emp 3 order by job.--------FORD 7902 SCOTT 7788 ADAMS 7876 JAMES 7900 MILLER 7934 SMITH 7369 BLAKE 7698 CLARK 7782 JONES 7566 KING 7839 ALLEN 7499 MARTIN 7654 TURNER 7844 WARD 7521 14 rows selected. Order the query in ascending order of start date. 1981. ename. EMPNO --------7876 7499 7698 7782 7902 7900 7566 7839 7654 7934 7788 7369 7844 7521 ENAME ---------ADAMS ALLEN BLAKE CLARK FORD JAMES JONES KING MARTIN MILLER SCOTT SMITH TURNER WARD SQL> select empno. and May 1. When you use more than one column in the ORDER BY clause. JOB --------ANALYST ANALYST CLERK CLERK CLERK CLERK MANAGER MANAGER MANAGER PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN ENAME EMPNO ---------. ename 2 from emp 3 order by ename desc. ordered by job first and then by ename within each job category. Exercise 4. 14 rows selected. 29 . EMPNO --------7521 7844 7369 7788 7934 7654 7839 7566 7900 7902 7782 7698 7499 7876 ENAME ---------WARD TURNER SMITH SCOTT MILLER MARTIN KING JONES JAMES FORD CLARK BLAKE ALLEN ADAMS 14 rows selected. sorts are nested ( that is. The following example sorts the query result first by job title and then by last name. You can also sort by more than one column.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> select empno. ename. SQL> select job. job and start date of employees hired between February 20.

after you’ve calculated the aggregates and set up the groups. SQL> 2 3 4 select deptno from emp group by deptno having max(sal) > 2900.3 1. 30 . the HAVING clause is a WHERE clause for groups. The example excludes salesmen and sorts the list by the total monthly salary. salary. and commission for all employees who earn commissions. WHERE clause conditions apply to the aggregates. HAVING limits groups. sum(sal) payroll from emp where job not like 'SALES%' group by job having sum(sal)>5000 order by sum(sal). you use HAVING with GROUP BY. Display the manager number and the salary of the lowest paid employee for that manager. Exclude any groups where the minimum salary is less than $1000. Display the name. SQL> 2 3 4 5 6 select job. Sort the output in descending order of salary. When there are aggregates in the select list of a query. Exclude anyone where the manager id is not known. The HAVING Clause In its most common usage. 3. DEPTNO --------10 20 The following example displays the job title and total monthly salary for each job title with a total payroll exceeding $5000.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S 2. Display the employee name and department number of all employees in departments 10 and 30 in alphabetical order by name. Most of the time.--------ANALYST 6000 MANAGER 8275 Exercise 4. while HAVING conditions apply to the query as a whole. JOB PAYROLL --------. Just as WHERE limits rows. Sort data in descending order of salary and commissions.

column.empno. dept 3 where emp. When this happens. SQL> select emp. dept.deptno. dept.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Joining Tables In a database that has been designed properly. In most cases. emp.deptno=dept.column1=table2. Let’s look at a join involving the EMP and DEPT tables.--------. emp. The join operation lets you retrieve and manipulate data from more than one table in a single SELECT statement. you may need to query more than one table at the same time using a join operation. table2 table1. The format of a join statement looks like this: Select From Where table.ename.--------.deptno. 31 .column2 To perform a simple or inner join.deptno. one table may not give you all the information that you need. you need to join the two tables together by using a column that is found in both tables. you specify joins in the WHERE clause of a SELECT statement. usually as a primary key in one table and a foreign key in the other.column table1.------------SMITH 20 20 DALLAS ALLEN 30 30 CHICAGO WARD 30 30 CHICAGO JONES 20 20 DALLAS MARTIN 30 30 CHICAGO BLAKE 30 30 CHICAGO CLARK 10 10 NEW YORK SCOTT 20 20 DALLAS KING 10 10 NEW YORK TURNER 30 30 CHICAGO ADAMS 20 20 DALLAS JAMES 30 30 CHICAGO FORD 20 20 DALLAS MILLER 10 10 NEW YORK 14 rows selected.loc 2 from emp. table. EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME DEPTNO DEPTNO LOC ---------.

deptno=d. List the results alphabetically by name. department number. e. 3.deptno. SQL> select e.manager.project_id from employee e.name.emp_id. d. 2. Write a query to display the employee name. Exercise 4.empno. It will not work with your practice tables) SQL> 2 3 4 select e. dept d 3 where e. d. This is done in the following manner (This table is an example only. A table alias is defined in the FROM clause after the actual table name. and department name for all employees who work in Dallas. job.loc 2 from emp e. department name.deptno=d.ename. and location of all employees who earn a commission.deptno. and department name for all employees. e. Sometimes you may need to join more than one table. commission.deptno and d.deptno.manager.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S You can cut down on the typing by using table aliases in the SELECT statement.deptno.--------. Write a query to display the employee name. 32 . projects p where e.manager=p. e. EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME DEPTNO DEPTNO LOC ---------.--------. d. d. department number. department d. p.------------SMITH 20 20 DALLAS ALLEN 30 30 CHICAGO WARD 30 30 CHICAGO JONES 20 20 DALLAS MARTIN 30 30 CHICAGO BLAKE 30 30 CHICAGO CLARK 10 10 NEW YORK SCOTT 20 20 DALLAS KING 10 10 NEW YORK TURNER 30 30 CHICAGO ADAMS 20 20 DALLAS JAMES 30 30 CHICAGO FORD 20 20 DALLAS MILLER 10 10 NEW YORK 14 rows selected. Write a query to display the name.4 1.

_. Here is an example: SQL> 2 3 4 create table table_name ( id number(4). If you want to force the user to enter data. This will create a table called “table_name” with three fields: an ID field which can take up to four numbers and a name and a city field which can each hold up to twenty alphanumeric characters. and alter them as necessary. name varchar2(20). Not null constraints One problem with the table is that users can leave fields blank if they want to. This module will give you the knowledge to create your own tables and fields and then alter or modify them after you have created them. 0-9. Naming Conventions There are certain restrictions on names you give to tables and columns. you probably want to know how to create your own tables. Table and column names: Must begin with a letter Can be 1-30 characters long Must contain only A-Z. you can do this by using the words “not null” when creating the table as demonstrated by the following example: 33 . and # Must not duplicate the name of another object owned by the same user Must not be Oracle Server reserved words To create a table.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Module Creating and Working with Tables 5 N • • • • • ow that you know how to pull data out of tables that were created for you. You may or may not want to allow this. you need to specify the name of the table and then specify its fields and the datatypes of those fields. a-z. city varchar2(20)).$. drop (delete) them.

3. The primary key ensures that the value in each row is unique and prevents null values from being entered. the dependent rows in any child tables will also be deleted. Foreign Key Constraint A foreign key constraint is used to relate tables. 34 . REFERENCES identifies the table and column in the parent table. 4. city varchar2(20)). The following constraints are available in Oracle: 1. however. The foreign key is created with a combination of the following keywords: FOREIGN KEY is used to define the column in the child table at the table constraint level. and the table containing the referenced column is the parent table. 2. city varchar2(20)). SQL> 2 3 4 create table table_name ( id number(4) primary key. but it would prevent you from entering John Smith twice. ON DELETE CASCADE indicates that when a row in the parent table is deleted. Not Null –specifies that a column may not contain a null value Unique – Specifies a column whose values must be unique for all rows Primary Key – Uniquely identifies each row of the table Foreign Key – Establishes and enforces a foreign key relationship between the column and a column of the referenced table 5. city varchar2(20)). The unique constraint will allow more than one null value. the row in the parent table cannot be deleted if it is referenced in the child table. Primary Key Constraint A primary key constraint creates a primary key for the table. name varchar2(20). It would not prevent you from entering John Smith and JOHN SMITH. name varchar2(20) not null. Without the ON DELETE CASCADE option. name varchar2(20) unique. Check – Specifies a condition that must be true Unique Key Constraint A unique key constraint requires that every value in a column be unique.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S SQL> 2 3 4 create table table_name ( id number(4). Only one primary key can be created for each table. The foreign key is defined in the child table. This means that a record cannot be inserted without a value being placed in this field. No two rows of a table can have duplicate values. because Oracle is case sensitive. SQL> 2 3 4 create table table_name ( id number(4). A not null constraint has now been placed on the “name” field.

name varchar2(20). SQL> 2 3 4 5 6 create table child_table ( child_id number(2) primary key. First drop (delete) the old constraint. SQL> insert into parent_table values (02. Check the child table and note that the dependent record has also been deleted. 3 city varchar2(20)). Try to drop the Flagstaff record now and see what happens now that we’ve added the ON DELETE CASCADE clause. SQL> delete from parent_table where id=01. This enters data into your tables and relates the John Smith record to Flagstaff by virtue of the foreign key. Now enter some information into your tables: SQL> insert into parent_table values (01. Now try to delete the Flagstaff record from the parent table: SQL> delete from parent_table where id=01. Now add a new constraint that contains the “ON DELETE CASCADE” clause to the child table: SQL> 2 3 4 alter table child_table add constraint childtable_id_fk Foreign key(id) references parent_table(id) ON DELETE CASCADE. id number(2) not null. 'PHOENIX'). 'JOHN SMITH'. SQL> alter table child_table 2 drop constraint CHILDTABLE_ID_FK. SQL> insert into child_table values (10. SQL> select * from child_table 35 . 'FLAGSTAFF').I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Let’s create the parent table first: SQL> create table parent_table ( 2 id number(2) primary key. What happened? Let’s do an alter table command to add “ON DELETE CASCADE” to the foreign key constraint. constraint childtable_id_fk FOREIGN KEY (id) REFERENCES parent_table (id)). 01). Now let’s create the child table and create a foreign key to reference the “id” column in the parent table.

city varchar2(20)). The previous statement will not allow nulls or lower case letters to be entered into the name column. 36 . constraint_type. check ((job = ‘SALESMAN’ and comm IS NOT NULL) or job != ‘SALESMAN’ and comm IS NULL)) Viewing Constraints on a Table Constraints set on a table can be viewed by executing the following statement. which we will cover in the next module. SQL> SELECT constraint_name. A check constraint that makes sure that the id column does not contain four-digit numbers below 1000 or above 5000 can be created with the following statement: SQL> 2 3 4 5 create table table_name ( id number(4) constraint tablename_id_ck check (id between 999 and 5001). search_condition 2 FROM user_constraints 3 where table_name = ‘CHILD_TABLE’. name varchar2(20) not null. Of course another way to ensure that you only get capital letters would be to convert lowercase letters automatically when they are inserted. city varchar2(20)). city varchar2(20)). check (start_date < sysdate and (end_date > sysdate or end_date is null))). Constraints can also be used on dates. name varchar2(20) not null constraint tablename_name_ck check (name=upper(name)). including sysdate. name varchar2(20) not null constraint tablename_name_ck check (name between ‘A’ and ‘Z’). but it will allow numbers and certain symbols. Note that you are actually creating a constraint with its own name. and can be used in simple logic statements. You can check for all uppercase letters in the name column by using this constraint: SQL> 2 3 4 5 create table table_name ( id number(4).I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Check Constraint Check constraints define a condition that each row must satisfy. “tablename_id_ck”. Substitute the name of the table you want to view for CHILD_TABLE and be sure to use uppercase letters. If you want to allow only capital letters: SQL> 2 3 4 5 create table table_name ( id number(4).

Dropping and Altering Tables There are times when you will want to drop (delete) tables that have been created. You may likely want to use Flagstaff as a default value to save some typing. The alter table statement is used to add. You should see that Flagstaff has automatically been entered in the city column. add or remove constraints as we saw above. hiredate date default sysdate). select * from clients. define a default value on a new column. 37 . Now let’s add the city column using the alter table statement: SQL> alter table clients 2 ADD (city varchar2(20)). modify or delete columns. This can be done with the Alter Table statement. name varchar2(20). 'JOHN SMITH'). 3 name varchar2(20). To demonstrate how to add a column.name) values (10.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Setting Default Values on a Column You can also set default values in a table when you create it. This might be useful in a situation where a value to be entered is frequently the same. let’s say that most people who are entered into the table will most likely live in Flagstaff. You should be able to do the same thing with dates. you may simply want to modify the structure of a table. and even to rename a table. city varchar2(20) default ‘FLAGSTAFF’). This is very easy to and can be done with this simple statement: SQL> drop table table_name In other cases. SQL> 2 3 4 create table employees ( id number(2). including the sysdate function. SQL> 2 3 4 create table clients ( id number(2). name varchar2(20). let’s first create the new table: SQL> create table clients ( 2 id number(2). Now try inserting data in the first two columns only and then select it: SQL> SQL> insert into clients (id. In our example.

Demobld will drop and create the demo tables. The two scripts (files) are demobld.sql if you just want to erase your changes and start with a fresh set of demo tables you only need to execute demobld. while demodrop simply drops them.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S You can also use alter table to modify columns.sql. SQL> create table employees 2 as 3 select * from emp. but then be able to set everything back to how it was originally. We’ll call it “employees”. You can change a column’s datatype. Demobld. This is a handy feature. The statement to do this is: SQL> alter table clients 2 drop (name). A feature that first showed up with Oracle8 is the ability to drop a column as well. and NOT NULL column constraint.sql and demodrop. Let’s modify the name column to be thirty spaces instead of twenty.sql.sql and demodrop. You do not need to drop the tables using demodrop. size. 38 . The following query will create a new table with selected columns from the “emp” table. You can also do this with views. The table can also be renamed by executing the following statement: SQL> rename clients to client_table Creating Tables from Subqueries An easy way to create new tables from exisiting data is to create one using a subquery. SQL> alter table clients 2 MODIFY (name varchar2(30)). default value. There are two scripts that are installed with the Oracle client that allows you to add and drop these tables repeatedly. bonus. which we will look at in module seven. Creating and Dropping Demo Tables Oracle has several practice tables that we have been using throughout this course.sql can be located under the current Northern Arizona University install at c:\Oracle/ORA81/sqlplus/demo/demobld. salgrade. and dummy. You should recognize them as emp. dept. This is useful if you want to play with the tables and change data. You can create tables from very sophisticated queries and joins that provide only the data you need.

job TITLE 4 from employees 5 where deptno=20. EMPNO ENAME JOB ---------.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S To run this script from the SQL*Plus tool. 39 .---------7369 7566 7788 7876 7902 SMITH JONES SCOTT ADAMS FORD CLERK MANAGER ANALYST CLERK ANALYST To drop a view: SQL> drop view employeeVU. View created. you can create a “view” of the table which only presents the data fields that you want to make available. Rather than create new tables with redundant data. For example. View dropped. ename. A view is set up with certain privileges for users. You can rename the column names when you create your view in the following manner: SQL> create view employeeVU 2 as select empno ID. you specify the name and then use a select statement: SQL> create view employeeVU 2 as select empno. Now check the view: SQL> select * from employeeVU. simply type in @c:\Oracle/ORA81/sqlplus/demo/demobld. you may want to set it up so that users can only see the data and not be allowed to update it. 3 ename NAME. Creating Views You may create tables that contain data that you don’t want to be made available to certain people or groups. job 3 from employees 4 where deptno=20. A view can also be configured to control how data is manipulated in the table. To create the view. View created.sql and press the enter key.

dname. View created.---------ACCOUNTING 1300 5000 2916. dept d 6 where e. SQL> create view emp_stats_vu 2 (name.oracle.---------7369 7566 7788 7876 7902 SMITH JONES SCOTT ADAMS FORD CLERK MANAGER ANALYST CLERK ANALYST Creating a view from multiple tables An especially handy feature of views is that you can create what looks and acts like a table from multiple tables and functions. avg(e.com or http://otn. 40 .66667 RESEARCH 800 3000 2175 SALES 950 2850 1557.sal).deptno 7 group by d. avgsal) 3 as select d. EMPNO ENAME JOB ---------. however.sal). Now test it: SQL> select * from emp_stats_vu.oracle. For more information consult the comprehensive Oracle complete reference guide or an online resource such as http://www. min(e.---------.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Now test it: SQL> select * from employeeVU. maxsal. There are many rules and commands that you need to be aware of before using a view in a production environment. You cannot update data in this type of view.deptno=d.14286 This is just a superficial overview of views. minsal.com.---------. NAME MINSAL MAXSAL AVGSAL -------------.sal) 5 from emp e.dname. 4 max(e.

50).ename) 2 values (8888.hiredate=’01-FEB-02’. use the following statement: SQL> insert into employees 2 values (8888.’01-FEB-02’. To insert a record. while number datatypes do not. use the following statement: SQL> delete from employees 3 where ename=’SUTHERLAND’.mgr=7839. You can update as many or as few of the columns as you like.0. It’s actually a pretty simple and straight-forward process.’ACTRESS’. Deleting Records To delete a record. let’s look at how to insert data into your tables and manage it once it’s there.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Inserting Records Now that you know how to create and manage tables and views. Updating Records To update a record.10000. use the following statement:: SQL> update employees 2 set job=’ACTOR’.deptno=50 3 where ename=’SUTHERLAND’.7839. Remember that varchar2 and date datatypes need to be enclosed in quotes. then you must identify the fields by name.’SUTHERLAND’).’ROBERTS’. SQL> insert into employees (empno.sal=10000. 41 . If you only want to insert data in certain fields.

Since indexes are independent of the tables. We will look at the commit function in the following section. or you may delete the entire contents of the table! If you do this by accident. SQL> delete from employees. Oracle will make them permanent if you exit from the SQL*Plus tool. SQL> rollback. 42 . you can also issue a rollback command and undo all of the changes up to the point where you last issued a commit command. This becomes very important if you are designing dynamic web pages that present data from your Oracle tables. Commit complete. then you will probably want to create an index to speed query searches. Rollback complete. It speeds up the retrieval of data by using a pointer and can reduce disk input/output by using a rapid path access method. Rollback complete. Committing Changes After making changes to records. SQL> commit. Creating an Index If you have a large table in which only a small percentage of records are expected to be returned at any one time. As we saw in the last section. SQL> rollback. they can be dropped at any time without affecting the data in the tables or the tables themselves. You probably do not want to use indexes on a table that is updated frequently as it may slow down inserts or updates. but they will not show up in your web pages until you have issued a commit command. An implicit index is created automatically when you define a primary key or unique constraint on a table. separate from the table it indexes. The changes appear to have been made in SQL*Plus.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Make sure that you use a where clause with the delete statement. Remember this and save yourself potentially hours of frustration if you present data on the web. There are two types of indexes. you need to issue a “commit” command to make the changes permanent. but you must do it before you commit. you can use the rollback function to correct it. 17 rows deleted. An explicit constraint is created when you manually execute a create index statement as shown below. An index is an independent object. but it is a good idea to get in the habit of committing after important changes.

ic.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S To create an index: SQL> create index employees_empno_idx 2 on employees(empno). You can view the indexes you created by using the following: SQL> select ic. 2 ic. 43 . ix. To drop the index: SQL> drop index employees_empno_idx. user_ind_columns ic 4 where ic.uniqueness 3 from user_indexes ix.table_name = 'employees'.index_name.column_name.column_position col_pos.index_name 5 and ic.index_name = ix. Index created.

We’ll also look at how to schedule jobs to make things happen to your data and tables at pre -determined times. Sequences are typically used to generate primary numbers. To generate the sequence type: 44 . your sequence value will start at 21 the following day. To create a sequence. so one sequence can be used on multiple tables. a sequence can create the equivalent of an Access database autonumber. 2. If your table only inserts three records the first day. We are going to create a sequence to generate an autonumber. If you didn’t specify “no cache” when you created the sequence. it will assign the numbers 1. When combined with a trigger. which automatically creates a new number each time a record is inserted into a table. “No cache” is important if you are using the sequence to create sequential numbers and it’s important that you don’t have any missing values. Oracle tends to pre -allocate 20 values per day. which is the default. Sequences Many tables need unique numbers to serve as primary key values. The “start with” clause can also be left out if you want the sequence number to begin at one. Sequence numbers are independent of tables. The “increment by” clause can be left out if you want it to increase by one number at a time. which we will create in the next section. A sequence generator can be used to automatically assign unique numbers to a row. and 3. but it can be useful in a case where you need the sequence number to start at a value like 1000.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Module Other Tips 6 T he next step is to learn how to use sequences and triggers to allow for automatic numbering and to cause things to happen when an event occurs. follow this general syntax: create sequence sequence_name increment by n start with n no cache. The sequence will also need a trigger.

I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Create sequence autonumber start with 1 nocache. This works like an autonumber in Access and allow access to be used as a front end to Oracle in situations where a primary key are similar automatically generated unique value is necessary. such as Visual Basic in an Active Server Page. You should get a “Sequence created” message if it was successful. You can do it this way: Insert into records_table values (autonumber. 10 / Trigger created. This creates a trigger that will automatically place a sequential number in whichever column specified. To drop the sequence. in this case employee is the tablename. The trigger allows the sequence to fire internally when a record is inserted. In other cases where a front end such as Microsoft Access is being used to insert data. 45 . use “drop sequence sequence_name” If you are embedding an SQL insert statement in something like Active Server Pages. without relying on external code.nextval. 9 END. “SMITH” is just data in the second column. ID is the name of the field where the autoincrement will be. you can create an autonumber that will be initiated by the code itself. 6 begin 7 select autonumber. rather than an event trigger in the table. “number(5)” specifies the datatype and number of digits. a sequence combined with a trigger is probably the best situation. Triggers Here’s how the trigger is created.Emp_ID := Emp_ID. this works fine if you can count on a dynamic page or other code to trigger the sequence event.nextval into Emp_ID from dual. 8 :new. Give it the name of the owner. ‘SMITH’) “Autonumber” is the name of the sequence and “nextval” tells the sequence to give you the next value available. SQL> create or replace trigger triggername_bef_ins_row 2 before insert on employee referencing 3 OLD old NEW new for each row 4 declare 5 Emp_ID number(5). As mentioned.

but someone is responsible for maintaining the data who has no strong technical aptitude and wants to avoid SQL at all costs.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Using Miicrosoft Access as a Front End to Oracle Not everyone wants to learn SQL nor do they want to write a lengthy SQL statement just to insert a record. Click OK. To set up Access as a front end. first create your tables in Oracle using SQL*Plus and then follow these steps. find “Files of Type: Microsoft Access” and scroll to the bottom to change “Microsoft Access” to “ODBC Databases”. Now go to the File menu and select Get External Data > Link Tables. Microsoft Access provides a convenient. GUI-based front end for these users. 46 . This can be especially useful in situations where a department is storing data in one of ITS’s Oracle databases. Open a blank Access database. In the “Link” dialog box that pops up.

I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Select the “Machine Data Source” tab and click on the “New” button. Select System Data Source and click the Next button. 47 .

it means that you probably used the “Oracle ODBC Driver” instead of the “Microsoft ODBC for Oracle” drive. You should now see this box: Find your username and the tables that are located in your space. A description can also be entered if useful.) See page ??? if you forgot how to do this. delete the ODBC connection and re -create it using Microsoft ODBC for Oracle. Put your Oracle username in and then most likely NAUDEV or ITSDEV for the Server name. Note that this is different from the “Oracle ODBC Driver” which may also be listed in your choices. go back. The new ODBC name should now be highlighted. If so.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Click on the “Microsoft ODBC for Oracle” driver and click the next button. Click on the Next button and then click “Finish”. Click OK. Now fill in the box that should pop up. Choose one or more tables and click OK. depending on where your tables are located. (Don’t forget to change this password shortly after they assign it. 48 . “Naudev_tables” can be any name you want to give your ODBC connection. If you can’t find any tables above a certain letter. Simply click OK and then enter the Oracle password that the DBA’s assigned to you. The Oracle ODBC Driver is not recommended because of some anomalies that have been noticed in the NAU env ironment.

I N T R O D U C T I O N

T O

S Q L

A N D

S Q L * P L U S

Access will probably prompt you for a Unique Record Identifier. This is only important for Access and does not change anything on the Oracle side. You should choose something however or you probably will not be able to enter any data through Access, only view it. Click the OK button.

Your link to the Oracle table is now complete. You will notice that the table icon is different than what is usually seen in Access. (It is a globe with an arrow.) This represents a linked table. The good news is that once you have this link, it can be treated as any other table in Access. Queries, forms, and modules can be written in Access that actually run against the Oracle tables. As mentioned above, this can be a very powerful tool, especially when non-technical personnel are expected to manage the data. Plus it gives you the security of having your data stored and backed up on ITS professionally-managed databases.

49

I N T R O D U C T I O N

T O

S Q L

A N D

S Q L * P L U S

Module Six – Lab
(Suggested solutions are in the back of the manual.) 1. Create a new table called lab_one and add several columns, including one called unique_id and make it a primary key with an identifiable name. 2. Using an SQL insert statement, enter one or two records into the new table. 3. Now create a sequence, named something like “autonumber”, which will be used to create an autonumber in the unique_id field. 4. Since we will use Access as a front end, you will also want to create a trigger to cause the sequence to insert a value when a new record is inserted. 5. Now create an Access front end to your new table. Once it is set up, try to insert a couple of records through the GUI interface. Which tool do you prefer, SQL*Plus or Access?

SQL Loader
So how do you get large numbers of records into your tables without having to enter each record by hand? There is a tool called SQL Loader that will let you enter data from a delimited text file. The hard part is setting up the control file, but once you have done this, the records can be loaded in a few seconds to a few minutes depending on the quantity of data. Whole books have been written on SQL Loader, most notably one by O’Reilly, which is devoted entirely to the intricacies of this command line tool. First of all, you need to do a search for the tool to make sure you have it. Look for “sqlldr.exe”. It should be in a path like c:\ORACLE\ora81\bin. SQL*Loader reads files and places the data from those files in an Oracle database based on the instructions it receives from a control file. The control file describes the data being loaded and tells Oracle where to place it. The SQL loader tool isn’t included in the NAU download install, so you need to get it form a complete install from the CD or ask your friendly neighborhood SWAT team member for it.

50

I N T R O D U C T I O N

T O

S Q L

A N D

S Q L * P L U S

1. First we need to create a table to hold the data: Create table class_info (idno number(4), course_no number(3), day_of_class varchar2(20), Building varchar2(50), Seats_remaining number(2), instructor varchar2(50)) storage (initial 1m next 100k pctincrease 0 maxextents unlimited); The last few lines dealing with “storage” are sometimes needed to avoid a “max extents” error that occurs sometimes depending on the amount of data you are trying to load. If you get a max extents error, you need to add this storage clause when creating the table. The DBA’s at NAU have se the default max extents to ten and the clause changes that to allow for loading of large amounts of data. 2. Now create the control file and store it as “class_info.ctl”. (Note the “replace” in the second line. This option wipes out existing data. Use “append” if you want to add to existing data.): load data infile class_info.txt replace into table class_info fields terminated by ‘,’ optionally enclosed by ‘”’ trailing nullcolls (idno, course_no, day_of_class, building, seats_remaining, instructor)

Chyfo at http://www.ispirer.com is a nice little tool which will creat all of the necessary files and scripts for you when migrating data from various database to Oracle. It is a command line tool and you still have to have a pretty good understanding of how things work to use it effectively, however. Don’t forget about the O’Reilly book, which is a great resource if you want to get serious about using SQL loader and tools like Chyfo. Your instructor will tell you where to get the data file, called “class_info.txt”. Place it in the same directory as the control file. I usually create a directory at the root, “C:\loaddata”, for example, to keep the path short and simple. Now open a command prompt and enter the following:

51

It’s worth taking a look at. It is usually dumped in c:\documents and settings/yourusername.) SQL Loader creates a log that explains how data was loaded and whether anything went wrong. You will probably find it by going to the Start menu and going to Oracle > Database Administration > SQLPlus Worksheet 52 . SQL*Plus Worksheet Another tool that you can install from the ITS dba website is the SQL*Plus Worksheet. but it provides a slightly more intuitive graphical interface for running queries and has two panes: one for the SQL queries and other commands and a second for the output. The worksheet works pretty much the same way as the SQL*Plus tool.ctl (You can set this up as a batch file.I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Sqlldr username/password@naudev control=c:\loaddata/class_info.

--------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 14 rows selected.1 1. SQL> select ename. 2. hiredate 2 from emp.--------.--------.--------. ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB --------CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK CLERK ANALYST CLERK HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 28-SEP-81 01-MAY-81 09-JUN-81 19-APR-87 17-NOV-81 08-SEP-81 23-MAY-87 03-DEC-81 03-DEC-81 23-JAN-82 14 rows selected. SQL> select * 2 from emp. i .I N T R O D U C T I O N T O S Q L A N D S Q L * P L U S Solutions Solutions to Exercises Exercise 2. EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB MGR HIREDATE SAL COMM DEPTNO --------. job.--------.

JOB --------ANALYST CLERK MANAGER PRESIDENT SALESMAN Exercise 2. SQL> select ename. DEPTNO --------10 20 30 40 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON 5.3. ENAME SAL ---------. SQL> describe dept Name Null? ------------------------------. ii . sal 2 from emp 3 where sal > 2850. ENAME DEPTNO ---------.-------DEPTNO NOT NULL DNAME LOC Type ---NUMBER(2) VARCHAR2(14) VARCHAR2(13) 4.--------JONES 2975 SCOTT 3000 KING 5000 FORD 3000 2. SQL> select ename. SQL> select distinct job 2 from emp. SQL> select * 2 from dept.--------JONES 20 3. deptno 2 from emp 3 where empno=7566.2 1.

---------. SQL> select ename 2 from emp 3 where ename like 'S%'. ENAME Old Salary New Salary ---------. SQL> select ename.-------EMPNO NOT NULL ENAME JOB MGR HIREDATE SAL COMM DEPTNO Type ---NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7.2) NUMBER(7. 12*(sal+75)"New Salary" 2 from emp 3 where ename='TURNER'. sal 2 from emp 3 where sal not between 1500 and 2850.--------SMITH 800 WARD 1250 JONES 2975 MARTIN 1250 SCOTT 3000 KING 5000 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300 10 rows selected.---------TURNER 18000 18900 6. iii . 12*sal "Old Salary". (Do this query first to find out what columns are in the table) SQL> describe emp Name Null? ------------------------------. ENAME ---------SMITH SCOTT 5. ENAME SAL ---------. 4.SQL> select ename.2) NUMBER(2) Then run the query on the following page.

--------. SQL> select max(sal) "Maximum". min(sal) "Minimum".3 1.SQL> select empno. job. 2 sum(sal) "Sum". 2 sal. Exercise 2. SQL> select count(empno) 2 from emp. mgr.--------. SQL> select count(job) "Number of Clerks" 2 from emp 3 where job='CLERK'.--------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10 14 rows selected. avg(sal) "Average" 3 from emp. ename as "Last Name". deptno 3 from emp.--------. Number of Clerks ---------------4 iv . EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 Last Name ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER JOB MGR HIREDATE SAL COMM DEPTNO --------. comm.--------. Maximum Minimum Sum Average --------.--------.--------. COUNT(EMPNO) -----------14 3.2143 2. hiredate.--------5000 800 29025 2073.

'ddth "of" Month') "Today's Date" 2 from dual. SQL> select to_char (sysdate.-------------------------------TURNER 208. ENAME HIREDATE ---------. Today's Date ----------------25th of January SQL> select to_char (sysdate. Today's Date --------------------------twenty-fifth of January 3.Exercise 3. hiredate 2 from emp 3 where hiredate between '01-JAN-82' and '31-DEC-82'. SQL> select ename. ENAME MONTHS_BETWEEN(SYSDATE. SQL> select sysdate 2 from dual. SYSDATE --------25-JAN-99 2.1 1. months_between (sysdate.--------MILLER 23-JAN-82 or v . 'ddspth "of" Month') "Today's Date" 2 from dual. hiredate) 2 from emp 3 where ename='TURNER'.HIREDATE) ---------.56175 4. SQL> select ename.

SQL> select ename.5 MANAGER 2450 2975 8275 2758.--------. avg(sal) 2 from emp 3 group by job.3333 PRESIDENT 5000 5000 5000 5000 SALESMAN 1250 1600 5600 1400 2. JOB COUNT(JOB) --------. hiredate 2 from emp 3 where hiredate like '%-%-82'.--------MILLER 23-JAN-82 Exercise 4. sum(sal). SQL> select job. JOB --------SALESMAN SALESMAN MANAGER MANAGER HIREDATE --------20-FEB-81 22-FEB-81 02-APR-81 01-MAY-81 ENAME ---------ALLEN WARD JONES BLAKE vi .---------ANALYST 2 CLERK 4 MANAGER 3 PRESIDENT 1 SALESMAN 4 Exercise 4. min(sal).--------ANALYST 3000 3000 6000 3000 CLERK 800 1300 4150 1037.2 1.--------. ENAME HIREDATE ---------. hiredate from emp where hiredate between '20-FEB-81' and '01-MAY-81' order by hiredate.1 1.--------. SQL> 2 3 4 select ename. job. max(sal). count(job) 2 from emp 3 group by job. SQL> select job. JOB MIN(SAL) MAX(SAL) SUM(SAL) AVG(SAL) --------.

deptno.deptno.3 1.deptno vii .--------ALLEN 1600 300 TURNER 1500 0 MARTIN 1250 1400 WARD 1250 500 Exercise 4. SQL> 2 3 4 select emp.dname 2 from emp e.ename.--------7566 3000 7839 2450 7782 1300 7788 1100 Exercise 4. SQL> 2 3 4 select ename.4 1. MGR MIN(SAL) --------. dept where emp. comm desc. or SQL> select e. SQL> 2 3 4 select ename. dept d 3 where e. SQL> 2 3 4 5 6 select mgr. emp.deptno=d.ename. sal. comm from emp where comm is not null order by sal desc. ENAME DEPTNO ---------.deptno=dept. e.2. dept.deptno order by ename. deptno from emp where deptno=10 or deptno=30 order by deptno.--------. ename. min(sal) from emp group by mgr having mgr is not null and min(sal) > 1000 order by min(sal) desc.--------CLARK 10 KING 10 MILLER 10 ALLEN 30 BLAKE 30 JAMES 30 MARTIN 30 TURNER 30 WARD 30 3. ENAME SAL COMM ---------.dname from emp. d.

deptno and loc='DALLAS'. e. d. e.------------ALLEN 30 300 CHICAGO WARD 30 500 CHICAGO MARTIN 30 1400 CHICAGO TURNER 30 0 CHICAGO 3.comm. dept d where e.-------------CLERK 20 RESEARCH MANAGER 20 RESEARCH ANALYST 20 RESEARCH CLERK 20 RESEARCH ANALYST 20 RESEARCH ENAME ---------SMITH JONES SCOTT ADAMS FORD viii . SQL> 2 3 4 select e. ENAME DEPTNO DNAME ---------.--------. e. e.loc from emp e.4 order by ename. d.job.-------------ADAMS 20 RESEARCH ALLEN 30 SALES BLAKE 30 SALES CLARK 10 ACCOUNTING FORD 20 RESEARCH JAMES 30 SALES JONES 20 RESEARCH KING 10 ACCOUNTING MARTIN 30 SALES MILLER 10 ACCOUNTING SCOTT 20 RESEARCH SMITH 20 RESEARCH TURNER 30 SALES WARD 30 SALES 2.deptno=d.deptno.deptno.deptno and comm is not null. dept d where e.ename.deptno=d.dname from emp e. JOB DEPTNO DNAME --------.--------.--------.ename.--------. SQL> 2 3 4 select e. ENAME DEPTNO COMM LOC ---------.

Sign up to vote on this title
UsefulNot useful