111
Lesson 01 Basic Introduction First let us understand the basic definitions of elements, fields, and items, columns, records, tables, datatypes, as well as primary and foreign keys. Elements, Fields and Items In this tutorial, we will use the terms: elements, fields and items interchangeably. A record also is the same as a row in a table. Columns, Tables, Records, and Datatypes To understand the relationships between tables, records, columns, and datatype consider the following. A field is the smallest unit in a table. A record is nothing more than a collection of fields or columns horizontally. A table holds a collection of records. Now each column must have its own datatype. A record can be added or inserted into a table. A value in a column can be changed and a record in a table can be deleted. Primary and Foreign Keys Relationships between two tables are normally established by defining primary or foreign keys. The following diagram shows relationship between the EMP (Employee) table and the DEPT (Department) table. The DEPTNO column in the EMP table is a foreign key and the DEPTNO column in the DEPT table is the primary key.

(SQL Tutorial)

Embed Size (px)

Citation preview

Page 1: (SQL Tutorial)

Lesson 01Basic IntroductionFirst let us understand the basic definitions of elements, fields, and items, columns, records, tables, datatypes, as well as primary and foreign keys.Elements, Fields and ItemsIn this tutorial, we will use the terms: elements, fields and items interchangeably.A record also is the same as a row in a table.Columns, Tables, Records, and DatatypesTo understand the relationships between tables, records, columns, and datatype consider the following.A field is the smallest unit in a table. A record is nothing more than a collection of fields or columns horizontally. A table holds a collection of records. Now each column must have its own datatype. A record can be added or inserted into a table. A value in a column can be changed and a record in a table can be deleted.

 Primary and Foreign KeysRelationships between two tables are normally established by defining primary or foreign keys.The following diagram shows relationship between the EMP (Employee) table and the DEPT (Department) table.The DEPTNO column in the EMP table is a foreign key and the DEPTNO column in the DEPT table is the primary key.

Page 2: (SQL Tutorial)

A primary key has the immutable responsibility of serving as a unique identifier in a table. A foreign key is a column that refers to the primary key of another table. To join two tables, a “where clause” is used to set up a table relationship between primary and foreign keys.Entity Relationship/Logical data Model"Entity Relationship Diagram" or "Logical Data Model" is used to establish relationships between entities. In the following diagram-an Entity Relationship Diagram For Company’s Customers and Their Orders--the relationship between the customer table and the order table, is established by their defined primary and foreign keys.The foreign key of the order table refers to the primary key of the customer table. A customer can have one or many orders. An order, however, can refer to one and only one customer.Composite IndexA primary key can be composed of more than one column. We call it a composite index.An example of a composite index is the Item table in the diagram. Note how the combination of two columns in the items table was used to create a primary key. These two columns are "itemid" and "orderid".You are going to use the EMP, ORD, ITEM, CUSTOMERS, PORTFOLIO, PRICE_HISTORY, etc tables in your Hands-On training during the entire tutorial.

 Entity Relationship Diagram For

Company’s Customers and their OrdersNow, observe the Entity Relationship Diagram for Company’s Customers and their portfolio carefully.The Customers table contains ID (customer id), first_name, last_name, etc. The customer id (ID) is the primary key of the customer table.In the portfolio table you have a composite index that contains the stock_symbol and customer_id columns. The customer_id column is a foreign key of the portfolio table and it refers to the primary key of the customer table.The stock_history table contains columns such as symbol, sales, high, low, etc. The symbol column in the stock_history table is the primary key. The symbol column as a primary key will refer to the foreign key (stock_symbol) in the portfolio table. As you can see a table can contain many foreign keys but only one primary key.

Page 3: (SQL Tutorial)

The price table has a composite index. Its composite index contains the symbol and trade_date columns. The symbol column in the price table is a foreign key. It refers to the primary key of the stock_history table.From this ERD, you will know that a customer may have 1 or many stocks; and a customer’s stock may have 1 or many recorded prices and so on. It is very important for a developer to understand the entity relationship diagram of his/her task. It will assist the developer on writing its SQL statement.Study these two entity relationship diagrams and try to understand them. Then start to work on our hands-on exercises.

 Entity Relationship Diagram For Company’s Customers and their Stocks Portfolio

DatabaseRemember, a collection of all these tables under a single or many different schemas can be stored and maintained in a database. A database, in effect, is a collection of tables.DBA vs. DevelopersThe integrity, security, connectivity, performance, and tuning of a database will be maintained by DBAs. One of the responsibilities of a DBA is to plan a contingency for disaster and ensure recovery of the database.

Page 4: (SQL Tutorial)

DBAs maintain the integrity of a database by using "backup and recovery". They perform Oracle client/server connectivity and do "performance tuning" to maximize availability and better response time for their clients. They may use Oracle Enterprise Management tools to perform and monitor their tasks.On the other hand developers use front-end and back-end tools along with management tools to perform their tasks. They develop applications to manipulate a database’s data. Their application will query, insert, delete and update a record or records. They use front-end tools such as "form builder," "report builder," and "graphics builder." They use back-end tools such as "schema builder," "procedure builder," and "query builder." They use project builder tools to manage and deliver their applications to their clients.We strongly advise you before writing any "SQL" statements to study first your table and have a solid understanding of the table's attributes and its data structure.Now, let's observe the employee table. We abbreviated the employee table to "EMP." The columns in this table are: Employee number, name, job, manager's id, hire date, salary, commission, and department number.

Notice that the manager id column references to the employee number. A manager is an employee of his/her company. On this type of table, you can establish a "selfjoin" condition.Before writing any query spend some time to understand the structure of the table and its data. A table contains information that describes an entity. It has ROWS and COLUMNS.

Page 5: (SQL Tutorial)

A row is a collection of information about a sub-entity. Here, for example, this table contains the company's employee information.A table may have a primary key. In this table, the first column (employee number) is a primary key. A primary key is a unique identifier for each individual employee. A table can have a foreign key. Here, the last column (department number) is a foreign key. A foreign key of a table always references to a primary key of another table. In this table, the foreign key references to the primary key of the department table. A table can have unique keys, composite keys, and index keys. Avoid having too many indexes in a table.Notice, the commission column and manager id columns have "null values." The employee number should not have a "null value", since it is a primary key. Notice that the manager id column refers to the employee number in the employee table.Once you understand the nature of your data in a table, you are ready to write a good query against that table.

Questions:Q: What are the definitions of the following items?column,record,table,item,field,element,primary key,foreign key, anddatatype.Q: What is the relationship between primary and foreign keys?Q: Describe the Entity Relationship diagram and Logical Data Model.Q: What is a composite index?Q: What are the responsibilities of an Oracle DBA and Oracle Developer?Q: What is a Database?

Lesson 02Selecting Data (SQL)In this section, you will learn how to query an Oracle Table.Go to MS-DOS and login to "SQLPLUS" as "iself” password “schooling."SQL> CONNECT iself/schooling@school SELECT statementsThe SELECT statement is a DML (Data Manipulation Language) statement. DML statements are SQL commands that allows you to retrieve and manipulate a data in the database. SQL commands are divided to three parts:DML - Data Manipulation Language are SQL commands that allows you to query and manipulate data such as UPDATE, SELECT, INSERT, and DELETE.DDL - Data Definition Language are SQL commands that allows you to create, alter, and/or remove an object in the database such as CREATE TABLE, DROP TABLE, ALTER TABLE, etc.DCL - Data Command Language are SQL commands that allows you to execute a command in the SQLPLUS such as CONNECT, etc.Query the employee names and their salaries from the employee table.SQL> SELECT ename, sal FROM emp;Column HeadingAs you notice from the above query statement, the columns heading were the columns name as a default. These column names most of the time are meaningless. You use the column heading to make them more meaningful.For the same above query, now you use the “as” clause for the column heading. Notice that the column heading is changed.SQL> SELECT ename, sal AS salary FROM emp;Use the same above query without using the “as” clause. The ‘as’ clause is a default option.SQL> SELECT ename, sal salary FROM emp;

Page 6: (SQL Tutorial)

Use the same above query to use a double quote for the ename and sal as “Full Name” and “Salary” column headings. You use a double quote if the column headings contain “case sensitive” or “blank” characters.SQL> SELECT ename “Full Name”, sal "Salary"FROM emp;Arithmetic ExpressionYou can use an arithmetic expression in the SELECT statement.Use an arithmetic expression that calculates a 10 percent salary bonus for all employees.SQL> SELECT ename, sal salary, sal * .1 bonusFROM emp;Use the dual table as a dummy table to execute the system's function, user's functions or any other arithmetic expressions.SQL> SELECT 100+200 total FROM dual;NULL valueA null value means I don’t know. Note that any number that is added, multiplied, divided, or subtracted from NULL will be NULL.Remember, the result of any arithmetic calculation with a "null" is a "null" value.SQL> SELECT 100+null “Null + 100”FROM dual;Query the employee names and their commissions. Notice that the commission column contains the null value.SQL> SELECT ename, comm commission FROM emp;NVL functionYou can use the NVL function to substitute any not NULL value with a NULL column. This way, you will get more control on how to manipulate that column in a WHERE clause.Use the null value function (NVL) to assign a zero to any null value in the commission column.SQL> SELECT ename, NVL(comm,0) commissionFROM emp;ConcatenationYou will use two vertical bars (||) to concatenate two or more strings or columns together.Use two vertical bars or pipe line to concatenate a last and first name with the following format (example: Smith, Joe).SQL> SELECT last_name || ', ' || first_name AS "full name"FROM customers;ORDER BY clauseYou use the ORDER BY clause to sort one or more columns in a query.Use the "order by" clause to sort a query. Query the employee names sorted by ascending order.SQL> SELECT enameFROM empORDER BY ename ASC;Query the employee names sorted by descending order.SQL> SELECT ename FROM empORDER BY ename DESC;WHERE clauseYou use the WHERE clause to query one or more records selectively.Query the employee information whose employee number is 7788.SQL> SELECT *FROM emp WHERE empno = 7788;

Page 7: (SQL Tutorial)

LIKE conditionThe LIKE conditions specify a test involving pattern matching. Whereas the equality operator (=) exactly matches one character value to another, the LIKE conditions match a portion of one character value to another by searching the first value for the pattern specified by the second. The pattern can contain the special pattern-matching characters:% matches any string of any length (including length 0)_ matches any single character.

To search for the characters % and _, precede them by the escape character. For example, if the escape character is @, then you can use @% to search for %, and @_ to search for _.Query the employee names whose names start with the letter “M.”SQL> SELECT ename FROM emp WHERE ename LIKE 'M%';Query the employee names whose names end with the letter “R.”SQL> SELECT ename FROM emp WHERE ename LIKE '%R';BETWEEN conditionThe BETWEEN conditions specify a test to query all the records between the selection values inclusively.Query the employees name whose salaries between 2000 and 3000 dollars.SQL> SELECT ename FROM emp WHERE sal BETWEEN 2000 AND 3000;Query the employees’ name that’s their names start with a letter ‘C’ and end with a letter ‘F’.SQL> SELECT ename FROM emp WHERE upper (ename) BETWEEN ‘C’ AND ‘EZZZ’;You used the UPPER function in the above query to convert all names to upper case in the case if the employee’s names are case sensitive. DECODE functionThe DECODE function is like an IF-THEN-ELSE statement. It compares the content of a column to each of the comparisons. If there is a match, then it replaces the value. If there is no match, then the else action will be performed.Query the employee names and their department names using the “DECODE” function. Check if the "department no" is 10 then print "accounting", else if the "department no" is 20 then print "research," or if the "department no" is 30 then print "sales". Anything else print "others."SQL> SELECT ename, DECODE (deptno, 10, 'Accounting',20, 'Research', 30, 'Sales',

'Others') AS "Department" FROM emp; Questions:Q: Query the employee names and their salaries from the employee table.Q: Do the above query and use an “as” clause for the “salary” column aliases or column headings.Q: Repeat the previous query and have “Full Name” for the ename’s column heading and “Salary” for the “sal” column heading.Q: What is the result of 100 + NULL?Q: Query the employee names with their commissions.Q: Use the (NVL) the null value function to assign zero to any null value in the commission column for the previous query.Q: Concatenate the customers’ last name and first name separated by comma.Q: Query the employees name sorted by ascending order.Q: Query the employees name sorted by descending order.Q: Query the employee information whose employee number is 7788.Q: Query the employees name whose names start with the letter “M.”Q: Query the employees name whose names end with the letter “R.”Q: Query the employees name whose salaries between 2000 and 3000 dollars.

Page 8: (SQL Tutorial)

Q: Query the employees name and their department name using the “DECODE” function. If the department number is 10 then print "accounting.” If the department number is 20 then print "research," or if the department number is 30 then print "sales." Anything else prints others.

Lesson 03Advanced Data SelectionIntroductionIn this section, you will learn about an ambiguous column and how you can prevent it. You will learn how to query against two (such as the department and employee tables) or more tables by joining them together. You also learn what a sub-query is and how to use it.Now, let’s before you join the department table and the employee table, first query them individually.SQL> SELECT * FROM dept; SQL> SELECT * FROM emp;INNER Join or EQUIJOINJoining two or more tables together is the best relational database usage. You relate the tables using the WHERE clause. The equal sign (=) in a query only retrieves records that have exact match.Query the employees name and their department name using user schemas to avoid the ambiguous column problem. Also, this is an example of the inner join or equijoin.SQL> SELECT ename, dname FROM emp, dept WHERE emp.deptno = dept.deptno;Use the previous query and use the table aliases to avoid the ambiguous column. Use the letter “e” for the employee table alias and the letter “d” for the department table alias.SQL> SELECT ename, dname, e.deptno FROM emp e, dept d WHERE e.deptno = d.dpetno;Ambiguous ColumnAn ambiguous column is a column that is not defined clearly. Having two tables with the same column name, you should reference them such that there is no ambiguity on their ownerships. The column name should be identified by alias to make it clear that to what table that column is belong.If you join two tables that contain a common column name, you should use the table aliases or the user schema. Otherwise the column would be an ambiguous column.The following is an example of an ambiguous column.SQL> SELECT ename, deptno FROM emp, dept WHERE deptno = deptno;In the above example the ‘DEPTNO’ column is an ambiguous column since there is no identifier to indicate that what table the DEPTNO column belongs.Cartesian productAvoid a Cartesian product. A “Cartesian” product is caused by joining “N” number of tables while you have less than “N-1” joins condition in the query.SQL> SELECT * FROM dept, emp;This is an example of a Cartesian product.OUTER JOINBy joining two or more tables using OUTER join, not only you retrieve all matching records but also you retrieve the records that do not match. For example that you may have an employee that you did not assign any department number for him or via versa.Try to query the department table again.SQL> SELECT * FROM dept;Notice, we have only three records.Insert a record to the department. Remember that we have no employee in the department table.

Page 9: (SQL Tutorial)

SQL> INSERT INTO dept VALUES (40, 'Finance', 'Ohio');Save the insert transaction.SQL> COMMIT;Now, query all the employee names and their department names including the entire department name with no employees.Use outer join. As you know there is no employee in the "Finance" department.Use + sign next to the column that has no match in it.SQL> SELECT ename, dname FROM emp e, dept d WHERE e.deptno (+) = d.deptno;SELF JOIN If a table refers to itself in the WHERE clause, we say that join is a selfjoin.Query the manager names with their employees sorted by the manager names. This is an example of a selfjoin.SQL> SELECT mgr.ename “Manager Name”, e.ename “Employee Name”FROM emp mgr, emp e WHERE mgr.empno = e.mgr ORDER BY mgr.ename;SUM, AVG, MIN, and MAX functions Query the department number and their total, average, min, and max salaries for each department.SQL> SELECT deptno, SUM(sal), AVG(sal), MIN(sal), MAX(sal) FROM empGROUP BY deptno;GROUP BY statement Query the department number and their total salaries that have more than 5 employees in their department.SQL> SELECT deptno, SUM(sal) FROM emp GROUP BY deptno HAVING count(*) > 5;IN clause Use the IN clause, when you are going to use OR.Query the employee names that work for the Research or Sales departments (the department number 20 or 30).SQL> SELECT ename, deptno FROM emp WHERE deptno IN (20, 30);Sub-query If you write a query within a query, you are using sub-query. In the WHERE clause, not all the time, you have a constant value to compare. If you have to query a value from table, then you need to write a sub-query. Query the employee names that work in the "accounting" department. Assuming the department number is unknown.SQL> SELECT ename FROM emp WHERE deptno IN (SELECT deptnoFROM dept WHERE dname = "ACCOUNTING"); Runtime variable If you have a query that you have to change its WHERE clause constants or column names over and over, you may use the runtime variables. You can substitute those values without changing or modifying the query script.Query the employee names of each department. Use the runtime variable to substitute the department number.Run to query department number 10.Run to query department number 20.Run to query department number 30.SQL> SELECT ename FROM emp WHERE deptno = &deptno;SQL> /Enter value 10.SQL> run Enter value 20.SQL> / Enter value 30.EXISTS statement You use the EXISTS clause to test existence of rows in the results of a sub-query. When you specify the exits operation in a WHERE clause, you must include a sub-query that satisfies the EXISTS operation. If the sub-query returns data, then the EXISTS operation will return TRUE and a record from the parent query will be returned.Query the customer names which have more than four orders.SQL> SELECT name FROM customer c WHERE exists (SELECT 'T'FROM ord WHERE custid = c.custid GROUP BY custid HAVING count(*) > 4);

Page 10: (SQL Tutorial)

 Questions:Q: What is an ambiguous column?Q: How can you resolve an ambiguous column problem?Q: What is a Cartesian product?Q: How can you avoid a Cartesian product?Q: What is an inner join or equi-join?Q: What is an outer join?Q: What is a self join?Q: Query all the employee names and their department including all the departments with no employees.Q: Query the managers’ name with their employees sorted by the manager name.Q: Query the department number and their total, average, min, and max salaries for each department.Q: Query the department no and their total salaries that have more than 5 employees working in their department.Q: Query the employees name that work for the Research or Sales department (the department number 20 or 30).Q: Query the employees name that work in the "accounting" department. Assuming the department number is unknown.Q: Query the employees name and use the runtime variable to substitute the department number? Then run it for following department no 10, 20, and 30.Q: Query the customer names which have more than four orders.

Lesson 04Create the Database objects Create table, Primary key, Foreign Key, Unique, and Delete Cascade Create an employee table that contains five columns: employee id, last name, first name, phone number and department number. The last and first name should be not null. Make a check constraint to check the department number is between 9 and 100. Make a primary constraint on the employee ID column. Make a foreign key constraint on the department number column. Use the "delete cascade" option to delete all records if parent gets deleted. Use the "phone number" as a unique key.SQL> CREATE TABLE employee (empid NUMBER(10), lastname VARCHAR2(20) not null, firstname VARCHAR2 (20) not null, phone_no VARCHAR2 (15), deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100), constraint pk_employee_01 PRIMARY KEY (empid), constraint fk_dept_01 FOREIGN KEY (deptno) references dept (deptno) ON DELETE CASCADE, constraint uk_employee_01 UNQUE (phone_no)); Always, start the constraint name with PK prefix for a primary key, FK prefix for a foreign key, UK prefix for a Unique key, or CK prefix for a check constraint.Creating a composite index If you have an index that contains two or more columns, we call them a composite index. When an index is a composite index, you should make sure that the first column position in the index always be in your WHERE clause. The more columns from the composite index that you have in the WHERE clause the faster you will be able to retrieve your data. Avoid creating too many indexes.Create an index table using the “Create Index” statement. Create a composite index that contains two columns (last name and first name).SQL> CREATE INDEX employee_lname_fname_ind_01 ON employee (lastname, firstname); USER_TABLES table You use USER_TABLES to query or view all table objects (schema) that are belong to the user who login to a database.Query the tables that iself owns. The “Employee” table should be listed.

Page 11: (SQL Tutorial)

SQL> SELECT table_name FROM user_tables ORDER BY table_name;  USER_INDEXES table You use USER_INDEXES to query or view all index objects (schema) that are belong to the user who login to a database. Indexes are attached to their tables. Dropping a table will drop all its indexes.Query the index tables that belong to the employee table and owns by the iself user.SQL> SELECT index_name, uniqueness FROM user_indexesWHERE table_name = 'EMPLOYEE'; Notice that there are three index tables of which two are unique. Make sure that table name is in uppercase. All tables’ name are stored in uppercase in the Oracle database. USER_CONSTRAINTS tableYou use USER_CONSTRAINTS to query or view all constraint objects (schema) that are belong to the user who login to a database. The same as indexes, the constraints are attached to their tables. Dropping a table will drop all its constraints. You use USER_CONSTRAINTS to view table dependencies with its different types of constraints.Query the constraints name of the employee table including their types and status.On the constraint type column, "C" is for a "null and check" constraint; "U" is for a unique key; "R" is for a foreign key; and "P" is for a primary key. The status column can be enabled or disabled.SQL> SELECT constraint_name, constraint_type, statusFROM user_constraintsWHERE table_name = 'EMPLOYEE'; COLUMN commandYou use the COLUMN command to change size or format of your column to be displayed.Syntax:COL[UMN] [{column|expr} [option ...]]options:ALIAS alias Assign an alias to a columnCLEAR Reset the display attributes Format a column (e.g. COL emp_name FORMAT A15)HEA[DING] 'text' Set a column headingJUSTIFY {L[EFT]|C[ENTER]|C[ENTRE]|R[IGHT]}LIKE {expr|alias}Format like another column (already defined)NEWLINE Same as FOLD_BEFORENOPRINT|PRINT Display the columnNUL[L] char Display NULL values as CharON|OFF Enable or disable column format attributesWRA[PPED]|WOR[D_WRAPPED]|TRU[NCATED]How to treat long CHAR stringsUse the column command to change the size of the "column_name" to 30 characters.SQL> COLUMN column_name FORMAT a30 USER_IND_COLUMNS tableUSER_IND_COLUMNS contains all information about those columns that are index. It keeps information such as index_name, column_name, table_name, column position, etc.Query the index columns of the employee table. Remember that on the composite index the sequence of the column would be the same as the column position. Notice that the last name has the first position and the first name has the second position in the composite index.

Page 12: (SQL Tutorial)

SQL> SELECT index_name, column_name, column_positionFROM user_ind_columnsWHERE table_name = 'EMPLOYEE'; INSERT statement using column namesThe INSET statement writes a record in to a table. The following are some of INSERT syntaxes that are frequently used:

Syntax: INSERT [hint] INTO [schema.] table [@dblink] [t_alias] (column, column,...) VALUES (expression) INSERT [hint] INTO [schema.] table [@dblink] [t_alias] VALUES (expression) INSERT [hint] INTO [schema.] table [[SUB]PARTITION (ptn_name)] (column, column,...) VALUES (expression) INSERT [hint] INTO subquery WITH [READ ONLY | CHECK OPTION [CONSTRAINT constraint] ] [t_alias] (column, column,...) VALUES (expression)

Insert a record into the "employee" table using column names. In this type of insert, the input data values are inserted by a position of column.For example, 100 goes to employee id; "smith" goes to the "lastname"; 10 goes to the "department number; "joe" goes to the "firstname"; and 703 821 2211 goes to the "phone_no" column.SQL> INSERT INTO employee(empid, lastname, deptno, firstname, phone_no)VALUES (100, 'smith', 10,'joe', ‘7038212211'); COMMIT statementA record will not be added to a table unless you execute the COMMIT statement. All not committed records are stored in UNDO segment. It will give you a chance to undo your transaction. COMMIT means save all none committed transaction. It guarantees that the DBA will be able to recover your data to the point of failure.Save the transaction.SQL> COMMIT; INSERT statement using the column positionInsert a record using the column position format. In this case, the input data are inserted by the sequences of position of columns in the table. For example, 200 goes into the first column of the table; "KING" goes into the second column of the table; and so on.SQL> INSERT INTO employeeVALUES (200, 'KING', 'Allen', 5464327532, 10); Save the transaction.SQL> COMMIT; Query the employee table.SQL> SELECT * FROM employee; UPDATE statementTo change a value of a column in a table, you use the UPDATE statement. You must use the WHERE clause for specific record or records. Notice that if you don’t use a WHERE clause then the entire table will be changed. That could be an action that you did not want it.

Page 13: (SQL Tutorial)

Change "Smith" to “Judd” where "employee id" is 100.SQL> UPDATE employeeSET lastname = 'Judd'WHERE empid = 100; Save the transaction;SQL> COMMIT; Query the employee table to see the changes;SQL> SELECT * FROM employee; DELETE statementA record or records can be deleted from a table by using the DELETE statement. Again the same as UPDATE, you must make sure to have a WHERE clause in your query. Avoiding a WHERE clause will delete your all records in the table.Delete the employee record where its employee id is 200.SQL> DELETEFROM employeeWHERE empid = 200; Save the transaction;SQL> COMMIT; Query the table.SQL> SELECT * FROM employee; DELETE all recordsAs we mentioned before, to delete all records, you only avoid a WHERE clause. You can also truncate a table. If you want to delete all records from a table, you should use the TRUNCATE statement. It will change the table watermark. The table watermark is an address that indicates a last location of a record in a table. On the DELETE statement the watermark will not change. But using the TRUNCATE statement will change the watermark to the beginning of the table.Delete all records from the employee table using the DELETE statement and do not commit.SQL> DELETE FROM employee; Query the table.SQL> SELECT * FROM employee; ROLLBACK statementIf you change, delete, insert a record into a table but not execute the commit statement. All your before transaction block images are in an UNDO segment. You can execute the ROLLBACK statement in order to undo your transaction. It is a perfect statement for correcting a user mistake such as deleting a table’s records.Undo the delete transaction, as long as you did not commit the transaction.SQL> ROLLBACK; Query the employee table again.SQL> SELECT * FROM employee;

Page 14: (SQL Tutorial)

All records are back. Notice that you only are able to undo a transaction to the last point that you executed a COMMIT statement. TRUNCATE statementNow, truncate the employee table.SQL> TRUNCATE TABLE employee;Do not commit. Notice that the TRUNCATE command is a DDL statement and all DDL statements have commit inclusive. That is why the ROLLBACK action after truncation does not work. Undo the truncation.SQL> ROLLBACK; Query the employee table again.SQL> SELECT * FROM employee; Note that you lost all the data. Always remember that the truncate statement is a DDL statement and in all the DDL statements the commit is implicit. 

"People demand freedom of speech to make up for the freedom of thought which they avoid." - Soren Aabye Kierkegaard (1813-1855)

Questions:Q: Create an employee table that contains five columns:Such as Employee Id, last name, First name, Phone number and Department number with the following constraints.1. The last name and first name should be not null.2. Make a check constraint to check the department number is between 9 and 100.3. Make a primary constraint on the employee ID column.4. Make a foreign key on the department number column.5. Use the "delete cascade" to delete all records if parent gets deleted.6. Use the "phone number" as a unique key.

Q: Create a composite index on the employee table that contains two index columns (last name and first name).Q: Query the tables that you as a user own.Q: Query the index tables that belong to the employee table and owns by the iself user.Q: Change the size of the "column_name" to 30 characters logically (for display only.Q: Query the indexes columns of the employee table.Q: Insert a record into the "employee" table using column names.Q: Insert a record using the column position format.Q: How do you save the inserted transaction?Q: Change the "last_name" column value from “Smith” to “Judd” where the "employee id" is 100.Q: Delete all the employee records from the "employee" table using the delete command and the truncate command.Q: How do you undo a transaction?Q: What is the difference between the delete statement and the truncate statement?

Page 15: (SQL Tutorial)

Lesson 05"Not everything that can be counted counts, and not everything that counts can be counted." - Albert Einstein (1879-1955)

Read first then play the video:     SQL008(VIDEO)-Creating Other Oracle Database Objects 

Creating more Database ObjectsSET SQLPROMPTSometime you may want to open multiple SQLPLUS sessions. It is very normal that you may not know that what session you are in. To avoid this confusion, you can use the SQLPROMPT option to stay away from such problem.In this hands-on, you need to open three sessions. Each session will be a different user. For example, in the first session login to "sqlplus" as "iself” password “schooling"MS-DOS> SQLPLUS iself/schoolingSet the sql prompt to “iself.”SQL> SET SQLPROMPT ‘iself > ’ Go to the second session and login to "sqlplus" as “system” password “manager.”MS-DOS> SQLPLUS system/managerSet the sql prompt to “system.”SQL> SET SQLPROMPT ‘system > ’ Go back to the iself session. DROP TABLEWhen you drop a table all its dependencies such as its indexes, constraints, and triggers will be deleted. All the views, procedures, packages, and functions that reference to that table will be in an invalid status.Drop the employee table.SQL> DROP TABLE employee; CREATE TABLE AS …If you want to copy a table, you can use the CREATE TABLE AS statement. It copies all records. Notice that the new table will not inherit any constraints, indexes, and triggers from original table. Only records will be copied not dependencies.Copy column of employe name, job, commission and department number of the “EMP” table to the employee table.SQL> CREATE TABLE employeeAS SELECT ename, job, comm, deptnoFROM emp; DESCRIBE commandWhen you create a table, you would like to know what its columns’ name and their attributes are. The DESC command will display such information. Notice that you will not find its indexes information, and constraints’ name.Describe the employee table.SQL> DESC employee 

Page 16: (SQL Tutorial)

ALTER TABLE ADD …Once you create a table, you may want to delete, resize, or add more columns to it. The ALTER TABLE ADD statement will add a column or add a constraint to a table.Add a salary column to the employee table.Use "add" clause to add a column.SQL> ALTER TABLE employeeADD (salary NUMBER(8,2)); Describe the employee table.SQL> DESC employeeThe "salary" column was added. ALTER TABLE MODIFY …The MODIFY option in the ALTER TABLE statement, can change a column’s datatype and its length. Note that if you decrease a column’s length, you may truncate some of the data in the column. Therefore, Oracle will not allow you to reduce the length of a column unless it is null. So in order to reduce a column’s size, just copy that column to an alternative table, and then null the column and change the size. Then put the column values back. If the column has constraint, you may have to disable the constraint.Change the "ename" column size from 10 to 15.Use the "modify" clause to modify the column table.SQL> ALTER TABLE employeeMODIFY (ename VARCHAR2(15)); Describe the employee table to see the changes.SQL> desc employee RENAME commandThe RENAME command will change the table’s name. Remember that when you change the table name, all the status of those views, procedures, functions, and packages that were referencing to the table will be changed to an INVALID mode. You should modify them (views, procedures, functions, and packages) in order to force them to refer to the new table; and once they have been compiled or used, their status will be changed to a VALID mode.Rename the "employee" table to the "iself_employee" table.SQL> RENAME employee TO iself_employee; Query the iself_employee table to make sure that its data was not changed.SQL> SELECT * FROM iself_employee; CREATE VIEW AS …You use view to present rows and columns of a table in the way you want. You may use it for security reason. For example, you may eliminate some rows and columns that are very sensitive information. These changes are transparent to a user. There are two types of views. They are Simple View and Complex View. A Simple View is a view that was created only from one single table. In the contrast a Complex View is a view that it has two or more tables joining together. You may also insert, update, and delete a record using simple views. Do not try to insert, update, or delete a record from a complex view.Create a view to display only the employees name of the “Accounting” department.You may use a view for a security reason.This is an example of a simple view.

Page 17: (SQL Tutorial)

SQL> CREATE VIEW employee_nameAS SELECT enameFROM iself_employeeWHERE deptno = 10; Query against the new view to see the output.SQL> SELECT * FROM employee_name; ALTER VIEW …As we mentioned before, when you rename a table, all the status of its associated views, procedures, functions, and packages become in an invalid mode. One way to change the status from invalid to valid is to use the ‘ALTER VIEW’ statement with the COMPILE option.The view should be compiled if its status is invalid.Compile the view.SQL> ALTER VIEW employee_name COMPILE; DROP VIEW …A view can be dropped if it is not needed. When you drop a view, all the tables used in the view will be untouched. But all the views that were created using the dropped view, their status will change to an INVALID mode.Drop the employee_name view.SQL> DROP VIEW employee_name; CREATE INDEX commandWhen you use the WHERE clause in your SQL statement, Oracle’s optimizer will check to see whether you have an index on that column or not. If not, then it will scan the whole table. If your table is a long table which normally it is. It may take a very long time to retrieve that query. Creating an index on a column that you normally have it in the WHERE clause, will eliminate to scan the table. Creating an index will increase a performance of a query. Keep this in mind, just making all columns index because that will increase a query’s performance, it is not a good practice. When you create an index on a column, any insert, update, and delete has to do one more task to maintain the index table. That may cause some performance problem.There are different types of indexes:1- B-Tree index,2- Bitmap index, and

B-Tree indexWhen you create an index table by default will be the B-Tree index, unless you specify otherwise. The B-Tree index is the traditional index. It stores your data in a treelike fashion. It has the root node, which is an entry point for your search. It contains pointers to other nodes. The pointers in the root node point to another level in the index, which we call them branch nodes. The branch nodes also contain pointers to other nodes to the next level of node in the index. The highest level of the index is called the leaf nodes. Each leaf node is linked to its right and left leaf nodes. You create a B-Tree index on a column, if that column has a very high cardinality. The more unique value in a column represents a higher cardinality. For example: assuming that I have a table that contains 1000 records. If one of its columns (column c1) has 995 unique values against 1000 values, then that column has a high cardinality. In the contrast if one of its columns (columns c2) has 25 unique values against all 1000 values, then that column has a low cardinality.

Page 18: (SQL Tutorial)

Bitmap IndexYou create a bitmap index against a column when you have a low cardinality. Think of a Bitmap Index as a matrix. Its columns correspond to all unique values in the column. Notice that the higher cardinality brings more columns in your index table. That is the reason; why you should use a Bitmap Index when your column has a very low cardinality.Now, create a B-Tree index on the employee name column on the employee table.SQL> CREATE INDEX employee_ename_ind_01ON iself_employee (ename); ALTER INDEX REBUILDAn index table can be reorganized if it has fragmentation. A table may have fragmentation when you deleted lots of records or your table contains lots of migration or chained records.Assuming that your employee_ename_ind_01 index table, it has an index fragmentation. Reorganize the index table.SQL> ALTER INDEX employee_ename_ind_01 REBUILD; DROP INDEX …An index table can be dropped, if it is not needed. When you drop an index table, its table will not be dropped.Drop the employee_ename index table.SQL> DROP INDEX employee_lname_ind_01;Go to the "system/manager" session. CREATE USER …No one can login to Oracle unless they have userid and password. They should also have been granted to ‘CREATE SESSION.’ Otherwise, they will not able to login to SQLPLUS. They should have some system privileges in order to do their task such as CREATE TABLE, CREATE PROCEDURE, ALTER TABLE, etc. Make sure always to assign a default tablespace and a temporary tablespace to a user. Make sure that they are not able to write in the SYSTEM tablespace. Later in this book, you will learn how to stop users to create an object in the SYSTEM tablespace.Create a user with username “newuser” and password "newpass."Make its default tablespace as "iself_data."SQL> CREATE USER newuser IDENTIFIED BY by newpassDEFAULT TABLESPACE iself_data; GRANT RESOURCE, CONNECT statementThe RESOURCE and CONNECT roles contains some system privileges that allows users to login, create table, alter table, etc. For example: The CONNECT role has the CREATE SESSION system privilege. A user without the CREATE SESSION system privilege can not even login to SQLPLUS.Notice that the user can not connect or create any objects unless the privileges are granted to it. Grant the resource and connect roles to newuser.SQL> GRANT resource, connect TO newuser;Go to the third session and connect as newuser password newpass.SQL> sqlplus newuser/newpassSet the sql prompt to newuser. The SQLPROMPT option is a good command to show a user that what session he/she is in.SQL> SET SQLPROMPT ‘newuser > ‘ 

Page 19: (SQL Tutorial)

ALTER USER …Change the password often. It is a good practice. You as a user can only change your password by using the ALTER USER statement. You can not do any other altering such as changing your default tablespace, etc. The only user that can change your default tablespace is the one has already been granted the ALTER ANY USER system privilege.Change the newuser password to "mypass".SQL> ALTER USER newuser IDENTIFIED BY mypass; Users should be granted access by other users to query their tables.Query the iself_employee table.SQL> SELECT * FROM iself.iself_employee;No access granted.Go to the “system/manager” session CREATE PUBLIC SYNONYM …You create public synonym so that the users don’t need to type schema name to a table when they query the table. Creating a public synonym does not mean that oracle users can access to that table or object. Still the owner of the object has to grant access to a user on its table.Create a public synonym. The public synonym must be unique to an object. The public synonym ‘employees’ is exit.SQL> CREATE PUBLIC SYNONYM employees FOR iself.iself_employee; DROP PUBLIC SYNONYM …It comes a time that you may have to drop a public synonym. Dropping a public synonym, it doesn’t drop its dependencies.Drop the public synonym.SQL> DROP PUBLIC SYNONYM employees;Then create it again.Now, all the users that can access to iself’s employee table should be able to access it through the public synonym.Go to the "iself" session GRANT commandYou can grant an specific object privilege to user or all the privileges.For example:GRANT SELECT gives only a query access on a table.GRANT UPDATE gives only a write access on a table.GRANT DELELTE gives only a delete access on a table.GRANT INSERT gives only an insert access on a table and more…GRANT ALL gives all the access on a table to a user.Grant select and update on the employee table to the newuser. The newuser can not delete or insert any record.SQL> GRANT SELECT, UPDATE ON employee TO newuser;Go to the "newuser” sessionQuery the employee table using its public synonym.SQL> SELECT * FROM employee; Private SynonymSometime when you access to an object, you may have to type a lot of words. For example; I can access to a table like this:

Page 20: (SQL Tutorial)

SELECT * FROM [email protected];Notice that typing [email protected] is not very practical every time. So, you may create your own private synonym.SQL> CREATE SYNONYM empFOR [email protected];From now on, you can access to the table by using emp. For example:SQL> SELECT * FROM emp;When you create a private synonym, it will be used only by you. No one can use that synonym.Create a private synonym emp_table for the iself employee table.SQL> CREATE SYNONYM emp_table FOR iself.iself_employee; Query the table using the “emp_table” private synonym.SQL> SELECT * FROM emp_table; DROP SYNOMYM …A user can drop its private synonym if is not needed.Drop the emp_table private synonym.SQL> DROP SYNONYM emp_table; Go to the "iself" session and revoke the privileges from "newuser."It comes a time that you may have to revoke some object or system privileges from a user.Notice that an object privilege may have been granted to a user by using WITH GRANT OPTION. If that is the case then when you revoke an object privilege from a user, all the object privileges that were granted by that user to some other Oracle users will be revoked too.In the contrast with the WITH GRANT OPTION, if a system privilege was granted WITH ADMIN OPTION. When you revoke it, all the system privileges that were granted by that user to some other Oracle users will not be revoked.Revoke the update and select privileges on the employee table from newuser.SQL> REVOKE UPDATE, SELECT ON employee FROM newuser; Back to the "newuser" session.Query the employee table.SQL> SELECT * FROM employee;No access. 

"Only two things are infinite, the universe and human stupidity, and I'm not sure about the former." - Albert Einstein (1879-1955)

Questions:Q: Copy the “EMP” table to another table and name the new table "employee." In the new employee table use the employee name, job, commission and department number.Q: Add a salary column to the employee table.Q: Modify the "ename" column size from varchar10 to varchar15.Q: Rename the "employee" table to the "iself_employee" table.Q: Create a view to display the employee names of the “Accounting” department only.Q: Why do you use the view?

Page 21: (SQL Tutorial)

Q: How do you compile the view?Q: How do you delete the view?Q: Create an index on the employee table on the ename column only and name it employee_indx.Q: Reorganize the “employee_indx” index table.Q: Drop the employee_ename index table.Q: Create a user with username “newuser” and password "newpass." Its default tablespace should be the "iself_data" tablespace.Q: Grant the resource and connect roles to newuser.Q: Change the newuser password to "mypass".Q: Can the above new user access to any other user tables?Q: What is a public synonym?Q: What is the syntax to create a public synonym?Q: What is the difference between public and private synonym?Q: Create and drop a private synonym.Q: Revoke an object privilege on a table from a user.

Lesson 06"A lie gets halfway around the world before the truth has a chance to get its pants on." - Sir Winston Churchill (1874-1965)

Read first then play the video:   SQL009(VIDEO)-SQL and PL/SQL Command editors

Command Line editingGo to MS-DOS and make a new directory to be used for your new scripts and programs.Login to SQLPlus from DOSChange directory to the root directory.DOS> cd .. Make a directory called "iself".DOS> mkdir iself Change the directory to the iself directory.DOS> cd iself List directory. Notice that there is nothing in it.DOS> dir Login to “sqlplus” as "iself” password “schooling".SQL> sqlplus iself/schooling SQLPlus default directoryFrom now on the “iself” directory is a default directory for “SQLPLUS.” Query the dept table.SQL> SELECT deptno, dname, loc FROM dept; Command line editing

Page 22: (SQL Tutorial)

You should know command line editing since it is a universal editor regardless of the operating system platform. You can use it at IBM, UNIX, LINUX, DOS, and any other operating system. Learn it well, since it may come handy.Oracle BufferRemember that always your last “SQL” statement is in the Oracle buffer.L commandType the letter "L" to list the last entered “SQL” statement.SQL> lThe asterisk next to the line indicates the current line position. RUN commandsRun the “SQL” statement in the buffer, using the "run" command.SQL> run-or- the letter "r."SQL> r-or- "/"SQL> / Semi-column in OracleYou enter a semi-column at the end of each SQL statement. It means to terminate a SQL statement and execute the statement in the Oracle buffer.Write a format free “SQL” statement to query the dept table; and enter each word in a line.SQL> SELECTdeptno,dname,locFROMdept;End the SQL statement with “;” to terminate and execute the statement. List the statement from the Oracle buffer.SQL> L A dot (.) in a SQL statementYou enter a dot at the end of your SQL statement to tell Oracle that it is the end of my SQL statement and do not execute the statement. You may do that if for some reason you want to change your SQL statement in the Oracle buffer.Write a format free query and use a dot at the end of the sql statement to end the statement, but not run the statement.The sql statement will be in the Oracle buffer as long as it was not replaced or the user session was not terminated.SQL> SELECTdeptno,dname,locFROMdept.

Page 23: (SQL Tutorial)

 Then run the statement.SQL> r “c” or CHANGE commandUse the command line editor to add ‘location’ a column heading to the "loc" column. First, you should change the current line position to number 6 and then use the "C" or change command to add column heading.SQL> L6SQL> c/loc/loc "location"/ Listing lines within a rangeList the sql statement lines from 2 to 7.SQL> L 2 7 List the entire query.SQL> LDeleting lines within a rangeDelete the sql statement lines from 4 to 5.SQL> del 4 5 Run the query. Notice that the department name column was deleted.SQL> / Positioning a SQL linePosition line number 3 to the current line.SQL> L3 “I” or INSERT commandUse the "i" or insert command to insert a line.Then use the dot to terminate the insert mode.SQL> i4i dname, List the query. The line was added.SQL> L Then run the statement.SQL> / SAVE commandSave the sql statement as "d-e-p-t" file in the “iself” directory. Notice that the default extension is “s-q-l.”SQL> save dept GET commandUse the "get" command to replace the sql file into the buffer.SQL> get dept EXIT command

Page 24: (SQL Tutorial)

Exit “sqlplus” to see where the file was stored?SQL> exit List the file names in the iself directory.DOS> dir TYPE commandUse the "type" command to list the query.DOS> type dept.sql Login to "sqlplus" as “iself/schooling”DOS> sqlplus iself/schoolingList the buffer. Notice that there is no query in the buffer. Get the file and then run it. SQL> l SQL> get dept/“@” commandor use the "@" sign command to run the file.SQL> @c:START commandOr use the "start" command to run the file.SQL> start dept These are different ways you can run the SQL script file. 

"I do not feel obliged to believe that the same God who has endowed us with sense, reason, and intellect has intended us to forgo their use." - Galileo Galilei

QuestionsQ: What does the LIST or ‘L’ command line editor?Q: What does the INSERT or ‘I’ command line editor?Q: What does the DEL or ‘D’ command line editor?Q: How do you change a string in the Oracle Buffer?Q: How do you save the SQL script in the Oracle Buffer?Q: How do you open the SQL Script into the Oracle Buffer?

Lesson 07"The artist is nothing without the gift, but the gift is nothing without work." - Emile Zola (1840-1902)

Read first then play the video:    SQL010(VIDEO)-SQL and PL/SQL Notepad editor

Notepad EditingWhy notepad editing and use of afiedt.buf

Page 25: (SQL Tutorial)

Oracle makes provisions for you to utilize your favorite text editor to edit the statement created in "afiedt.buf," the file into which SQL*PLUS stores the most recently executed SQL statement. You simply type edit (abbreviated "ed"). This action causes Oracle to bring up the SQL statement in "afiedt.buf" into the operating system's default text editor. DEFINE_EDITOR commandTo change the text editor, issue the define_editor='your editor' statement from the SQL*PLUS prompt. Try to use a text editor rather than the Command Line editor. Go to MS-DOS and change the directory to the iself folder.SQL> cd .. Login to “sqlplus” as "iself/schooling".SQL> sqlplus iself/schooling Get the dept file.SQL> get dept “ed” commandYour default editor is notepad. Use the "ed" command, to call notepad. On notepad, you can modify the query. Then close the window and click on Yes to replace the changes to the buffer.Notice that when you use the ‘ed’ command in the sqlplus, your defined editor will bring the last SQL statement from Oracle buffer. Now, you should be able to modify the SQL statement. After you modify your query, you can save and exit from the defined editor. By default that is NOTEPAD.Remember that when you bring your SQL statement into your editor the ‘;’ character will be disappeared and instead a ‘/’ character will be replaced. Leave the SQL statement with ‘/’ character and don’t enter ‘;’ character at the end of your SQL statement.Also, you should not work in the defined editor one SQL statement at a time. You can not have multiple SQL statements. Notepad as an independent toolIf you want to use multiple SQL statements or to write your SQL script, you may want to open your own independent editor from the SQLPLUS tool.And the technique you may want to use is to open the notepad as an independent tool.To open the dept script from the iself directory, open notepad as a separate window and then open the "dept" file from the "iself" folder.Add a column heading. Change the statement to query only the department number 10.Save the file. Save the file at the iself folder. Go to “SQLPLUS.”Get the "dept" file.SQL> get dept Notice that the changes are in the buffer, run the query.SQL> run Use the “Start” command to run the query.Go to notepad

Page 26: (SQL Tutorial)

 Remove the department number column.Save the changes.Go back to “SQLPLUS.”Use the @ sign to run the file.No department number this time.

"This book fills a much-needed gap." - Moses Hadas (1900-1966) in a review

Questions:Q: How do you use the notepad editor?Q: What is afiedt.buf?Q: How do you change your text editor in the SQLPLUS tool?Q: What does the ed command in the SQLPLUS tool?Q: Can you have multiple SQL statements in the afiedt.buf file?Q: How do you use the notepad editor as an independent tool in the SQLPLUS utility?Q: How do you execute or run a SQL script?

Lesson 08“It is possible to fail in many ways...while to succeed is possible only in one way.” Aristotle (384 BC - 322 BC), Nichomachean Ethics

Read first then play the video:    SQL011(VIDEO)-Oracle9i and up SQL New Features

Oracle9i: SQL ANSI statementsCONNECT commandConnect to SQLPLUS as the iself user.SQL> CONNECT iself/schoolingSET commandLet's begin by setting the linesize to 100 and the pagesize to 55.SQL> SET LINESIZE 100 PAGESIZE 55Now, let's compare the Oracle9i ANSI (American National Standards Institute) standard JOIN syntax with the original join syntax. Query the employee name, department number, and department name columns from the EMP table and DEPT table.Join command using original syntaxFirst, let us exclude all of the sales department information by using the original Oracle join syntax.SQL> SELECT ename, dept.deptno, dnameFROM emp, deptWHERE emp.deptno = dept.deptnoAND dname <> 'SALES'/JOIN syntax (ANSI)And now, use the Oracle9i ANSI standard JOIN syntax.SQL> SELECT ename, dept.deptno, dnameFROM emp JOIN deptON emp.deptno = dept.deptnoAND dname <> 'SALES'

Page 27: (SQL Tutorial)

/Notice, that you get the same result.NATURAL JOIN syntax (ANSI)Use the Oracle9i ANSI standard NATURAL JOIN syntax to join the EMP and DEPT tables where the employees' salary is greater than 3000 dollars.SQL> SELECT ename, deptno, dnameFROM emp NATURAL JOIN deptWHERE sal > 3000/Notice that in the NATURAL JOIN syntax, you don't need a WHERE clause since the department number is the same.USING clauseUse the USING clause to join the EMP and DEPT tables where employees' salary is greater than 3000 dollars.SQL> SELECT ename, deptno, dnameFROM emp JOIN deptUSING (deptno)WHERE sal > 3000/Notice that in the USING clause the join column names must be the same.CROSS JOIN syntax (ANSI)Use the Oracle9i ANSI standard CROSS JOIN syntax with no WHERE clause to create a Cartesian product.

Query the department name and employee name where the department number is (10 or 30) and the employees are (SMITH, ALLEN, and WARD).SQL> SELECT dname, enameFROM dept d CROSS JOIN emp eWHERE d.deptno IN (10,30) andename IN ('SMITH','ALLEN','WARD')ORDER BY dname/This is an example of an Oracle9i ANSI standard CROSS JOIN syntax.OUTER JOIN syntax (ANSI)Using the OUTER JOIN option, not only will you query records that have matches but you also see the rows that have no matches.The Oracle9i ANSI Join syntax provides three separate capabilities: RIGHT, LEFT, and FULL OUTER JOIN. The word OUTER is redundant and usually omitted.RIGHT OUTER JOIN syntax (ANSI)Let's demostrate the RIGHT OUTER JOIN syntax usage.

First, add a Finance department to the department table with no associated employees.SQL> INSERT INTO deptVALUES (40,'FINANCE','WASHINGTON,DC')/SQL> COMMIT;Query all employee names with their department's name. With that in mind to:-- Exclude all of the sales department information;-- Include all of the departments that have no employees.

Page 28: (SQL Tutorial)

Use the original oracle join syntax to do the OUTER JOIN query.SQL> SELECT nvl(e.ename,'No Match'), d.deptno, d.dnameFROM dept d, emp eWHERE d.deptno = e.deptno (+)AND dname <> 'SALES'/Notice that FINANCE deptartment has no match.Write the same above query, using the Oracle9i ANSI standard RIGHT OUTER JOIN syntax.SQL> SELECT nvl(e.ename,'No Match'), d.deptno, d.dnameFROM emp e RIGHT OUTER JOIN dept dON d.deptno = e.deptnoWHERE dname <> 'SALES'/LEFT OUTER JOIN syntax (ANSI)Add an employee who doesn't work in any of the departments yet.

Make sure to disable the foreign key before inserting a record.SQL> INSERT INTO empVALUES (9900,'KAZ','CLERK',7902,TO_DATE(sysdate),1000,NULL,NULL)/COMMIT/Query all of the employee names including those who don't work for any department.

Use the original Oracle syntax.SQL> SELECT e.ename, d.deptno,nvl(d.dname,'No Match') as departmentFROM dept d, emp eWHERE d.deptno (+) = e.deptno/Notice that employee KAZ does not work for any department.List the same above query by using the Oracle8i ANSI standard LEFT OUTER JOIN syntax.SQL> SELECT e.ename, d.deptno,nvl(d.dname,'No Match') as departmentFROM emp e LEFT OUTER JOIN dept dON d.deptno = e.deptno/FULL OUTER JOIN syntax (ANSI)Let's perfom an excercise to use the FULL OUTER JOIN option to find all of the records that have no matches in the two joined tables.SQL> SELECT nvl(e.ename,'No Match') as name,d.deptno,nvl(d.dname,'No Match') as departmentFROM emp e FULL OUTER JOIN dept dON d.deptno = e.deptno/That would be difficult to do with an original Oracle syntax.Delete the FINANCE department and the KAZ employee.SQL> DELETE FROM dept

Page 29: (SQL Tutorial)

WHERE deptno = 40/DELETE FROM empWHERE empno = 9900/SQL> COMMIT/You have deleted the records so that you can repeat these steps over and over again. 

"I'm living so far beyond my income that we may almost be said to be living apart." - e e cummings (1894-1962)

Questions:Q: What is the SQL ANSI statement?Q: What is the difference between the SQL ANSI statement and Original Oracle statement?Q: Is the SET command a SQL statement?Q: How do you change your workstation’s page size or line size?Q: What does the JOIN syntax in the Oracle SQL (DML) statement?Q: What is the difference between the JOIN syntax and the NATURAL JOIN syntax?Q: What does the USING clause in the Oracle SQL statement?Q: When can you not use the USING clause?Q: What is the advantage of the NATURAL JOIN syntax?Q: What does the CROSS JOIN syntax in the Oracle SQL statement?Q: What does the IN clause in the Oracle SQL statement?Q: What do the OUTER JOIN, RIGHT OUTER JOIN, LEFT OUTER JOIN, and FULL OUTER JOIN syntax in the Oracle SQL statement?Q: How can you perform the FULL OUTER JOIN syntax using the Original Oracle syntax?

Lesson 09"Give me a museum and I'll fill it." - Pablo Picasso (1881-1973)

Read first then play the video:    SQL012(VIDEO)-WITH SUMMARY AS and MERGE statements 

Oracle9i: More SQL New FeaturesLogin as the iself user.SQL> CONNECT iself/schoolingSet the linesize to 100 and the pagesize to 55.SQL> SET LINESIZE 100 PAGESIZE 55WITH … AS statementIf you have a query which it needs to process the same sub-query several times, you should consider using the WITH …AS clause in your statement.This process will help you a great deal of performance. The query will create a temporary table to query it over and over.Use the (WITH ... AS) statement to query all the department names that their total paid salaries are more than 1/3 of the total salary of the company.SQL> WITH summary_totals AS(SELECT dname,

Page 30: (SQL Tutorial)

SUM(sal) AS totalsFROM emp NATURAL JOIN deptGROUP BY dname)SELECT dname, totalsFROM summary_totalsWHERE totals > (SELECT SUM(totals)*1/3FROM summary_totals)ORDER BY totals DESCSQL>/Multiple columns in SQL statementYou can use multiple columns to match the multiple columns returned from the sub-query.

Get the name of all employees who earn the maximum salary in their department.SQL> SELECT deptno, ename, job, salFROM empWHERE (deptno, sal) IN(SELECT deptno, MAX(sal)FROM empGROUP BY deptno)/Inline ViewIf you have a sub-query in a FROM clause in the Oracle SQL statement, is called an inline view.Use the (inline view) to query all of the employee names, jobs, and salaries where their salary is more than 10% of the total company paid salary.SQL> SELECT ename, job, salFROM (SELECT ename, job, salFROM empWHERE sal > (SELECT SUM(sal) * .1FROM emp)ORDER BY 3)/This is an example of the inline view query.MERGE statementTo show an example of how the MERGE statement works, pay careful attention to the following demonstration.

First, create a table with two columns.SQL> CREATE TABLE Merge2Here (c1 NUMBER, c2 VARCHAR2(10))/Write a stored procedure to populate the table.SQL> BEGINSQL> FOR i IN 1..10 LOOPSQL> INSERT INTO Merge2Here VALUES (i, i+10);SQL> END LOOP;SQL> COMMIT;SQL> END;SQL> /Then, create a second table with three columns.SQL> CREATE TABLE MoreGoodRows

Page 31: (SQL Tutorial)

(cc1 NUMBER, cc2 VARCHAR2(10), cc3 NUMBER)/Write a stored procedure to populate it.SQL> BEGINSQL> FOR i IN 1..3 LOOPSQL> INSERT INTO MoreGoodRows VALUES (i, i+10, i+20);SQL> END LOOP;SQL> FOR i IN 104..110 LOOPSQL> INSERT INTO MoreGoodRows VALUES (i, i+10, i+20);SQL> END LOOP;SQL> COMMIT;SQL> END;SQL> /Now, query the Merge2Here table.SQL> SELECT * FROM Merge2Here/Also, query the MoreGoodRows table.SQL> SELECT * FROM MoreGoodRows/Take notes about the data in these two tables.Use the MERGE statement to merge the MoreGoodRows table into the Merge2Here table using the first column as a join column. If there was a match, you should replace the third column value of MoreGoodRows with the second column of the Merge2Here table. On the other hand, if there was no match, just insert the first two columns of data into the Merge2Here table.SQL> MERGE INTO Merge2HereUSING MoreGoodRowsON (c1 = cc1)WHEN MATCHED THENUPDATE SET c2 = cc3WHEN NOT MATCHED THENINSERT VALUES (cc1, cc2)/Now, query the Merge2Here table.SQL> SELECT * FROM Merge2HereSQL> /Notice that the first three rows were changed and the last seven rows were added.Then, query the MoreGoodRows table.SQL> SELECT * FROM MoreGoodRowsSQL> /No changes on this table.Drop both the Merge2Here and MoreGoodRows tables.SQL> DROP TABLE Merge2HereSQL> /SQL> DROP TABLE MoreGoodRowsSQL> /SQL> DELETE FROM deptWHERE deptno = 40SQL> /SQL> COMMIT

Page 32: (SQL Tutorial)

SQL> /You have dropped your tables so that you can do this Hands-On exercise over. 

"In theory, there is no difference between theory and practice. But, in practice, there is." - Jan L.A. van de Snepscheut

Questions:Q: When do you use the WITH … AS clause in the SQL statement?Q: How does the WITH … AS clause help your performance?Q: Write a query to list all the department names that their total paid salaries are more than 1/3 of the total salary of the company.Q: What are the multiple columns in the SQL statement? Where or how do you use them?Q: Write a SQL statement to query the name of all employees who earn the maximum salary in their department using the multiple columns syntax.Q: What is the inline view in the Oracle SQL statement?Q: Write a SQL statement to query all of the employee names, jobs, and salaries where their salary is more than 10% of the total company paid salary.Q: What does the MERGE statement in the SQL statement?Q: Can you update, insert, or delete any records while you are using the MERGE statement?

Lesson 10"I find that the harder I work, the more luck I seem to have." - Thomas Jefferson (1743-1826)

Read first then play the video:    SQL013(VIDEO)-Materialized views - the view that stores data 

Materialized Views - The view that stores dataIntroductionYour organization is growing, and their managers from different states are in need of data warehousing. You should pre-compute database information into a summary data aggregated to be easily understood.They are asking you to create a materialized view to pre-compute and store information manually on the number of employees with their total salary paid for each department (to project the employees’ payment budget). They want, when new employees and their salaries are entered into the base tables, to be able to manually update their materialized view with its summary, aggregated data, to reflect these changes from the base tables.They should be able to download a subset of data from the company’s headquarter table to another company associated servers, assuming that their system is not in a distributed environment.In a distributed environment, they could use materialized views to replicate data at distributed sites and synchronize updates between these sites.Now, the company wants the ability to create an aggregated snapshot for the accounting department only. The required data include the total number of employees, and the total paid salaries for the accounting department only. Once the aggregated snapshot was created, it should define, in such a way, that it can update the materialized view once a month without any human intervention. The snapshot must be refreshed, based on the rule that your client asked.

Page 33: (SQL Tutorial)

 Your assignments are:1- To create a materialized view log,2- To create a materialized view,3- To test your materialized view,4- To execute or update you materialized view manually,5- To create materialized view and updated monthly,6- To test it, and7- To check and test your monthly job. Topics:Creating a materialized view logListing the snapshot logs' viewMLOG$_EMPCreating a materialized viewGranting materialized view privilegeListing the user's materialized viewsExecuting the REFRESH procedureUsing DBMS_SNAPSHOT packageExecuting the REMOVE procedureListing the materialized view in the job’s queueDeleting the materialized view’s jobDropping the created Materialized viewRevoking the materialized view privilege Log in to sqlplus as the iself user.SQL> CONNECT iself/schoolingTo do this Hands-On exercise, you must first create a materialized view log.CREATE MATERIALIZED VIEW ...PRIMARY KEY, ROWID, and INCLUDING NEW VALUESA materialized view (MVIEW) is a replica of a target master from a single point in time. The concept was first introduced with Oracle7 termed as SNAPSHOT. You use Materialized Views to create summaries in a data warehouse environment or replicate a data in a distributed environment. In data warehouses, you can use materialized views to pre-compute and store aggregated data such as the sum of sales. In distributed environments, you can use materialized views to replicate data from a master site to other distributed sites.Remember that the following datatypes in the Oracle database are not supported in snapshot replication: - LONG- LONG RAW- BFILE- UROWID (cot supported for updatable snapshots)Materialized View TypesRead-Only Materialized ViewsYou can not perform DML on snapshots in this category. Updatable Materialized ViewsYou can insert, update and delete rows of the updatable materialized view.Example:

Page 34: (SQL Tutorial)

create materialized view MVIEW_testrefresh faststart with sysdatenext sysdate+1FOR UPDATE asselect * from mytable@california; Subquery Materialized ViewsMaterialized views that are created with sub-queries in the WHERE clause of the mview query are referred to as subquery materialized views.Example:CREATE MATERIALIZED VIEW myordersREFRESH FAST ASSELECT * FROM myorder@california oWHERE EXISTS(SELECT * FROM mycustomer@dc cWHERE c.customer_id = o.customer_idAND c.credit_limit > 10000); Rowid vs. Primary Key Materialized ViewsFast refresh requires association between rows at snapshot and master sites. Snapshots that use ROWIDs to refresh are called ROWID snapshots while those that use primary keys are called primary key snapshots.Example:CREATE MATERIALIZED VIEW ordersREFRESH WITH ROWID ASSELECT * FROM orders@califonia;Create a materialized view log with a PRIMARY KEY, the ROWID, and INCLUDING NEW VALUES options.SQL> CREATE MATERIALIZED VIEW LOG ON empWITH PRIMARY KEY,ROWID (deptno)INCLUDING NEW VALUESSQL> /Begin by setting your linesize to 1000.SQL> SET LINESIZE 1000;Query your snapshot logs' view.SQL> SELECT * FROM user_snapshot_logsSQL> /This result shows that your log was created successfully and named MLOG$_EMP.BUILD IMMEDIATE and REFRESH ON DEMANDCreate a materialized view with the BUILD IMMEDIATE and REFRESH ON DEMAND options.

Your materialized view should have the department number, number of employees, and total salaries paid to employees by department.SQL> CREATE MATERIALIZED VIEW mv_salBUILD IMMEDIATEREFRESH ON DEMANDAS SELECT deptno, COUNT(1) AS no_of_emp, SUM(sal) AS salary

Page 35: (SQL Tutorial)

FROM empGROUP BY deptnoSQL> /Notice on the error message INSUFFICIENT PRIVILEGE.

In order to create a materialized view, you must be granted a CREATE MATERIALIZED VIEW privilege.Connect to SQLPLUS as system/manager.SQL> CONNECT system/managerGRANT CREATE MATERIALZED VIEW …Grant the CREATE MATERIALIZED VIEW privilege to the iself user.SQL> GRANT CREATE MATERIALIZED VIEW TO iselfSQL> /Now, log back in as the iself user.SQL> CONNECT iself/schoolingThis time you should be able to create a materialized view without any problems.

Create your materialized view again.SQL> CREATE MATERIALIZED VIEW mv_salBUILD IMMEDIATEREFRESH ON DEMANDAS SELECT deptno, COUNT(1) AS no_of_emp, SUM(sal) AS salaryFROM empGROUP BY deptnoSQL> /Note that this time the materialized view was created successfully.Query the user's materialized views.SQL> SELECT * FROM user_mviewsSQL> /Query the mv_sal materialized view.SQL> SELECT * FROM mv_salSQL> /Note the total salary paid to department 10.Query all the information about empno 7934.SQL> SELECT * FROM emp WHERE empno = 7934SQL> /Make a note about her salary.Change her salary to 5000 and save it into the EMP table.SQL> UPDATE empSET sal = 5000WHERE empno = 7934SQL> /SQL> COMMITSQL> /The salary column was changed.Query the mv_sal materialized view.SQL> SELECT * FROM mv_salSQL> /Notice that there are no changes made on the total salary in department 10.DBMS_SNAPSHOT package and REFRESH option

Page 36: (SQL Tutorial)

Refresh the mv_sal materialized view by executing the REFRESH procedure at the DBMS_SNAPSHOT package and use the letter C for the complete option.SQL> EXECUTE dbms_snapshot.refresh('mv_sal','C')SQL> /Now, query your mv_sal materialized view.SQL> SELECT * FROM mv_salSQL> /Notice that the total salary paid to department 10 was changed. In fact, you have manually updated the materialized view.START WITH SYSDATE NEXT …Now, let's create a materialized view named mv_account that would be updated every month automatically without any human intervention.SQL> CREATE MATERIALIZED VIEW mv_accountBUILD IMMEDIATEREFRESH FORCESTART WITH SYSDATE NEXT (SYSDATE+30)WITH PRIMARY KEYASSELECT * FROM empWHERE deptno = 10SQL> /Notice that the START WITH SYSDATE option will create an immediate data, and the NEXT (SYSDATE+30) option will update the table every 30 days.Check to see how many materialized views you have created.SQL> SELECT * FROM user_mviewsSQL> /you got one more materialized view.Query the mv_account materialized view.SQL> SELECT * FROM mv_accountSQL> /Insert a record to your EMP table.SQL> INSERT INTO emp VALUES(9999,'John','Kazerooni',7782,'04-Apr-02',1400,500,10)SQL> /SQL> COMMITSQL> /A record was added.Since you have 30 days to see your changes, you can update the mv_account materialized view by executing the REFRESH procedure from the DBMS_SNAPSHOT package and use the C option for the complete option.SQL> EXECUTE dbms_snapshot.refresh('mv_account','C')SQL> /Now, query the mv_account table.SQL> SELECT * FROM mv_accountSQL> /Notice that employee number 9999 was added to the materialized view.USER_JOBS tableCheck your jobs' queue.SQL> SELECT * FROM user_jobs

Page 37: (SQL Tutorial)

SQL> /Notice that this job is going to run each month. Make a note of it's job number.DBMS_JOB package and REMOVE procedureExecute the REMOVE procedure from the DBMS_JOB package to delete a job from the job's queue. Use the runtime variable to enter your job number.SQL> EXECUTE dbms_job.remove(&Enter_job_number)SQL> /Delete the added employee number 8888 and 9999 and change the employee's salary back to 1000.SQL> DELETE FROM emp WHERE empno IN (8888,9999);UPDATE empSET sal = 1000WHERE empno = 7934SQL> /SQL> COMMITSQL> /Drop all of the created Materialized views.SQL> DROP MATERIALIZED VIEW LOG ON empSQL> /SQL> DROP MATERIALIZED VIEW mv_salSQL> /SQL> DROP MATERIALIZED VIEW mv_accountSQL> /REVOKE CREATE MATERIALIZED VIEW …Log back in as system/manager and revoke the CREATE MATERIALIZED VIEW privilege from the ISELF user.SQL> CONNECT system/managerSQL> REVOKE CREATE MATERIALIZED VIEW FROM iselfSQL> /you have now cleared your session, so that you can perform this excercise over and over again.

"Each problem that I solved became a rule which served afterwards to solve other problems." - Rene Descartes (1596-1650), "Discours de la Methode"

Questions:Q: What is a Materialized View?Q: What are the Materialized View types?Q: Write the difference between ROWID and PRIMARY KEY in the Materialized View.Q: What is the difference between a Materialized View and View?Q: When or why do you use a Materialized View?Q: What is a materialized view log?Q: What are the PRIMARY KEY and ROWID in the Materialized View Log?Q: What does the USER_SNAPSHOT_LOGS view contain?Q: Create a materialized view that contains the department number, number of employees, and total salaries paid to employees by department.Q: Who can create a materialized view?Q: What does the USER_MVIEWS view contain?Q: How do you refresh a materialized view?

Page 38: (SQL Tutorial)

Q: What parameter should be used to update the materialized view every month automatically without human intervention?Q: What does the USER_JOBS view contain?Q: How do you remove a job from the Oracle Job Queue?Q: How do you drop a materialized view log and a materialized view?

Lesson 11"In the End, we will remember not the words of our enemies, but the silence of our friends." - Martin Luther King Jr. (1929-1968)

Read first then play the video:    SQL014(VIDEO)-The BREAK ON clause

The BREAK ON clauseIntroductionYour organization now wants to get a simple report from the following report layout. Unfortunately, they don’t have the “REPORTS builder” tool and you have to use sql*plus in order to fulfill their user requirements.The client asked you to query all employee names and their departments where their salaries are greater than $3,150.00, sorted by department. The report layout printout:----------------Salary-----------------Department Employee Salary-------------------- -------------------- -----------ACCOUNTING KING $5,250.00******************** -----------sum $5,250.00 SALES ALLEN $3,758.57BLAKE $3,464.20******************** -----------sum $7,222.77 ------------ confidential ------------- Your assignments are:1. To use TTITLE, COLUMN, COMPUTE and BREAK commands,2. To query department name, employee names and their salaries, and3. To have subtotal for each department. Topics:REPHEADERREPFOOTERCOLUMN <col> HEADING <hdr> FORMAT a20BREAK ON <col> SKIP nCOMPUTE SUM OF <col> ON <col>SPOOLHOSTCLEAR BUFFERCLEAR COLUMNS

Page 39: (SQL Tutorial)

CLEAR COMPUTE Connect to SQLPLUS as the iself user.SQL> CONNECT iself/schoolingSet the pagesize to 55 and the linesize to 80.SQL> SET PAGESIZE 55SQL> SET LINESIZE 80REPHEADER and REPFOOTER commandsMake a report header and footer the way it was stated in the case study.SQL> REPHEADER '----------------Salary-----------------'SQL> REPFOOTER '------------ confidential -------------'COLUMN … HEADING … FORMAT …commandMake your column heading and format as stated in the case study.SQL> COLUMN dname HEADING 'Department' FORMAT a20SQL> COLUMN sal HEADING 'Salary' FORMAT $99,999.99SQL> COLUMN ename HEADING 'Employee' FORMAT a20BREAK and COMPUTE commandBuild a break on the department number and compute a sub-total for each department.Skip one line for each control break.SQL> BREAK ON dname SKIP 1SQL> COMPUTE SUM OF sal ON dnameSPOOL commandUse the SPOOL command to populate a text file with any thing that you type in the SQLPLUS prompt or you query. You have to SPOOL off in order to be able to open the spool file. If you don’t spool off, you will see a zero byte written in the file and you will not be able to see any output data.Spool it on a file called salary.out in your c: drive.SQL> SPOOL c:.outQuery your report based on your case study description.SQL> SELECT dname, ename, salFROM emp e, dept dWHERE e.deptno = d.deptno AND sal > 3150ORDER BY dnameSQL> /Spool off, of the output.SQL> SPOOL OFFYou can use the text editor to open your spool file.CLEAR commandNote that all the values in REPHEADER, REPFOOTER, BUFFER, COLUMNS, COMPUTE and etc are going to stay the same during your open session. In order to clean them, you should use the CLEAR command for BUFFER, COLUMNS, and COMPUTE. And input NULL to REPHEADER and REPFOOTER.Clear the buffer, repheader, repfooter, and compute all of the columns from your session.SQL> REPHEADER ''SQL> REPFOOTER ''SQL> CLEAR BUFFERSQL> CLEAR COLUMNSSQL> CLEAR COMPUTE

Page 40: (SQL Tutorial)

"Whether you think that you can, or that you can't, you are usually right." - Henry Ford (1863-1947)

Questions:Q: What does the BREAK ON clause in SQLPLUS?Q: What do the REPHEADER and REPFOOTER commands in SQLPLUS?Q: What does the following commands?COLUMN sal HEADING 'Salary' FORMAT $99,999.99COLUMN ename HEADING 'Employee' FORMAT a20REPHEADER '' BREAK ON dname SKIP 1COMPUTE SUM OF sal ON dnameSPOOL c:.outSPOOL OFFREPFOOTER ''CLEAR BUFFERCLEAR COLUMNSCLEAR COMPUTEQ: What does the CLEAR command in SQLPLUS?

Lesson 12"The only way to get rid of a temptation is to yield to it." - Oscar Wilde (1854-1900)

Read first then play the video:    SQL015(VIDEO)-Troubleshooting - UNION, INTERSET, and MINUS statements

UNION, INTERSET, and MINUS statementsIntroductionYour organization has another table that contains employee data for the accounting department only. You have been assigned to check the contents of the accounting table with the base EMP table. You need to:1- List all of the records from the EMP table in the accounting department that are not in the accounting table.2- List all of the records that are common in both tables.3- Merge the two tables so that you can query all of the records with no duplicated records. Topics:UNIONINTERSECTMINUS Connect to SQLPLUS as the iself user.SQL> CONNECT iself/schoolingSet the linesize to 100 and the pagesize to 55.SQL> SET LINESIZE 100 PAGESIZE 55

Page 41: (SQL Tutorial)

Create a table named accounting and copy all of the accounting employees into it.SQL> CREATE TABLE accountingAS (SELECT * FROM empWHERE deptno = 10)SQL> /Query the accounting table.SQL> SELECT * FROM accountingSQL> /Now, insert a new record into the accounting table.SQL> INSERT INTO accounting VALUES(9000,'Dana','Kazerooni',7782,'04-Apr-02',1500,null,10)SQL> /SQL> COMMIT;Insert a new record into the EMP table.SQL> INSERT INTO EMP VALUES(9999,'Borna','Kazerooni',7782,'04-Apr-02',1500,null,10)SQL> /SQL> COMMIT;Query the accounting table again.SQL> SELECT * FROM accountingSQL> /Note the employee that was added to accounting table.Query the accounting employees from the EMP table.SQL> SELECT * FROM empWHERE deptno = 10SQL> /Note! The employee record was added to the EMP table.MINUS statementIt will query all the records that are not matching against your base table.Find all of the records from the EMP table in the accounting department, that are not in the accounting table.SQL> SELECT * FROM empWHERE deptno = 10MINUS SELECT * FROM accountingSQL> /Notice that this is the record that you added into the EMP table.INTERSECT statementIt will query all the records that match with the base table. It is the same as joining two tables.Search and list for all of the records that are common in both tables.SQL> SELECT * FROM empWHERE deptno = 10INTERSECT SELECT * FROM accountingSQL> /Notice the common records.UNION statementIt will query all the records that match or not match with the base table.Merge the two tables so that you can query all of the records with no duplicated records.SQL> SELECT * FROM accountingUNION ALL SELECT * FROM emp

Page 42: (SQL Tutorial)

WHERE deptno = 10AND empno NOT IN (SELECT empno FROM accounting)SQL> /Now, drop the accounting table.SQL> DROP TABLE accountingSQL> /Delete the record which was added to the EMP table.SQL> DELETE FROM empWHERE empno = 9999SQL> /SQL> COMMIT;

"Don't stay in bed, unless you can make money in bed." - George Burns (1896-1996)

Questions:Q: What does the UNION statement in the SQL statement?Q: What does the INTERSET statement in the SQL statement?Q: What does the MINUS statement in the SQL statement?

Lesson 13"I don't know why we are here, but I'm pretty sure that it is not in order to enjoy ourselves." - Ludwig Wittgenstein (1889-1951)

Read first then play the video:    SQL016(VIDEO)-Troubleshooting Deleting duplicated records 

Troubleshooting Deleting duplicated recordsIntroductionYour organization has a lot of duplicated records in their Account Employee table. This is a daily problem in any organization and you should be prepared to fix the problem. You have been assigned to clean all of the duplicated records. Begin by logging in as the iself user.SQL> CONNECT iself/schoolingSet the linesize to 100 and the pagesize to 55.SQL> SET LINESIZE 100 PAGESIZE 55CREATE TABLE AS …First, let's create a table with lots of duplicated records. Create a table named dup_emp and copy all of the EMP's records into it.SQL> CREATE TABLE dup_empAS (SELECT * FROM emp)SQL> /Query the dup_emp table.SQL> SELECT * FROM dup_empSQL> /INSERT INTO … SELECT commandInsert all the accounting department rows into the dup_emp table.SQL> INSERT INTO dup_emp

Page 43: (SQL Tutorial)

SELECT * FROM emp WHERE deptno = 10SQL> /SQL> commit;Query all the duplicated records from the dup_emp table order by the employee name.SQL> SELECT * FROM dup_empWHERE deptno = 10ORDER BY enameSQL> /Notice that all of the employees of department 10 have been duplicated. Don’t try to understand the following PL/SQL statements. You will learn how to write a PL/SQL statement at the PL/SQL book.Using PL/SQL to delete duplicated recordsWrite a procedure to delete all of the duplicated records.SQL> DECLARESQL> -- Get the unique empno.SQL> CURSOR c_empno ISSQL> SELECT DISTINCT empno AS empno FROM dup_emp;SQL> -- Get all duplicated records for an employee.SQL> CURSOR c_duprec (p_empno NUMBER) ISSQL> SELECT rowid FROM dup_emp WHERE empno = p_empno;SQL> first_one BOOLEAN;SQL> BEGINSQL> FOR v_empno IN c_empno LOOPSQL> first_one := TRUE;SQL> FOR v_duprec IN c_duprec (v_empno.empno) LOOPSQL> IF NOT first_one THENSQL> DELETE FROM dup_empSQL> WHERE rowid = v_duprec.rowid;SQL> COMMIT;SQL> END IF;SQL> first_one := FALSE;SQL> END LOOP;SQL> END LOOP;SQL> END;SQL> /Query again the dup_emp table order by the department and employee number.

Then check for duplication.SQL> SELECT * FROM dup_empWHERE deptno = 10ORDER BY enameSQL> /Notice that there are no duplicated records.Using SQL to delete duplicated recordsYou could write a delete statement to remove all duplicated records. The following statement will delete all records that have the same employee number except the first one.

In this time, you did not have any duplicated record to be deleted.SQL> DELETE FROM dup_empWHERE ROWID IN (SELECT MAX(ROWID)

Page 44: (SQL Tutorial)

FROM dup_empGROUP BY empnoHAVING COUNT (empno) > 1)SQL> /Drop the dup_emp table.SQL> DROP TABLE dup_empSQL> /

"Good people do not need laws to tell them to act responsibly, while bad people will find a way around the laws." - Plato (427-347 B.C.)

Questions:Q: Why it is important to eliminate duplicate records?Q: What does the following SQL statement?SQL> DELETE FROM dup_empWHERE ROWID IN (SELECT MAX(ROWID)FROM dup_empGROUP BY empnoHAVING COUNT (empno) > 1)SQL> /

Lesson 14"Talent does what it can; genius does what it must." - Edward George Bulwer-Lytton (1803-1873)

Read first then play the video:    SQL017(VIDEO)-Data Partitioning 

Data PartitioningIntroductionYour organization’s database is growing very fast. They want to have a database that contains each department in a separate tablespace. They projected that their employee’s table is growing to more than 100 million rows in each department. Also, upon their requirements, they want to have each department’s employees in a separate hard disk, and to be independent of other department employee’s data. Also, they want to be sure all the employees are in the same table. They want it to be partitioned in such away, that when they run a query against an employee’s information, they would scan at most on the department’s hard disk that he/she works, rather than the other department’s hard disks on non-partitioned table.You will need to choose a partition key. You have been told that the department’s employees are distributed equally among the partition table. There are two types of partitioning approaches that you, as a database designer, must choose (they are Local and Global). A Local index is one that is partitioned exactly like the table to which it belongs. A Global index, unlike local indexes, you should explicitly partition range boundaries using the “VALUE LESS THAN” methods. They want you to create a “Local Index” for the partition table. Your assignments are:1- To create folder for each department,

Page 45: (SQL Tutorial)

2- To create tablespace with following specification for each department:a. Automatic Allocation for an unlimited size,b. Generates redo logs and recoverable, andc. Type must be permanent.3- To create the partition table,4- To copy the EMP table into the partition table,5- To check the table statistics,6- To create a local partition indexes, and7- To check the index table statistics. Connect to SQLPLUS as the iself user.SQL> CONNECT iself/schoolingSet the linesize to 100 and the pagesize to 55.SQL> SET LINESIZE 100 PAGESIZE 55Creating OS directory from DOSHOST commandCreate folders for the accounting department, Reseach department, Sales department, and other departments. Make sure that you have at least 50 Megabytes of hard drive space available on your hard disk. The HOST command tells the SQLPLUS tool that the command is an operating system command. It will execute it at OS level.

SQL> HOST mkdir c:dept10SQL> HOST mkdir c:dept20SQL> HOST mkdir c:dept30SQL> HOST mkdir c:deptxxYour folders were created.CREATE TABLESPACETablespace is a logical place that you will store your object in it. An Oracle user can store all their tables in their default tablespace. Notice that all procedures, functions and packages will be stored in the SYSTEM tablespace and you have no control to enforce that to any other tablespace.Create a tablespace for the accounting department with the following options:1- Automatic Allocation,2- Generates the redo logs,3- Recoverable, and4- Tablespace type must be permanent.SQL> CREATE TABLESPACE dept10tsLOGGINGDATAFILE 'c:dept10ts_01.dbf' SIZE 10MAUTOEXTEND ONNEXT 5KMAXSIZE UNLIMITEDSQL> /Notice that you don't have the sufficient privilege to create a tablespace.Now, connect to SQLPLUS as the system/manager userSQL> CONNECT system/managerGRANT CREATE TABLESPACE and DROP TABLESPACE …Grant the CREATE TABLESPACE and DROP TABLESPACE privilege to the iself user.SQL> GRANT CREATE TABLESPACE TO iselfSQL> /

Page 46: (SQL Tutorial)

SQL> GRANT DROP TABLESPACE TO iselfSQL> /The CREATE TABLESPACE privilege and DROP TABLESPACE privilege was granted to the ISELF user.Now, go back and connect to SQLPLUS as the iself user.SQL> CONNECT iself/schoolingCreate tablespaces for the accounting department.SQL> CREATE TABLESPACE dept10tsLOGGINGDATAFILE 'c:dept10ts_01.dbf' SIZE 10mAUTOEXTEND ONNEXT 5kMAXSIZE UNLIMITEDSQL> /The accounting department tablespace was created.Create tablespaces for the research department.SQL> CREATE TABLESPACE dept20tsLOGGINGDATAFILE 'c:dept20ts_01.dbf' SIZE 10MAUTOEXTEND ONNEXT 5KMAXSIZE UNLIMITEDSQL> /Here, the research department tablespace was created.Create tablespaces for the sales department.SQL> CREATE TABLESPACE dept30tsLOGGINGDATAFILE 'c:dept30ts_01.dbf' SIZE 10MAUTOEXTEND ONNEXT 5KMAXSIZE UNLIMITEDSQL> /And here, the sales department tablespace was created.

Create tablespaces for the other departments.SQL> CREATE TABLESPACE deptxxtsLOGGINGDATAFILE 'c:deptxx_01.dbf' SIZE 10MAUTOEXTEND ONNEXT 5KMAXSIZE UNLIMITEDSQL> /And now, the other departments tablespace was created.CREATE partition tablePARTITION and MAXVALUE optionsNow, create a range-based partitioning table named p_emp. Make sure that the data entry of the accounting department goes to the dept10ts tablespace, the data entry of the research department goes to the dept20ts tablespace, etc.SQL> CREATE TABLE p_emp (empno NUMBER(4) PRIMARY KEY,

Page 47: (SQL Tutorial)

ename VARCHAR2(10),job VARCHAR2(9),mgr NUMBER(4),hiredate DATE,sale NUMBER(7,2),comm NUMBER(7,2),deptno NUMBER(2))STORAGE (INITIAL 5KNEXT 5KPCTINCREASE 0)PARTITION BY RANGE (deptno)(PARTITION dept10VALUES LESS THAN (20)TABLESPACE dept10ts,PARTITION dept20VALUES LESS THAN (30)TABLESPACE dept20ts,PARTITION dept30VALUES LESS THAN (40)TABLESPACE dept30ts,PARTITION deptxxVALUES LESS THAN (MAXVALUE)TABLESPACE deptxxts)SQL> /Your partition table should be created. Notice that the VALUES LESS THAN clause indicates the partition key value must be less then its assigned value in order to be illegible for any DML transaction on its assigned tablespace.Insert records into your partition table (p_emp).SQL> INSERT INTO p_emp SELECT * FROM empSQL> /SQL> COMMITSQL> /ANALZE TABLE COMPUTE STATISTICSAnalyze your partition table.SQL> ANALYZE TABLE p_emp COMPUTE STATISTICSSQL> /USER_TAB_PARTITIONSPartition_name, tablespace_name and num_rows columnsQuery the PARTITION_NAME, TABLESPACE_NAME, and NUM_ROWS columns from the dictionary view.SQL> SELECT partition_name, tablespace_name, num_rowsFROM user_tab_partitionsWHERE table_name = 'P_EMP'SQL> /Notice that in the accounting tablespace you have three records and research tablespace you have 5 records, etc.Compare these two tables, EMP and P_EMP.First, query the EMP table.SQL> SELECT * FROM empSQL> /

Page 48: (SQL Tutorial)

Now, query the p_emp table.SQL> SELECT * FROM p_empSQL> /Can you see the difference? Notice that the query scanned the partition table by the sequence of the tablespaces. That is why the list is sorted by department number.SELECT … PARTITION ()Query the accounting employees from the partition table. Use the partition option.SQL> SELECT * FROM p_emp PARTITION (dept10)SQL> /Notice that your query is only against the accounting department partition and you don't have to have a WHERE clause.Query employee number 7900 from the sales department.SQL> SELECT * FROM p_emp PARTITION (dept30)WHERE empno = 7900SQL> /CREATE INDEX … LOCALCreate a local partition index.SQL> CREATE INDEX p_emp_ind ON p_emp (deptno) LOCALSQL> /Analyze the partition table index.SQL> ANALYZE INDEX p_emp_ind COMPUTE STATISTICSSQL> /Query the statistics on the number of records in each partition.SQL> SELECT index_name, partition_name, num_rowsFROM user_ind_partitionsSQL> /DROP TABLE … CASCADE CONSTRAINTSDrop the table and all of the tablespaces.SQL> DROP TABLE p_emp CASCADE CONSTRAINTSSQL> /DROP TABLESPACE … INCLUDING CONTENTSSQL> DROP TABLESPACE dept10ts INCLUDING CONTENTSSQL> /SQL> DROP TABLESPACE dept20ts INCLUDING CONTENTSSQL> /SQL> DROP TABLESPACE dept30ts INCLUDING CONTENTSSQL> /SQL> DROP TABLESPACE deptxxts INCLUDING CONTENTSSQL> /Now, connect to SQLPLUS as the system/manager userSQL> CONNECT system/manager

REVOKE CREATE TABLESPACE privilegesRevoke the CREATE TABLESPACE and DROP TABLESPACE privileges from the ISELF user.SQL> REVOKE CREATE TABLESPACE FROM iselfSQL> /REVOKE DROP TABLESPACE privilegesSQL> REVOKE DROP TABLESPACE FROM iselfSQL> /

Page 49: (SQL Tutorial)

RMDIR using /S /Q optionsRemove all of the created folders. Use the /S option if folder is not empty. And use the /Q option for the QUIET MODE option.SQL> HOST rmdir c:dept10 /S /QSQL> HOST rmdir c:dept20 /S /QSQL> HOST rmdir c:dept30 /S /QSQL> HOST rmdir c:deptxx /S /Q  

"I'm all in favor of keeping dangerous weapons out of the hands of fools. Let's start with typewriters." - Frank Lloyd Wright (1868-1959)

Questions:Q: What is a data partitioning in the Oracle database?Q: When should you use data partitioning?Q: What is the advantage of using a data partitioning?Q: What is a partition key?Q: What is a local index in the data partitioning?Q: What is a global index in the data partitioning?Q: What are the differences between local and global indexes?Q: How does the ‘VALUE LESS THAN’ method work in the data partitioning?Q: Why do you need multiple tablespaces?Q: Create a range-based partitioning table named p_emp. Be sure that the data entry of the each department goes to its own provided tablespaces such as the accounting department goes to the dept10ts tablespace, the data entry of the research department goes to the dept20ts tablespace, etc.Q: What does the MAXVALUE parameter mean in the data partitioning?Q: How do you analyze a partition table?Q: What does the USER_TAB_PARTITIONS view contain?Q: Write a query to list the accounting employees from the partition table. Use the partition option.Q: Write a query to list employee number 7900 from the sales department?Q: How do you create a local partition index?Q: How do you analyze a partition table index?Q: What does the USER_IND_PARTITIONS view contain?

Lesson 15"Some cause happiness wherever they go; others, whenever they go." - Oscar Wilde (1854-1900)

Read first then play the video:    SQL018(VIDEO)-Data Warehousing and use of ROLLUP and CUBE functions

The ROLLUP and CUBE functionHands-OnData warehousing is a focus in your organization. Management needs more reports in order to truly understand their data. You have been assigned to write simple SQL statement using the “ROLLUP” operator to create salary subtotals for each type of job per year. Also, you should use the CUBE operator to enable a simple statement to calculate all possible combinations of the types of jobs and year for the research department only.

Page 50: (SQL Tutorial)

Notice: A select statement using the ROLLUP operator returns both ‘regular rows’ and ‘super-aggregate rows.’ Super-aggregate rows are rows that contain a sub-total value.A select statement using the CUBE operator returns cross-tabulation values, thus produces totals in all possible dimensions, and is used for warehousing aggregated data reports. The report layout printout: The ROLLUP layout output:Year JOB SUM(SAL) COUNT(*)---- --------- ---------- ----------80 CLERK 1050 180 1050 181 ANALYST 3150 181 CLERK 997.5 181 MANAGER 9160.45 381 PRESIDENT 5250 181 SALESMAN 11609.82 481 30167.77 1082 CLERK 1365 182 1365 187 ANALYST 2000 187 CLERK 1337.06 187 3337.06 235919.83 14 The CUBE layout output:Year JOB SUM(SAL) COUNT(*)---- --------- ---------- ----------80 CLERK 1050 180 1050 181 ANALYST 3150 181 MANAGER 3123.75 181 6273.75 287 ANALYST 2000 187 CLERK 1337.06 187 3337.06 2ANALYST 5150 2CLERK 2387.06 2MANAGER 3123.75 110660.81 5 IntroductionOracle added the ROLLUP and CUBE functions in Oracle9i to the GROUP BY clause of the SELECT statement. The ROLLUP function creates subtotals at any level of aggregation from the most detailed up to a grand total. The CUBE function is similar to the ROLLUP function, but it calculates all possible combinations of subtotals. Look at the following example to have a better understanding of these two powerful functions. We use these two functions a lot when we have a warehousing application or needs.Connect to SQL*PLUS as the iself user.SQL> CONNECT iself/schooling

Page 51: (SQL Tutorial)

Set the pagesize to 55 and the linesize to 100.SQL> SET PAGESIZE 55SQL> SET LINESIZE 100Alter the EMP table, and add a column to store the year that employees were hired.SQL> ALTER TABLE emp ADD (year VARCHAR2(2))SQL> /Set the column year heading.SQL> COLUMN year FORMAT a4 HEADING "Year"Update the EMP table to set the year each employee was hired, into the newly created YEAR column.SQL> UPDATE empSET year = TO_CHAR(hiredate,'YY')SQL> /SQL> commit;ROLLUP grouping optionQuery an aggregation sum report for each job, in each year, using the ROLLUP grouping option.SQL> SELECT year, job, SUM(sal), COUNT(*)FROM empGROUP BY ROLLUP (year, job)SQL> /This is an example of a GROUP BY ROLLUP option.CUBE grouping optionQuery an aggregation sum report for each job, in each year using the CUBE option group for the research department only.SQL> SELECT year, job, SUM(sal), COUNT(*)FROM empWHERE deptno = 20GROUP BY CUBE (year, job)SQL> /This is an example of a GROUP BY CUBE option.DROP TABLE … DROP columnDrop the year columnSQL> ALTER TABLE emp DROP (year)SQL> /You have dropped the year column so that you can perform this exercise over and over again.

"I am ready to meet my Maker. Whether my Maker is prepared for the great ordeal of meeting me is another matter." - Sir Winston Churchill (1874-1965)

Questions:Q: What does the ROLLUP operator?Q: What does the CUBE operator?Q: What are the differences between the CUBE and ROLLUP functions?Q: What environments may use the CUBE and ROLLUP functions most?Q: Write a query to list an aggregation sum report for each job, in each year, using the ROLLUP grouping option.Q: Write a query to list an aggregation sum report for each job, in each year, using the CUBE grouping option.

Page 52: (SQL Tutorial)

Lesson 16"I shall not waste my days in trying to prolong them." - Ian L. Fleming (1908-1964)

Read first then play the video:    SQL021(VIDEO)-Defining Objects and Collection Types 

Defining Objects and Collection TypesHands-On introductionYour organization is going to gather information about all the employees’ families in order to keep track of the number of the employee kids, kids’ names and their date of birth. You have been assigned to use the nested object tables for the employees’ family. You should use the “CONSTRUCTOR” operator to refer to the nested table with the “THE” syntax. Your client should be able to insert a record into the nested table directly or update the nested table, and be able to get individual elements from a nested object table using the object columns. Your assignments are:1- To use nested object tables,2- To create a record object type,3- To create a table objects type,4- To create a table for employee’s table (EMP_FAMILY),5- To insert record into table,6- To query information from table,7- To update information from table, and8- To delete information from table. 

Connect to SQLPLUS as the iself user.SQL> CONNECT iself/schoolingStart your session by setting the pagesize to 55 and the linesize to 100. Also, change the object_name column format to only 20 characters long.SQL> SET PAGESIZE 55 LINESIZE 100SQL> COLUMN object_name FORMAT a20This section contains examples of creating and using user-defined object types and collection types in the Oracle database.CREATE TYPE … AS OBJECT …Create an object type with two columns to hold the employee's child name and date of birth and name it employee_kids.SQL> CREATE TYPE employee_kids AS OBJECT (NAME VARCHAR2(30),dob DATE)SQL> /CREATE TYPE … IS TABLE OF …Create a table type using employee_kids and name it employee_kids_table.SQL> CREATE TYPE employee_kids_table IS TABLE OF employee_kidsSQL> /Query all of the object types that you created.SQL> SELECT object_name FROM user_objects

Page 53: (SQL Tutorial)

WHERE object_type = 'TYPE'SQL> /CREATE TABLE … NESTED TABLE …Create the emp_family table containing the kids column with a type of employee_kids_table.SQL> CREATE TABLE emp_family(empno NUMBER,kids employee_kids_table)NESTED TABLE kids STORE AS nested_employee_kids_tableSQL> /This is an example of a nested table column. In this column, you will store the name and birth of an employees' child.INSET INTO … VALUES (object_type(), …)Insert two rows into the emp_family table.SQL> INSERT INTO emp_family VALUES (7900, employee_kids_table())SQL> /SQL> INSERT INTO emp_family VALUES (7788, employee_kids_table())SQL> /SQL> COMMIT;Note that the constructor creates an empty nested table as opposed to leaving it null. Notice that without using the constructor, it is not possible to refer to the nested table with the "THE" clause.Insert another row into the emp_family table, while specifying three employee kids for the nested table at the same time.SQL> INSERT INTO emp_family VALUES(7902,employee_kids_table( employee_kids('David','08-AUG-01'),employee_kids('Peter','10-JUN-88'),employee_kids('Mark','30-OCT-92')))SQL> /Now, query the emp_family table.SQL> SELECT * FROM emp_familySQL> /Notice that the names David, Peter, and Mark were added.Describe the emp_family tableSQL> desc emp_familyINSERT using “THE” sub-queryNow insert directly into the nested table. The "THE" sub-query is used to identify the nested table to INSERT INTO.SQL> INSERT INTO THE(SELECT kids FROM emp_familyWHERE empno = 7900)VALUES ('Fred','10-SEP-89')SQL> /SQL> INSERT INTO THE(SELECT kids FROM emp_familyWHERE empno = 7900)VALUES ('Sue','10-DEC-99')SQL> /SQL> commit

Page 54: (SQL Tutorial)

SQL> /Note that when using this method only one row may be inserted into the nested table at a time - as would also be the case if you were inserting rows into any table.

Set off the record separator and then query the emp_family table.SQL> SET RECSEP OFFSQL> COLUMN KIDS FORMAT A55 WORDSQL> SELECT * FROM emp_familySQL> /Notice that the names FRED and SUE were added to the KIDS nested table.Now query directly from the nested table. The "THE" sub-query is used to identify the nested table to query. Query the children names of employee number 7788.SQL> SELECT nameFROM THE(SELECT kids FROM emp_family WHERE empno = 7788)SQL> /Notice that this employee does not have any kids.UPDATE … SET … = object_type()Use an UPDATE statement, to change the whole nested table for a given row, in the "emp_family" table.SQL> UPDATE emp_familySET kids = employee_kids_table(employee_kids('Sara','08-OCT-88'))WHERE empno = 7788SQL> /SQL> COMMITSQL> /Now, query the emp_family table.SQL> SELECT * FROM emp_familySQL> /Notice that the KIDS nested table was replaced and Sara was inserted into the kids table.UPDATE THE (SELECT …)Now, let's update a single element of the nested table. Update the David name to Dana where the employee number is 7902.SQL> UPDATE THE(SELECT kids FROM emp_family WHERE empno=7902)SET name = 'Dana'WHERE name = 'David'SQL> /SQL> COMMIT;The "THE" sub-query is used to identify the KIDS nested table.Query the emp_family table to see the changes.SQL> SELECT * FROM emp_familySQL> /David was changed to Dana.CREATE UNIQUE INDEX …Add a unique index to the nested table. Note that we must include the nested_table_id column in this case.SQL> CREATE UNIQUE INDEX i_nested_employee_kids_tableON nested_employee_kids_table(nested_table_id,name)SQL> /

Page 55: (SQL Tutorial)

Insert the duplicated record into the nested table.SQL> INSERT INTO THE(SELECT kids FROM emp_familyWHERE empno = 7900)VALUES ('Sue','10-DEC-99')SQL> /

UNIQUE CONSTRAINT VIOLATIONAs you can see, you get a UNIQUE CONSTRAINT VIOLATION message.DROP TYPE statementDrop the emp_family, employee_kids_table, and employee_kids tables.SQL> DROP TABLE emp_familySQL> /SQL> DROP TYPE employee_kids_tableSQL> /SQL> DROP TYPE employee_kidsSQL> /You have dropped the objects so that you can practice this Hands-On over.   

“Always bear in mind that your own resolution to succeed is more important than any one thing.” Abraham Lincoln (1809 - 1865)

Questions:Q: What is an object type?Q: What is a collection object?Q: Create an object type with two columns to hold the employee's child name and date of birth and name it employee_kids .Q: Create a table type using employee_kids and name it employee_kids_table.Q: Create the emp_family table containing the kid’s column with a type of employee_kids_table.Q: How do you insert a record in the object type?Q: What is the constructor?Q: What is the ‘THE’ sub-query?Q: How do you query a record using the ‘THE’ sub-query?Q: What is a nested table?Q: How do you insert a record to a nested table?Q: How do you update a record to nested table?Q: How do you add a unique index to a nested table?

Lesson 17Try not to become a man of success but rather to become a man of value. Albert Einstein (1879 - 1955)

Replicating data with a NESTED TABLE collection typeHands-On IntroductionToday, a lot of company wants to replicate their data for a reason of backup and recovery, accessibility, performance, etc.

Page 56: (SQL Tutorial)

 This hand-on is intended to introduce the enhancement in Oracle9i to teach how to replicate an object from location “A” to “B” based on a table with a NESTED TABLE collection type. We will learn how to create a materialized view based on a table with a NESTED TABLE collection type. We assume that you have two sites (Master Site with a service name of SITEA and Materialized View Site with a service name of SITEB). Also we assume that we have user schema called REPLICATOR in both sites. CONNECT …/…@...STEPS to implement replication:Step 1: Connect to “SITEA” (Master Site) as the REPLICATOR user.SQL> CONNECT replicator/…@SITEACREATE TYPE … AS OBJECT …Step 2: Create the “address_book_type_object” object. Then create a nested table type from created object.SQL> CREATE OR REPLACE TYPE address_book_type_objectAS OBJECT (id_address NUMBER(1),address VARCHAR2(20)); CREATE TYPE … AS TABLE OF …SQL> CREATE TYPE address_book_nested_typeAS TABLE OF address_book_type_object; CREATE TABLE … NESTED TABLE …Step 3: Create the “ADDRESS_BOOK” table with created “ADDRESS_BOOK_NESTED_TYPE” type.SQL> CREATE TABLE address_book( id NUMBER(10) CONSTRAINT address_book_pk PRIMARY KEY,first_name VARCHAR2(15),last_name VARCHAR2(15),address_obj address_book_nested_type)NESTED TABLE address_obj STORE AS address_nested((PRIMARY KEY (NESTED_TABLE_ID, id_address))); CREATE MATERIALIZED VIEW LOG …Step 4: Now, create a Materialized View Log.SQL> CREATE MATERIALIZED VIEW LOG ON address_book;ALTER MATERIALIZED VIEW LOG ON address_book ADD(address_obj);SQL> CREATE MATERIALIZED VIEW LOG ON address_nestedWITH PRIMARY KEY; INSERT INTO … VALUES (object_type(),…)Step 5: Insert some records into your address book table and then commit the transaction.SQL> INSERT INTO address_bookVALUES ('100','Borna','Kaz',address_book_nested_type(

Page 57: (SQL Tutorial)

address_book_type_object (1,‘Company Name’),address_book_type_object (2,'1576 Dunterry place')address_book_type_object (3, 'Orlando','FL, 22101')));SQL> INSERT INTO address_bookVALUES ('200','Dana','Kaz’,address_book_nested_type (address_book_type_object (1,‘Company Name2’')));SQL> COMMIT; Query the address book table.SQL> SELECT *FROM address_book; Step 6: Connect to SITEA again with a DBA privilege.SQL> CONNECT system/…@SITEA Obtaining an Object ID (OID)Step 7: Obtain Object ID of created “ADDRESS_BOOK_TYPE” object.SQL> SELECT OWNER, TYPE_OID FROM DBA_TYPESWHERE TYPE_NAME LIKE 'ADDRESS%'; Step 8: Connect to SITEB (Materialized View Site) as the REPLICATOR user.SQL> CONNECT replicator/...@SITEB Step 9: Assuming that your object IDs are‘XXXXXXXXXXXXXXXXXXXXX’ and ‘YYYYYYYYYYYYYYYYYYYYY.SQL> CREATE OR REPLACE TYPE address_book_type_objectOID ‘XXXXXXXXXXXXXXXXXXXXX’AS OBJECT (id_address NUMBER(1),address VARCHAR2(20));Creating type using OIDSQL> CREATE TYPE address_book_nested_typeOID ‘YYYYYYYYYYYYYYYYYYYYY’AS TABLE OF address_book_type_object; CREATE MATERIALIZED VIEW …FROM [email protected] 10: Now, create a Materialized View that it will be updated as soon as there is any changes on the Master table (ADDRESS_BOOK) by executing refresh procedure.SQL> CREATE MATERIALIZED VIEW address_book_mvNESTED TABLE address_obj STORE AS address_nested_mvREFRESH FAST ASSELECT *FROM replicator.address_book@SITEA; DBMS_MVIEW.REFRESH procedureStep 11: From now on, any changes in the ADDRESS_BOOK table in the Master Site (SITEA) will be replicated to the SITEB (Materialized View Site) by executing DBMS_MVIEW.REFRESH procedure on the SITEB.SQL> EXECUTE dbms_mview.refresh(‘address_book_mv’,’F’);

Page 58: (SQL Tutorial)

 

A great secret of success is to go through life as a man who never gets used up. Albert Schweitzer (1875 - 1965)

Questions:Q: What is a data replica?Q: What is the difference between a materialized view and a materialized view log?Q: What is an object ID?Q: How do you retrieve an object ID?Q: How do you use an object ID to create an object type?

Lesson 18“If your success is not on your own terms, if it looks good to the world but does not feel good in your heart, it is not success at all.” Anna Quindlen

IMPORTANT-READ CAREFULLYThe following are important definitions to remember: "DML" stands for Data Manipulation Language. SELECT, UPDATE, INSERT, and DELETE are the "DML" statements. A "SELECT" statement must consist of a "SELECT" and a "FROM" clause. A Mathematical Operation can be performed on the "SELECT" statement. The "DUAL" table would be used when a user does not want to pull data from a table but rather wants simply to use an arithmetic operation. It contains only one row and one column. The "NULL" value will be used when you don't know the value of the column. Remember that the Null value means "I don't know;" and any mathematical operation on the null value will return a null result. The null value function (NVL) can convert a null value an assigned value. A "column heading" can be used in place of the actual column name. If your column heading is case sensitive, a reserved word, or contains white space, it must be enclosed within double quotes. A "table alias" can be used in place of the actual table name to make a column a unique identifier. Two or more columns or strings can be concatenated using a double-pipe. The "ORDER BY" clause in a select statement will sort the order of a listed table. The "WHERE" clause can contain comparison operations linked together. The "LIKE" clause can be used for pattern matching.

Page 59: (SQL Tutorial)

 The "BETWEEN" clause would be used for a range operation. The "DECODE" function will match the column values with appropriate return values. It continues matching until it has identified all cases. The last variable is used for the default return value. A "JOIN" table is: when a query obtains data from more than one table and merges the data together. You may join tables together using "inner join" or "equijoin", "outer join", and "self join". "inner join" also known as equijoin is an equality operation linking the data in the common columns. "outer join" returns data in one table even when there is no match in the other table. A "self join" is based on an equality operation linking the data to itself. A "Cartesian" product" is caused by joining "N" number of tables while you have less than "N-1" join conditions in the query. An "Anonymous Column" is caused by joining two tables when they have a common column name in them. You can use table aliases or table names next to a column name to avoid causing the "anonymous column." The "GROUP BY" clause will assist you in grouping data together. The "EXISTS" operation produces a "TRUE" or "FALSE" value based on the related sub-query data output. You may use the global column name in your sub-query. The "IN" operation produces a "TRUE" or "FALSE" value based on the related sub-query data output or list of values. "MIN," "MAX," and "SUM" are grouping functions that allow you to perform operations on data in a column. You can assign a variable in a "SELECT" statement at run time with use of a runtime variable. A Table is a collection of records. Use the "VARCHAR2" datatype when your input data string varies and does not exceed more than 2000 characters. Use the "CHAR" datatype when your input data string is fixed and does not exceed more than 2000 characters. If your input data is number, use the "NUMBER" datatype. 

Page 60: (SQL Tutorial)

The "DATE" datatype should be used when your input data is "date", "time", or "date and time". The "RAW" datatype should be used when your input data contains binary data and does not exceed more than 2000 bytes. If your input data contains text data and does not exceed more than 2 gig, use the "LONG" datatype. The "LONG RAW" datatype is used if your input data is binary and does not exceed more than 2 Gig. Use the "ROWID" datatype when your application references to the "rowid" of a table. The "BLOB" (Binary Large Object) datatype would be used for binary long objects and can store up to 4 gig. Use the "CLOB" (Character Large Object) datatype if you have to store a book in a column. Its size should not exceed more than 4 gig. Try to use "CLOB" instead of the "LONG" datatype. It is searchable; also more than one column can be defined as Large Object in a table. The "BFILE" datatype would be used for the large external files. The content of this column points to system files. The DATA DICTIONARY is a repository of all the database objects that were created by different schemas. All the information about the database objects is stored in the data dictionary. You will retrieve the data dictionary information using the data dictionary views. DDL" stands for Data Definition Language. CREATE TABLE, CREATE USER, DROP TABLE, ALTER TABLE are examples of the DDL statements. The "ALTER" command changes an object. The "DROP" command removes an object. The "TRUNCATE" or "DELETE" command removes records from an object. When you use the truncate statement, the "high watermark" will change to the beginning of the table. The truncate statement is a "DDL" statement; and on all DDL statements, the commit is implicit. That is the reason that you can not rollback on the truncate statement. Also, when a table is removed all its indexes, constraints, and references will be removed as well. The Oracle9i ANSI standard JOIN syntax You can use Oracle9i ANSI standard JOIN syntax to join the contents of two or more tables together in a single result according to the following syntax.Syntax:SELECT col1, col2

Page 61: (SQL Tutorial)

FROM table1 JOIN table2ON condition; The ANSI standard NATURAL JOIN syntaxA natural join is a join between two or more tables where Oracle joins the tables according to the column(s) in the two or more tables sharing the same name with the following syntax.Syntax:SELECT col1, col2FROM table1 NATURAL JOIN table2; The USING clauseYou can use Oracle9i ANSI standard JOIN syntax to join the contents of two or more tables together in a single result according to the columns in the two tables sharing the same name and be used in the USING clause with the following syntax.Syntax:SELECT col1, col2FROM table1 JOIN table2USING (col); The ANSI standard CROSS JOIN syntaxA cross-join is produced when you use the CROSS keyword in your ANSI/ISO -compliant join query. You use it when you want to retrieve a Cartesian product.Syntax:SELECT col1, col2FROM table1 CROSS JOIN table2; The OUTER JOIN clauseA OUTER JOIN is a join between two tables where you want to see information from tables even when no corresponding records exist in the common column. You can have RIGHT OUTER JOIN, LEFT OUTER JOIN, and FULL OUTER JOIN.Syntax:SELECT col1, col2FROM table1 RIGHT/LEFT/FULL OUTER JOIN table2; RIGHT OUTER JOINA RIGHT OUTER JOIN is a join between two tables where you want to see information from table on the right side even when no corresponding records exist in the common column.Syntax:SELECT col1, col2FROM table1 RIGHT OUTER JOIN table2; LEFT OUTER JOINA LEFT OUTER JOIN is a join between two tables where you want to see information from table on the left side even when no corresponding records exist in the common column.Syntax:SELECT col1, col2FROM table1 LEFT OUTER JOIN table2; FULL OUTER JOIN

Page 62: (SQL Tutorial)

A FULL OUTER JOIN is a join between two tables where you want to see information from both tables on the left and right sides even when no corresponding records exist in the common column.Syntax:SELECT col1, col2FROM table1 FULL OUTER JOIN table2; The (WITH name AS) statementOracle9i provides you with the WITH clause that lets you factor out the sub-query, give it a name, then reference that name multiple times within the original complex query. The (inline view)A sub-query that appears in the FROM clause is called an inline view. You must enclose the query text for the inline view in parentheses and also give a label for the inline view so that columns in it can be referenced later. The MERGE statementOracle9i provides you with the MERGE statement so that you can identify a table into which you would like to update data in an existing row or add new data if the row does not already exist. Materialized ViewUnlike an ordinary view, which only contains an SQL statement, a materialized view contains the rows of data resulting from an SQL query against one or more base tables. The materialized view can be set up to automatically keep itself in synch with those base tables. Materialized view logWhenever a change is made to one of the underlying base tables; the database stores a log on each change. Using DBMS_SNAPSHOT packageYou can use the REFRESH procedure of the DBMS_SNAPSHOT package to refresh periodically a snapshot manually. UNIONThe UNION set operator combines the results of two queries into a single result with no record duplication. INTERSECTThe INTERSECT set operator returns all the rows contained in both tables. MINUSThe MINUS set operator returns all the rows in one table minus the rows contained in other table. TablespaceA tablespace is a logical database structure that is designed to store other logical database structures. Oracle sees a tablespace as a large area of space into which Oracle can place new objects. Space in tablespace is allocated in segments. 

Page 63: (SQL Tutorial)

Partitioned tablePartitioned tables are just like regular tables except for an important small feature-they enable you to reference the individual segments that might support larger tables directly. The ROLLUP functionIt is simple extension to the SELECT statement’s GROUP BY clause. It creates subtotals at any level of aggregation needed, from the most detailed up to a grand total. The CUBE functionIt is simple extension to the SELECT statement’s GROUP BY clause. It calculates subtotals for all the combinations of a group of dimensions. It also calculates a grand total. JAVAJAVA is a language that is portable, due to the fact that it is run within your environment. This environment may be a web browser, a database, or an application server. Nested TableIf an object is in an object, it is a nested object. A nested table is a table that is nested in another table. The “THE” sub-queryThe "THE" sub-query is used to identify the nested table to insert into. Note only one row may be inserted into the nested table at once using this method-as would be the case if you were inserting into any table. The REF CursorREF cursors hold cursors in the same way that VARCHAR2 variables hold strings. This is an added feature that comes with PL/SQL v2.2. A REF cursor allows a cursor to be opened on the server and passed to the client as a unit rather than one row at a time. One can use a Ref cursor as a target of assignments and can be passed as parameters to the Program Units. Ref cursors are opened with an OPEN FOR statement and in all other ways, they are the same as regular cursors. Table of RecordsA table of records is a new feature added in PL/SQL v2.3. It is the equivalent of a database table in memory. If you structure the PL/SQL table of records with a primary key (an index) you can have array-like access to the rows.Table of records differ from arrays in that they are not bound by a fixed lower or higher limit. Nor do they require consecutive index numbers as arrays do. Consult a PL/SQL reference manual (version 2.3 or higher) for further explanation. There are three steps involved in creating a table of records. Oracle Server is an object-relational database management system that provides an open, comprehensive, and integrated approach to information management. It consists of an Oracle database and instance.The Oracle Database contains all user data information. It has a physical and a logical structure.The “Physical Structure” is determined by the operating system files; such as data files, control files, and parameter files.

Page 64: (SQL Tutorial)

The “Logical Structure” is determined by the Oracle Database, such as tablespaces, tables, and segments.An instance is a combination of Oracle background processes and memory buffers.The memory buffer is called System Global Area (SGA) and is shared by the database users. Every time a database is started the system global area is allocated and Oracle background processes are started.Oracle Background Processes Server tasks between memory and disk.A user establishes connection and then requests information using a client application from the Oracle Server.The Listener process waits for connection requests from a client application, and routes each client to a server process.Server processes are created on behalf of each user’s application to read a user request and return the results.The TNSNAMES.ORA and SQLNET.ORA files establish client session connectivity to a server using the local naming option.

“Of course there is no formula for success except perhaps an unconditional acceptance of life and what it brings.” Arthur Rubinstein (1886 - 1982)

General Questions:Q: What does the DML stand for?Q: What are the examples of the DML statement?Q: What should a ‘SELECT’ statement consist of?Q: Can you perform a mathematical operation on a ‘SELECT’ statement?Q: What is the DUAL table?Q: When do you use the DUAL table?Q: What does the DUAL table contain?Q: What is the NULL value?Q: What is the result of 100+NULL?Q: What does the NVL function?Q: What is a COLUMN HEADING?Q: What is a TABLE ALIAS?Q: How can you concatenate two columns or strings?Q: What does the LIKE clause?Q: What does the DECODE function?Q: How many different types of JOIN table do you know?Q: What is an inner join table?Q: What is an outer join table?Q: What is an equi-join table?Q: What is the difference between an inner join table and an outer join table?Q: What is a SELF JOIN table?Q: What is the Cartesian product?Q: How can you avoid having a Cartesian product?Q: What is an anonymous column?Q: How can you avoid having an anonymous column?Q: When do you use the GROUP BY clause?Q: What does the EXISTS operation produce?Q: What does the IN operation produce?Q: What is a runtime variable?

Page 65: (SQL Tutorial)

Q: What is a table?Q: What is the difference between a VARCHAR2 datatype and a CHAR datatype?Q: What is the difference between a DATE and NUMBER datatypes?Q: How does a DATE store in the Oracle database?Q: What is the difference between a LONG RAW and BLOB datatypes?Q: What is the difference between a LONG and CLOB datatypes?Q: What is a ROWID of a record?Q: What is the BFILE datatype?Q: What is a data dictionary in the Oracle database?Q: What type of data store in a data dictionary?Q: What is a data dictionary view?Q: What is DDL?Q: What does DDL stand for?Q: What are the differences between a TRUNCATE and DELETE commands?Q: What is a high watermark in the Oracle table?Q: What is implicit in a DDL statement?Q: What is the Oracle9i ANSI?Q: What are the differences between the NATURAL JOIN and JOIN syntaxes?Q: When do you use the USING clause in the Oracle ANSI database?Q: Write and describe all different types of JOIN in the Oracle ANSI statements?Q: What is an inline view in the Oracle database?Q: What is the materialized view?Q: What is the view?Q: When do you use the DBMS_SNAPSHOT package?Q: What is the materialized view log?Q: Describe the UNION, INTERSET, and MINUS set operators in the Oracle SELECT statement?Q: What is a tablespace in the Oracle database?Q: What is a partitioned table in the Oracle database?Q: When do you use a partitioned table in the Oracle database?Q: What are the differences between Oracle table and Oracle partitioned table?Q: What is the ROLLUP function?Q: What is the CUBE function?Q: What is the Nested Table in the Oracle database?Q: What is the logical structure in the Oracle database?Q: What is the physical structure in the Oracle database?Q: What is an instance in the Oracle database?Q: What is SGA?Q: What are the Oracle Background Processes?Q: What is the listener process in the Oracle database?

Lesson 19“Nothing in the world can take the place of persistence. Talent will not; nothing is more common than unsuccessful men with talent. Genius will not; unrewarded genius is almost a proverb. Educations will not the world is full of educated derelicts. Persistence and determination alone are omnipotent. The slogan, 'Press on,' has solved and always will solve the problems of the human race.” --Calvin Coolidge

Answers:

Page 66: (SQL Tutorial)

Q: What are the definitions of the following items?column,record,table,item,field,element,primary key,foreign key, anddatatype.

A: A column is a smallest unit in a database that you need to deal with. A record is a collection of columns and a table is a collection of records. The terms: elements, columns, fields and items can be used interchangeably. A primary key is a unique identifier in a table. A foreign key is a column in a table (child) that references to a primary key column in another table (parent). Relationships between two tables are normally established by defining primary or foreign keys. A datatype is a format that an input data will be stored in a column.Q: What is the relationship between primary and foreign keys?A: Relationships between two tables are normally established by defining primary or foreign keys. It will establish a child and parent relationships. A foreign key is a column in a table (child) that references to a primary key column in another table (parent).Q: Describe the Entity Relationship diagram and Logical Data Model.A: "Entity Relationship Diagram" or "Logical Data Model" is used to establish relationships between entities.Q: What is a composite index?A: If an index key or a primary key were composed of more than one column. We call it a composite index.Q: What are the responsibilities of an Oracle DBA and Oracle Developer?A: The integrity, security, connectivity, performance, and tuning of a database will be maintained by DBAs. One of the responsibilities of a DBA is to plan a contingency for disaster and ensure recovery of the database. On the other hand developers use front-end and back-end tools along with management tools to perform their tasks. They develop applications to manipulate a database’s data. Their application will query, insert, delete and update a record or records. They use front-end tools such as "form builder," "report builder," and "graphics builder." They use back-end tools such as "schema builder," "procedure builder," and "query builder." They use project builder tools to manage and deliver their applications to their clients.Q: What is a Database?A: A collection of all tables under a single or many different schemas can be stored and maintained in a database. A database, in effect, is a collection of objects such as tables, indexes, stored procedures, etc.Q: Query the employee names and their salaries from the employee table.A: SQL> SELECT ename, sal FROM emp;Q: Do the above query and use an “as” clause for the “salary” column aliases or column headings.A: SQL> SELECT ename, sal AS salary FROM emp;Q: Repeat the previous query and have “Full Name” for the ename’s column heading and “Salary” for the “sal” column heading.A: SQL> SELECT ename “Full Name”, sal "Salary"FROM emp;Q: What is the result of 100 + NULL?

Page 67: (SQL Tutorial)

A: NULL.Q: Query the employee names with their commissions.A: SQL> SELECT ename, comm commission FROM emp;Q: Use the (NVL) the null value function to assign zero to any null value in the commission column for the previous query.A: SQL> SELECT ename, NVL(comm,0) commissionFROM emp;Q: Concatenate the customers’ last name and first name separated by comma.A: SQL> SELECT last_name || ', ' || first_name AS "full name"FROM customers;Q: Query the employees name sorted by ascending order.A: SQL> SELECT enameFROM empORDER BY ename ASC;Q: Query the employees name sorted by descending order.A: SQL> SELECT ename FROM empORDER BY ename DESC;Q: Query the employee information whose employee number is 7788.A: SQL> SELECT *FROM empWHERE empno = 7788;Q: Query the employees name whose names start with the letter “M.”A: SQL> SELECT enameFROM empWHERE ename LIKE 'M%';Q: Query the employees name whose names end with the letter “R.”A: SQL> SELECT enameFROM empWHERE ename LIKE '%R';Q: Query the employees name whose salaries between 2000 and 3000 dollars.A: SQL> SELECT enameFROM empWHERE sal BETWEEN 2000 AND 3000;Q: Query the employees name and their department name using the “DECODE” function. If the department number is 10 then print "accounting.” If the department number is 20 then print "research," or if the department number is 30 then print "sales." Anything else prints others.A: SQL> SELECT ename, DECODE (deptno, 10, 'Accounting',20, 'Research',30, 'Sales','Others') AS "Department"FROM emp;Q: What is an ambiguous column?A: An ambiguous column is a column that is not defined clearly. Having two tables with the same column name, you should reference them such that there is no ambiguity on their ownerships.Q: How can you resolve an ambiguous column problem?A: The column name should be identified by alias to make it clear that to what table that column is belong.Q: What is a Cartesian product?

Page 68: (SQL Tutorial)

A: A “Cartesian” product is caused by joining “N” number of tables while you have less than “N-1” joins condition in the query.Q: How can you avoid a Cartesian product?A: To avoid it, just when joining “N” number of tables you should have more or equal “N-1” joins condition in the query.Q: What is an inner join or equi-join?A: Joining two or more tables together using the WHERE clause with the equal sign (=) in a query. This type of query will retrieve records that have exact match and will be called inner join or equi-join.Q: What is an outer join?A: Joining two or more tables using OUTER join, not only you retrieve all matching records but also you retrieve the records that do not match.Q: What is a self join?A: When a table refers to itself in the WHERE clause, we call that join is a self-join.Q: Query all the employee names and their department including all the departments with no employees.A: SQL> SELECT ename, dnameFROM emp e, dept dWHERE e.deptno (+) = d.deptno;Q: Query the managers’ name with their employees sorted by the manager name.A: SQL> SELECT mgr.ename “Manager Name”, e.ename “Employee Name”FROM emp mgr, emp eWHERE mgr.empno = e.mgrORDER BY mgr.ename;Q: Query the department number and their total, average, min, and max salaries for each department.A: SQL> SELECT deptno, SUM(sal), AVG(sal), MIN(sal), MAX(sal)FROM empGROUP BY deptno;Q: Query the department no and their total salaries that have more than 5 employees working in their department.A: SQL> SELECT deptno, SUM(sal)FROM empGROUP BY deptnoHAVING count(*) > 5;Q: Query the employees name that work for the Research or Sales department (the department number 20 or 30).A: SQL> SELECT ename, deptnoFROM empWHERE deptno IN (20, 30);Q: Query the employees name that work in the "accounting" department. Assuming the department number is unknown.A: SQL> SELECT enameFROM empWHERE deptno IN(SELECT deptnoFROM deptWHERE dname = "ACCOUNTING");Q: Query the employees name and use the runtime variable to substitute the department number? Then run it for following department no 10, 20, and 30.

Page 69: (SQL Tutorial)

A: SQL> SELECT enameFROM empWHERE deptno = &deptno;SQL> /Q: Query the customer names which have more than four orders.A: SQL> SELECT nameFROM customer cWHERE exists(SELECT 'T'FROM ordWHERE custid = c.custidGROUP BY custidHAVING count(*) > 4);Q: Create an employee table that contains five columns:Such as Employee Id, last name, First name, Phone number and Department number with the following constraints.1. The last name and first name should be not null.2. Make a check constraint to check the department number is between 9 and 100.3. Make a primary constraint on the employee ID column.4. Make a foreign key on the department number column.5. Use the "delete cascade" to delete all records if parent gets deleted.6. Use the "phone number" as a unique key.

A: SQL> CREATE TABLE employee(empid NUMBER(10),lastname VARCHAR2(20) not null,firstname VARCHAR2 (20) not null,phone_no VARCHAR2 (15),deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),constraint pk_employee_01 PRIMARY KEY (empid),constraint fk_dept_01 FOREIGN KEY (deptno)references dept (deptno) ON DELETE CASCADE,constraint uk_employee_01 UNQUE (phone_no));Q: Create a composite index on the employee table that contains two index columns (last name and first name).A: SQL> CREATE INDEX employee_lname_fname_ind_01ON employee (lastname, firstname);Q: Query the tables that you as a user own.A: SQL> SELECT table_nameFROM user_tablesORDER BY table_name;Q: Query the index tables that belong to the employee table and owns by the iself user.A: SQL> SELECT index_name, uniquenessFROM user_indexesWHERE table_name = 'EMPLOYEE';Q: Change the size of the "column_name" to 30 characters logically (for display only).A: SQL> COLUMN column_name FORMAT a30Q: Query the indexes columns of the employee table.A: SQL> SELECT index_name, column_name, column_positionFROM user_ind_columnsWHERE table_name = 'EMPLOYEE';

Page 70: (SQL Tutorial)

Q: Insert a record into the "employee" table using column names.A: SQL> INSERT INTO employee(empid, lastname, deptno, firstname, phone_no)VALUES (100, 'smith', 10,'joe', ‘7038212211');Q: Insert a record using the column position format.A: SQL> INSERT INTO employeeVALUES (200, 'KING', 'Allen', 5464327532, 10);Q: How do you save the inserted transaction?A: COMMIT;Q: Change the "last_name" column value from “Smith” to “Judd” where the "employee id" is 100.A: SQL> UPDATE employeeSET lastname = 'Judd'WHERE empid = 100;Q: Delete all the employee records from the "employee" table using the delete command and the truncate command.A: SQL> DELETE FROM employee;ORSQL> TRUNCATE TABLE employee;Q: How do you undo a transaction?A: ROLLBACK;Q: What is the difference between the delete statement and the truncate statement?A: Notice that the TRUNCATE command is a DDL statement and all DDL statements have commit inclusive. That is why the ROLLBACK action after truncation does not work. Also, if you want to delete all records from a table, you should use the TRUNCATE statement. It will change the table watermark. The table watermark is an address that indicates a last location of a record in a table. On the DELETE statement the watermark will not change. But using the TRUNCATE statement will change the watermark to the beginning of the table.Q: Copy the “EMP” table to another table and name the new table "employee." In the new employee table use the employee name, job, commission and department number.A: SQL> CREATE TABLE employeeAS SELECT ename, job, comm, deptnoFROM emp;Q: Add a salary column to the employee table.A: SQL> ALTER TABLE employeeADD (salary NUMBER(8,2));Q: Modify the "ename" column size from varchar10 to varchar15.A: SQL> ALTER TABLE employeeMODIFY (ename VARCHAR2(15));Q: Rename the "employee" table to the "iself_employee" table.A: SQL> RENAME employee TO iself_employee;Q: Create a view to display the employee names of the “Accounting” department only.A: SQL> CREATE VIEW employee_nameAS SELECT enameFROM iself_employeeWHERE deptno = 10;Q: Why do you use the view?A: You use view to present rows and columns of a table in the way you want. You may use it for security reason. For example, you may eliminate some rows and columns that are very sensitive information. These changes are transparent to a user.

Page 71: (SQL Tutorial)

Q: How do you compile the view?A: SQL> ALTER VIEW employee_name COMPILE;Q: How do you delete the view?A: SQL> DROP VIEW employee_name;Q: Create an index on the employee table on the ename column only and name it employee_indx.A: SQL> CREATE INDEX employee_indxON employee (ename);Q: Reorganize the “employee_indx” index table.A: SQL> ALTER INDEX employee_ indx REBUILD;Q: Drop the employee_ename index table.A: SQL> DROP INDEX employee_indx;Q: Create a user with username “newuser” and password "newpass." Its default tablespace should be the "iself_data" tablespace.A: SQL> CREATE USER newuser IDENTIFIED BY by newpassDEFAULT TABLESPACE iself_data;Q: Grant the resource and connect roles to newuser.A: SQL> GRANT resource, connect TO newuser;Q: Change the newuser password to "mypass".A: SQL> ALTER USER newuser IDENTIFIED BY mypass;Q: Can the above new user access to any other user tables?A: No.Q: What is a public synonym?A: It is a synonym that public users can use. We create public synonym so that the users don’t need to type schema name to a table when they query the table. Creating a public synonym does not mean that oracle users can access to that table or object. Still the owner of the object has to grant access to a user on its table.Q: What is the syntax to create a public synonym?A: SQL> CREATE PUBLIC SYNONYM employees FOR iself.iself_employee;Q: What is the difference between public and private synonym?A: The private synonym is only for the user who owns or created the synonym, but the public can be used by every users.Q: Create and drop a private synonym.A: SQL> CREATE SYNONYM emp_table FOR iself.iself_employee;To drop:SQL> DROP SYNONYM emp_table; Q: Revoke an object privilege on a table from a user.A: SQL> REVOKE UPDATE, SELECT ON employee FROM newuser;Q: What does the LIST or ‘L’ command line editor?A: It lists the current SQL statement that was typed in the Oracle buffer.Q: What does the INSERT or ‘I’ command line editor?A: It inserts a command in the Oracle buffer after the current active line that was indicated with an *.Q: What does the DEL or ‘D’ command line editor?A: It deletes the current active line in the Oracle Buffer.Q: How do you change a string in the Oracle Buffer?A: First, mark the line as a current active line and then type the‘del’ command.Q: How do you save the SQL script in the Oracle Buffer?A: SQL> save c:.sql

Page 72: (SQL Tutorial)

Q: How do you open the SQL Script into the Oracle Buffer?A: SQL> get c:.sqlQ: How do you use the notepad editor?A: Just type: the ed command to open the default editor.Q: What is afiedt.buf?A: The "afiedt.buf" file is a place that into which SQL*PLUS stores the most recently executed SQL statement.Q: How do you change your text editor in the SQLPLUS tool?A: Issue the define_editor='your editor' statement from the SQL*PLUS prompt.Q: What does the ed command in the SQLPLUS tool?A: We use the "ed" command, to open your default word editor.Q: Can you have multiple SQL statements in the afiedt.buf file?A: No. You can only use one SQL statement at a time.Q: How do you use the notepad editor as an independent tool in the SQLPLUS utility?A: Just open your notepad editor outside of your SQLPLUS.Q: How do you execute or run a SQL script?A: SQL> run c:.sql or start c:Q: What is the SQL ANSI statement?A: It is some standard roles that provided by American National Standards Institute.Q: What is the difference between the SQL ANSI statement and Original Oracle statement?A: The Original Oracle statements are not follow the role of American National Standards Institute.Q: Is the SET command a SQL statement?A: No.Q: How do you change your workstation’s page size or line size?A: SQL> SET LINESIZE 100 PAGESIZE 55Q: What does the JOIN syntax in the Oracle SQL (DML) statement?A: It does innor join using the ON clause.SQL> SELECT ename, dept.deptno, dnameFROM emp JOIN deptON emp.deptno = dept.deptnoAND dname <> 'SALES'/Q: What is the difference between the JOIN syntax and the NATURAL JOIN syntax?A: In the NATURAL JOIN syntax, you don't need the ON clause if the column’s names are the same.Q: What does the USING clause in the Oracle SQL statement?A: It joins two tables and in the USING clause the join column names must be the same.Q: What is the advantage of the NATURAL JOIN syntax?A: It is less typing.Q: What does the CROSS JOIN syntax in the Oracle SQL statement?A: We can use the Oracle9i ANSI standard CROSS JOIN syntax with no WHERE clause to create a Cartesian product.Q: What does the IN clause in the Oracle SQL statement?A: The IN clause in the Oracle SQL statement is an equivalent of the OR condition in the SQL statement.Q: What do the OUTER JOIN, RIGHT OUTER JOIN, LEFT OUTER JOIN, and FULL OUTER JOIN syntax in the Oracle SQL statement?A: We use the OUTER option when we want all records that have exact match plus those records that have no match.

Page 73: (SQL Tutorial)

Q: How can you perform the FULL OUTER JOIN syntax using the Original Oracle syntax?A: Although it is possible but it is very difficult to perform the full outer join using the original Oracle syntax.Q: When do you use the WITH … AS clause in the SQL statement?A: If we have a query which it needs to process the same sub-query several times, we should consider using the WITH …AS clause in our statement.Q: How does the WITH … AS clause help your performance?A: The query will create a temporary table to query it over and over.Q: Write a query to list all the department names that their total paid salaries are more than 1/3 of the total salary of the company.A: SQL> WITH summary_totals AS(SELECT dname,SUM(sal) AS totalsFROM emp NATURAL JOIN deptGROUP BY dname)SELECT dname, totalsFROM summary_totalsWHERE totals > (SELECT SUM(totals)*1/3FROM summary_totals)ORDER BY totals DESCSQL>/Q: What are the multiple columns in the SQL statement? Where or how do you use them?A: We use multiple columns to match the multiple columns returned from the sub-query.Q: Write a SQL statement to query the name of all employees who earn the maximum salary in their department using the multiple columns syntax.A: SQL> SELECT deptno, ename, job, salFROM empWHERE (deptno, sal) IN(SELECT deptno, MAX(sal)FROM empGROUP BY deptno)/Q: What is the inline view in the Oracle SQL statement?A: If we have a sub-query in a FROM clause in the Oracle SQL statement, is called an inline view.Q: Write a SQL statement to query all of the employee names, jobs, and salaries where their salary is more than 10% of the total company paid salary.A: SQL> SELECT ename, job, salFROM (SELECT ename, job, salFROM empWHERE sal > (SELECT SUM(sal) * .1FROM emp)ORDER BY 3)/Q: What does the MERGE statement in the SQL statement?A: We use the MERGE statement to merge one table into another table.Q: Can you update, insert, or delete any records while you are using the MERGE statement?A: Yes.Q: What is a Materialized View?A: A materialized view (MVIEW) is a replica of a target master from a single point in time.

Page 74: (SQL Tutorial)

Q: What are the Materialized View types?A: Read-Only Materialized ViewsUpdatable Materialized ViewsSub-query Materialized ViewsRow-id vs. Primary Key Materialized ViewsQ: Write the difference between ROWID and PRIMARY KEY in the Materialized View.A: Fast refresh requires association between rows at snapshot and master sites. Snapshots that use ROWIDs to refresh are called ROWID snapshots while those that use primary keys are called primary key snapshots.Q: What is the difference between a Materialized View and View?A: A Materialized View is a physical duplicated data in a table, but a View is just a logical presentation of a table.Q: When or why do you use a Materialized View?A: You use Materialized Views to create summaries in a data warehouse environment or replicate a data in a distributed environment. In data warehouses, you can use materialized views to pre-compute and store aggregated data such as the sum of sales. In distributed environments, you can use materialized views to replicate data from a master site to other distributed sites.Q: What is a materialized view log?A: A materialized view log is a holder that contains updated, inserted, or deleted records’ information in the primary table.Q: What are the PRIMARY KEY and ROWID in the Materialized View Log?A: The Materialized View log that use ROWIDs to refresh are called ROWID view log while those that use primary keys are called primary key view log.Q: What does the USER_SNAPSHOT_LOGS view contain?A: It shows if our log was created successfully and its name (MLOG$_EMP).Q: Create a materialized view that contains the department number, number of employees, and total salaries paid to employees by department.A: SQL> CREATE MATERIALIZED VIEW mv_salBUILD IMMEDIATEREFRESH ON DEMANDAS SELECT deptno,COUNT(1) AS no_of_emp, SUM(sal) AS salaryFROM empGROUP BY deptnoSQL> /Q: Who can create a materialized view?A: The one that was granted the CREATE MATERIALIZED VIEW privilege.Q: What does the USER_MVIEWS view contain?A: It contains all the Materialized Views’ information that were created by the user.Q: How do you refresh a materialized view?A: SQL> EXECUTE dbms_snapshot.refresh('mv_sal','C');Q: What parameter should be used to update the materialized view every month automatically without human intervention?A: The START WITH SYSDATE option will create an immediate data, and the NEXT(SYSDATE+30) option will update the table every 30 days.Q: What does the USER_JOBS view contain?A: It contains all users’ jobs in the Oracle queue.Q: How do you remove a job from the Oracle Job Queue?A: SQL> EXECUTE dbms_job.remove(job_number);

Page 75: (SQL Tutorial)

Q: How do you drop a materialized view log and a materialized view?A: SQL> DROP MATERIALIZED VIEW LOG ON emp;To drop it:SQL> DROP MATERIALIZED VIEW mv_sal;Q: What does the BREAK ON clause in SQLPLUS?A: It builds a break on a column.Q: What do the REPHEADER and REPFOOTER commands in SQLPLUS?A: They make a report header and footer.Q: What does the following commands?COLUMN sal HEADING 'Salary' FORMAT $99,999.99 --Creates heading format.COLUMN ename HEADING 'Employee' FORMAT a20 - Creates heading format.REPHEADER '' - Creates report heading.BREAK ON dname SKIP 1 - Creates control bread on a column and skip 1 line after the break.COMPUTE SUM OF sal ON dname - Computes total salary within a department.SPOOL c:.out -- Activates spooling.SPOOL OFF -- Deactivate spooling.REPFOOTER '' - Creates report footer.CLEAR BUFFER -- Clear the Oracle buffer.CLEAR COLUMNS - Clears columns.CLEAR COMPUTE -- Clears compute functions.Q: What does the CLEAR command in SQLPLUS?A: Note that all the values in REPHEADER, REPFOOTER, BUFFER, COLUMNS, COMPUTE and etc are going to stay the same during your open session. In order to clean them, you should use the CLEAR command for BUFFER, COLUMNS, and COMPUTE. And input NULL to REPHEADER and REPFOOTER.Q: What does the UNION statement in the SQL statement?A: It will query all the records that match or not match with the base table.Q: What does the INTERSET statement in the SQL statement?A: It will query all the records that match with the base table. It is the same as joining two tables.Q: What does the MINUS statement in the SQL statement?A: It will query all the records that are not matching against your base table.Q: Why it is important to eliminate duplicate records?A: To keep your database integrity.Q: What does the following SQL statement?SQL> DELETE FROM dup_empWHERE ROWID IN (SELECT MAX(ROWID)FROM dup_empGROUP BY empnoHAVING COUNT (empno) > 1)SQL> /A: Deletes all the rows that have the same employee number except the first one.Q: What is a data partitioning in the Oracle database?A: The data partitioning in the Oracle database is that the data will be partitioned in multi-tablespaces for ease of maintenances.Q: When should you use data partitioning?A: When you have a huge data file and can be classified to some partitions.Q: What is the advantage of using a data partitioning?A: It is faster to access. It is easier to maintain.

Page 76: (SQL Tutorial)

Q: What is a partition key?A: It is used to separate data and associates them to their own assigned tablespace.Q: What is a local index in the data partitioning?A: A Local index is one that is partitioned exactly like the table to which it belongs.Q: What is a global index in the data partitioning?A: A Global index, unlike local indexes, you should explicitly partition range boundaries using the “VALUE LESS THAN” methods.Q: What are the differences between local and global indexes?A: In the local index you don’t define explicitly partition range.Q: How does the ‘VALUE LESS THAN’ method work in the data partitioning?A: The VALUES LESS THAN clause indicates the partition key value must be less then its assigned value in order to be illegible for any DML transaction on its assigned tablespace.Q: Why do you need multiple tablespaces?A: Multiple tablespaces give us more flexibility to maintain a tablespace without affecting any performance or downtime to others.Q: Create a range-based partitioning table named p_emp. Make sure that the data entry of the each department goes to its own provided tablespaces such as the accounting department goes to the dept10ts tablespace, the data entry of the research department goes to the dept20ts tablespace, etc.A: SQL> CREATE TABLE p_emp (empno NUMBER(4) PRIMARY KEY,ename VARCHAR2(10),job VARCHAR2(9),mgr NUMBER(4),hiredate DATE,sale NUMBER(7,2),comm NUMBER(7,2),deptno NUMBER(2))STORAGE (INITIAL 5KNEXT 5KPCTINCREASE 0)PARTITION BY RANGE (deptno)(PARTITION dept10VALUES LESS THAN (20)TABLESPACE dept10ts,PARTITION dept20VALUES LESS THAN (30)TABLESPACE dept20ts,PARTITION dept30VALUES LESS THAN (40)TABLESPACE dept30ts,PARTITION deptxxVALUES LESS THAN (MAXVALUE)TABLESPACE deptxxts)SQL> /Q: What does the MAXVALUE parameter mean in the data partitioning?A: It means as large as the column can hold.Q: How do you analyze a partition table?A: SQL> ANALYZE TABLE p_emp COMPUTE STATISTICS;Q: What does the USER_TAB_PARTITIONS view contain?

Page 77: (SQL Tutorial)

A: A user can query its partitions table’s information that was created by the user.Q: Write a query to list the accounting employees from the partition table. Use the partition option.A: SQL> SELECT * FROM p_emp PARTITION (dept10);Q: Write a query to list employee number 7900 from the sales department?A: SQL> SELECT * FROM p_emp PARTITION (dept30)WHERE empno = 7900SQL> /Q: How do you create a local partition index?A: SQL> CREATE INDEX p_emp_ind ON p_emp (deptno) LOCAL;Q: How do you analyze a partition table index?A: SQL> ANALYZE INDEX p_emp_ind COMPUTE STATISTICS;Q: What does the USER_IND_PARTITIONS view contain?A: It contains information in regard to the user’s partition indexes.Q: What does the ROLLUP operator?A: The ROLLUP operator returns both ‘regular rows’ and ‘super-aggregate rows.’ Super-aggregate rows are rows that contain a sub-total value. Q: What does the CUBE function?A: The CUBE operator returns cross-tabulation values, thus produces totals in all possible dimensions, and is used for warehousing aggregated data reports.Q: What are the differences between the CUBE and ROLLUP functions?A: See the output…Q: What environments may use the CUBE and ROLLUP functions most?A: Warehousing.Q: Write a query to list an aggregation sum report for each job, in each year, using the ROLLUP grouping option.A: SQL> SELECT year, job, SUM(sal), COUNT(*)FROM empGROUP BY ROLLUP (year, job)SQL> /Q: Write a query to list an aggregation sum report for each job, in each year, using the CUBE grouping option.A: SQL> SELECT year, job, SUM(sal), COUNT(*)FROM empWHERE deptno = 20GROUP BY CUBE (year, job)SQL> /Q: What is an object type?A: The object type in the Oracle database is like the class eliminate in the C++ developer tool or any object oriented tool.Q: What is a collection object?A: The collection object in the Oracle database is like a nested table and a variable array in a table.Q: Create an object type with two columns to hold the employee's child name and date of birth and name it employee_kids .A: SQL> CREATE TYPE employee_kids AS OBJECT (NAME VARCHAR2(30),dob DATE

Page 78: (SQL Tutorial)

)SQL> /Q: Create a table type using employee_kids and name it employee_kids_table.A: SQL> CREATE TYPE employee_kids_tableIS TABLE OF employee_kids;Q: Create the emp_family table containing the kid’s column with a type of employee_kids_table.A: SQL> CREATE TABLE emp_family(empno NUMBER,kids employee_kids_table)NESTED TABLE kids STORE AS nested_employee_kids_tableSQL> /Q: How do you insert a record in the object type?A: SQL> INSERT INTO emp_family VALUES(7902,employee_kids_table(employee_kids('David','08-AUG-01'),employee_kids('Peter','10-JUN-88'),employee_kids('Mark','30-OCT-92')))SQL> /Q: What is the constructor?A: The constructor creates an empty nested table as opposed to leaving it null. Notice that without using the constructor, it is not possible to refer to the nested table with the "THE" clause.Q: What is the ‘THE’ sub-query?A: To query a nested table you should use the "THE" clause. Also, the "THE" sub-query is used to identify the nested table to INSERT INTO.Q: How do you query a record using the ‘THE’ sub-query?A: SQL> SELECT nameFROMTHE(SELECT kids FROM emp_family WHERE empno = 7788)SQL> /Q: What is a nested table?A: It is a table within a table.Q: How do you insert a record to a nested table?A: SQL> INSERT INTOTHE(SELECT kids FROM emp_familyWHERE empno = 7900)VALUES ('Sue','10-DEC-99');Q: How do you update a record to nested table?A: SQL> UPDATE emp_familySET kids = employee_kids_table(employee_kids('Sara','08-OCT-88'))WHERE empno = 7788SQL> /Q: How do you add a unique index to a nested table?

Page 79: (SQL Tutorial)

A: SQL> CREATE UNIQUE INDEX i_nested_employee_kids_tableON nested_employee_kids_table(nested_table_id,name)SQL> /Q: What is a data replica?A: A duplicated data in a different location.Q: What is the difference between a materialized view and a materialized view log?A: The Materialized view is a real duplicated data from a primary table but the materialized view log is an on going logs generated due to the table changes after the last refresh.Q: What is an OID (Object ID)?A: It is a unique ID assigned to an object by Oracle.Q: How do you retrieve an object ID?A: SQL> SELECT OWNER, TYPE_OID FROM DBA_TYPESWHERE TYPE_NAME LIKE 'ADDRESS%';Q: How do you use an object ID to create an object type?A: SQL> CREATE OR REPLACE TYPE address_book_type_objectOID ‘XXXXXXXXXXXXXXXXXXXXX’AS OBJECT (id_address NUMBER(1),address VARCHAR2(20));Q: What is the relationship between primary and foreign keys?A: The relationships between two tables are normally established by defining primary or foreign keys. A primary key has the immutable responsibility of serving as a unique identifier in a table. A foreign key is a column that refers to the primary key of another table. To join two tables, a “where clause” is used to set up a table relationship between primary and foreign keys.Q: What is a composite index?A: A primary key can be composed of more than one column. We call it a composite index.Q: What is the result of 100 + NULL?A: NULL value.Q: Write a query to concatenate the customers’ last name and first name separated by comma.A: SELECT last_name || ‘, ‘ || first_nameas “Full Name”FROM customers/Q: Query the employees name and their department name using the “DECODE” function. If the department number is 10 then print "accounting.” If the department number is 20 then print "research," or if the department number is 30 then print "sales." Anything else prints others.A: SELECT ename, DECODE (deptno, 10, 'Accounting',20, 'Research',30, 'Sales','Others') AS "Department"FROM emp/Q: Query the department number and their total salaries that have more than 5 employees working in their department.A: SELECT deptno, SUM(sal)FROM empGROUP BY deptnoHAVING count(*) > 5

Page 80: (SQL Tutorial)

/Q: query the customer names which have more than four orders.A: SELECT name FROM customer cWHERE exists (SELECT 'T' FROM ordWHERE custid = c.custidGROUP BY custidHAVING count(*) > 4)/Q: Create an employee table that contains five columns:Such as Employee Id, last name, First name, Phone number and Department number with the following constraints.7. The last name and first name should be not null.8. Make a check constraint to check the department number is between 9 and 100.9. Make a primary constraint on the employee ID column.10. Make a foreign key on the department number column.11. Use the "delete cascade" to delete all records if parent gets deleted.12. Use the "phone number" as a unique key.

A: CREATE TABLE employee(empid NUMBER(10),lastname VARCHAR2(20) not null,firstname VARCHAR2 (20) not null,phone_no VARCHAR2 (15),deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),constraint pk_employee_01 PRIMARY KEY (empid),constraint fk_dept_01 FOREIGN KEY (deptno)references dept (deptno) ON DELETE CASCADE,constraint uk_employee_01 UNQUE (phone_no))/Q: What is the difference between the delete statement and the truncate statement?A: On the DELETE statement the watermark will not change. But using the TRUNCATE statement will change the watermark to the beginning of the table.Q: Copy the “EMP” table to another table and name the new table "employee." In the new employee table use the employee name, job, commission and department number.A: CREATE TABLE employeeAS SELECT ename, job, comm, deptnoFROM emp/Q: Reorganize the “employee_indx” index table.A: ALTER INDEX employee_indx REBUILD/Q: What is the difference between public and private synonym?A: You create synonym so that the users don’t need to type schema name to a table when they query the table. The Public Synonym is available to all database users but the Private Synonym is available only to the owner of synonym.Q: Can you have multiple SQL statements in the afiedt.buf file?A: No.Q: How do you execute or run a SQL script?A: SQL> @my_sql_script; or start my_sql_script;Q: Write a query to list all the department names that their total paid salaries are more than 1/3 of the total salary of the company.

Page 81: (SQL Tutorial)

A: SQL> WITH summary_totals AS(SELECT dname,SUM (sal) AS totalsFROM emp NATURAL JOIN deptGROUP BY dname)SELECT dname, totalsFROM summary_totalsWHERE totals > (SELECT SUM (totals)*1/3FROM summary_totals)ORDER BY totals DESCSQL>/Q: What is a Materialized View?A: A materialized view (MVIEW) is a replica of a target master from a single point in time. You use Materialized Views to create summaries in a data warehouse environment or replicate a data in a distributed environment. In data warehouses, you can use materialized views to pre-compute and store aggregated data such as the sum of sales. In distributed environments, you can use materialized views to replicate data from a master site to other distributed sites.Q: What does the following SQL statement?SQL> DELETE FROM dup_empWHERE ROWID IN (SELECT MAX(ROWID)FROM dup_empGROUP BY empnoHAVING COUNT (empno) > 1)SQL> /A: Deletes duplicated records.Q: What does the MAXVALUE parameter mean in the data partitioning?A: It is the maximum possible value that can be store into a column.Q: What does the following SQL statement?SQL> INSERT INTO THE(SELECT kids FROM emp_familyWHERE empno = 7900)VALUES ('Sue','10-DEC-99')SQL> /A: Inserts a record to a nested object in a table.