Sie sind auf Seite 1von 30

SQL Introduction SQL (Structured Query Language) is a database sublanguage for querying and modifying relational databases.

It was developed by IBM Research in the mid 70's and standardized by ANSI in 1986. The Relational Model defines two root languages for accessing a relational database -- Relational Algebra and Relational Calculus. Relational Algebra is a low-level, operator-oriented language. Creating a query in Relational Algebra involves combining relational operators using algebraic notation. Relational Calculus is a high-level, declarative language. Creating a query in Relational Calculus involves describing what results are desired. SQL is a version of Relational Calculus. The basic structure in SQL is the statement. Semicolons separate multiple SQL statements. ORACLE is relational database management system What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database. According to ANSI (American National Standards Institute), it is the standard language for relational database management systems. SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingress, etc. Although most database systems use SQL, most of them also have their own additional proprietary extensions that are usually only used on their system. However, the standard SQL commands such as

"Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used to accomplish almost everything that one needs to do with a database. In relational database systems (DBS) data are represented using tables (relations). A query issued against the DBS also results in a table. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column. Rows contain the records or data for the columns. A table can have up to 254 columns. Oracle offers the following basic data types: char(n): Fixed-length character data (string), n characters long. A string of type char is always padded on right with blanks to full length of n. (+ can be memory consuming). Example: char(40) varchar2(n): Variable-length character string.It is not padded with blank spaces Example: varchar2(80) number(d, p): Numeric data type for integers and real. D is the total umber of digits, p is the number of digits to the right of the decimal point. Data types derived from number are int[eger], dec[imal], smallint and real. Example: 234.45 is data type number (5,2). date: Date data type for storing date and time. The default format for a date is: DD-MMM-YY. Examples: 13OCT-94, 07-JAN-98 1 long: Character data up to a length of 2GB. Only one long column is allowed per table.

Note: . It can, however, be simulated by using either char(1) or number(1). Select: The select statement is used to query the database and retrieve selected data that match the criteria that you specify. Here is the format of a simple select statement: select [distinct] <column(s)> from <table> [where <condition> ] [Order by <column(s) [asc|desc]>] The columns to be selected from a table are specified after the keyword select. This operation is also called projection. . If all columnsshould be selected, the asterisk symbol * can be used to denote all attributes. The select clause may also contain arithmetic expressions. Eg:- select ENAME, DEPTNO, SAL _ 1.55 from EMP; Here is the complete format of the SELECT statement: SELECT [ALL | DISTINCT] column1[,column2] FROM table1[,table2] [WHERE "conditions"] [GROUP BY "column-list"] [HAVING "conditions] [ORDER BY "column-list" [ASC | DESC] ] Note :-see the order in which clauses are executing.

order by: It is also possible to specify a sorting order in which the result tuples of a query are displayed. For this the order by clause is used and which has one or more attributes listed in the select clause as parameter. desc specifies a descending order and asc specifies an ascending order this is also the default order). For example, the query select ENAME, DEPTNO, HIREDATE from EMP; from EMP order by DEPTNO [asc], HIREDATE desc; If one is interested in tuples that satisfy certain conditions, the where clause is used. In a where clause simple conditions based on comparison operators can be combined using the logical connectives and, or, and not to form complex conditions. Conditions may also include pattern matching operations and even sub queries . Example: List the job title and the salary of those employees whose manager has the number 7698 or 7566 and who earn more than 1500: select JOB, SAL from EMP where (MGR = 7698 or MGR = 7566) and SAL > 1500; For all data types, the comparison operators = > < > = Equal, Greater than, Less than, Greater than or equal,

< Less than or equal, = < Not equal to, > are allowed in the conditions of a where clause. Like:- A powerful operator for pattern matching is the like operator. Together with this perator, two special characters are used: 1.The percent sign % (also called wild card) which matches zero or more characters including none. 2.The underline , called position marker which matches exactly one character. For example, to select all tuples from the table DEPT that contain two C in the name of the department, the condition would be where DNAME like %C%C%. character appears between the two Cs. To test for inequality, the not clause is used. Further string operations are: upper(<string>) takes a string and converts any letters in it to uppercase, e.g., DNAME = upper(DNAME) (The name of a department must consist only of upper case letters.) lower(<string>) converts any letter to lowercase, initcap(<string>) converts the initial letter of every word in <string> to uppercase. length(<string>) returns the length of the string. substr(<string>, n [, m]) clips out a m character piece of <string>, starting at position n. If m is not specified, the end of the string is assumed. Eg:- substr(DATABASE SYSTEMS, 10, 7) returns the string

SYSTEMS. TRIM enables you to trim leading or trailing characters (or both) from a character string TRIM ( [{ { LEADING | TRAILING | BOTH } [trim_character]) | trim_character } FROM ] trim_source )

If trim_character or trim_source is a character literal, then you must enclose it in single quotes.

If you specify LEADING, then Oracle removes any leading characters equal to trim_character. If you specify TRAILING, then Oracle removes any trailing characters equal to trim_character. If you specify BOTH or none of the three, then Oracle removes leading and trailing characters equal to trim_character. If you do not specify trim_character, then the default value is a blank space. If you specify only trim_source, then Oracle removes leading and trailing blank spaces. The function returns a value with datatype VARCHAR2. The maximum length of the value is the length of trim_source. If either trim_source or trim_character is null, then the TRIM function returns null.

Eg:-SELECT TRIM (0 FROM 0009872348900) "TRIM Example"

FROM DUAL; TRIM Example -----------98723489 Eg:- select trim (leading x from xxxMCAxxxx) from dual; TRIM Example -----------MCAxxxx CONCATENATE CONCATENATE('string1' || 'string2' Or CONCAT(str1, str2, [,...n]) ASCII Get The ASCII Value Of A Character Eg:-SELECT ASCII('A') FROM dual; INSTR Simple searching.It is like like operator except that like can only be used in where/having caluse.Instr can be used anywhere except in the from clause. Syntax.:Instr(string,set [start,[occurrence]]); By default it will start the search at position 1.If we specify start it will skip all the characters upto that point and begin its search there. Eg:-Select instr(oracle oracle,o,1,2) o/p -10. Translate

Replaces a sequence of characters in a string with another set of characters.It performs a character by character replacement. Eg:- select translate(1sct523 123,797) from dual; o/p:- 9sct597 vsize Returns the number of bytes in the internal representation. Syntax: Vsize(expression) Eg:-select vsize(snum) from dual; Aggregate Functions Aggregate functions are statistical functions such as count, min, max ,sum and avg. Eg:1. How many tuples are stored in the relation EMP? select count(*) from EMP; count(*) returns all the rows in a table 2. How many different job titles are stored in the relation EMP? select count(distinct JOB) from EMP; 3. List the minimum and maximum salary. select min(SAL), max(SAL) from EMP; 4. Compute the difference between the minimum and maximum salary. select max(SAL) - min(SAL) from EMP; 5. Sum of all salaries of employees working in the department 30. select sum(SAL) from EMP where DEPTNO = 30; Note :- avg, min and max ignore the null values , but count considers null values. Examples:--1. select first, last, city from empinfo;

2. select 3. select

last, city, age from empinfo where age > 30; first, last, city, state from empinfo where first LIKE 'J * from empinfo; first, last, from empinfo where last LIKE '%s'; first, last, age from empinfo where last LIKE '%illia * from empinfo where first = 'Eric';

%';
4. select 5. select 6. select

%';
7. select

Select statement exercises 1. Display everyone's first name and their age for everyone that's in table. select first, age from empinfo; 2. Display the first name, last name, and city for everyone that's not from Payson. select first, last, city from empinfo where city <> 'Payson'; 3. Display all columns for everyone that is over 40 years old. select * from empinfo where age > 40; 4. Display the first and last names for everyone whose last name ends in an "ay". select first, last from empinfo where last LIKE '%ay'; 5. Display all columns for everyone whose first name equals "Mary".

select * from empinfo where first = 'Mary'; 6. Display all columns for everyone whose first name contains "Mary". select * from empinfo where first LIKE '%Mary%'; Date Functions ADD_MONTHS (date, number of months) Adds the specified number of months to the date (subtracts months if the number of months is negative).
1)

2) LAST_DAY(date) Returns the last day of the month that contains the date Eg:-Select LAST_DAY(15-FEB-2000) from dual; o/p :- 29-FEB-2000 3) MONTHS_BETWEEN(date1,date2) Returns the difference between two dates . Note: If date1 is earlier than date2, the result is negative. The result also takes into account time differences between the two values. eg:Select MONTHS_BETWEEN(02-FEB-2001,01-JAN2001) from dual; 1.03225806 4) NEXT_DAY(date,day name) Returns the date of the first day of the specified name that is later than the date supplied Example :-select NEXT_DAY(14-MAR2001,TUESDAY) from dual; 20-MAR-2001 5) ROUND (datetime,format)

Returns the date-time rounded to the unit specified by the format, or to the nearest day if no format is supplied Eg:- Select ROUND(27-OCT-1999, YEAR) from dual; 01-JAN-2000 6) SYSDATE Returns the current date-time from the server where the database is located 7) least & greatest select least (to_date(20-jan-02,to_date(20-dec-02)) from dual; 20-jan-02. select greatest (to_date(20-jan-02,to_date(20-dec02)) from dual; 20-dec-02 Note: greatest means latest. In change the default date format from dd-mon-yy by using Alter session set NLS_Date-Format= <my format> But change is only valid for current session. Conversion Functions 1) TO_CHAR(date,format) Converts a date to a string in the specified format Example: select TO_CHAR(sysdate, Month DD, YYYY) from dual; April 01 2007 Note:to_char(<date>,dd-mon-yy) like %jun% evaluates to true if date is in june. 2) TO_CHAR(number,format) Converts a number to a string in the specified format

Example: select TO_CHAR(17145,$099,999) from dual; $017,145 3) TO_DATE(string,format) Converts a string to a date using the specified format Note: Oracle automatically converts dates in the standard format of DD-MON-YYYY. Example: select TO_DATE(01-02-1999, DD-MM-YYYY) from dual; 01-02-1999 Select to_date(11051946,mmddyyyy) from dual; 11-05-1999 Select to_char (to_date (22-feb-02,day)) from dual;
4)

TO_NUMBER(string, format) select to_number(subtr($100,2,3)) from dual; 100 100 will be in number data type.

Creating Tables The create table statement is used to create a new table. Here is the format of a simple create table statement: create table <table> ( <column 1> <data type> [not null] [unique] [<column constraint>], ......... <column n> <data type> [not null] [unique] [<column constraint>], [<table constraint(s)>] ); For each column, a name and a data type must be specified and the column name must be unique within the table definition. Column

definitions are separated by comma. There is no difference between names in lower case letters and names in upper case letters. Format of create table if you were to use optional constraints: Note: You may have as many columns as you'd like, and the constraints are optional. Example: create table employee (first varchar(15), last varchar(20), age number(3), address varchar(30) ) What are constraints? When tables are created, it is common for one or more columns to have constraints associated with them. A constraint is basically a rule associated with a column that the data entered into that column must follow. The insert statement is used to insert or add a row of data into the table. Strings should be enclosed in single quotes, and numbers should not. Example: insert into emp (first, last, age, address, city, state) values ('Luke', 'Duke', 45, '2130 Boars Nest', 'Hazard Co', 'Georgia'); Note: All strings should be enclosed between single quotes: 'string' 1. Select all columns for everyone in your employee table. 2. Select all columns for everyone with a salary over 30000. 3. Select first and last names for everyone that's under 30 years old. 4. Select first name, last name, and salary for anyone with "Programmer" in their title.

5. Select all columns for everyone whose last name contains "ebe". 6. Select the first name for everyone whose first name equals "Potsy". 7. Select all columns for everyone over 80 years old. 8. Select all columns for everyone whose last name ends in "ith". 1. Select all columns for everyone in your employee table. select * from emp; 2. Select all columns for everyone with a salary over 30000. select * from emp where salary > 30000; 3. Select first and last names for everyone that's under 30 years old. select firstname, lastname from emp where age < 30; 4. Select first name, last name, and salary for anyone with "Programmer" in their title. select firstname, lastname, salary from emp where title LIKE '%Programmer%' ; 5. Select all columns for everyone whose last name contains "ebe". select * from emp where lastname LIKE '%ebe%' 6. Select the first name for everyone whose first name equals "Potsy". select firstname from emp where firstname = 'Potsy'; 7. Select all columns for everyone over 80 years old. select * from emp where age > 80;

8.

Select all columns for everyone whose last name ends in "ith".; select * from emp where lastname LIKE '%ith'

Updating Records The update statement is used to update or change records that match a specified criteria. This is accomplished by carefully constructing a where clause. Examples: The employee JONES is transfered to the department 20 as a manager and his salary is increased by 1000: update EMP set JOB = MANAGER, DEPTNO = 20, SAL = SAL +1000 where ENAME = JONES; All employees working in the departments 10 and 30 get a 15% salary increase. update EMP set SAL = SAL _ 1.15 where DEPTNO in (10,30); Update statement exercises After each update, issue a select statement to verify your changes. 1. Jonie Weber just got married to Bob Williams. She has requested that her last name be updated to Weber-Williams. 2. Dirk Smith's birthday is today, add 1 to his age. 3. All secretaries are now called "Administrative Assistant". Update all titles accordingly. 4. Everyone that's making under 30000 are to receive a 3500 a year raise. 5. Everyone that's making over 33500 are to receive a 4500 a year raise. 6. All "Programmer II" titles are now promoted to "Programmer III".

7. All "Programmer" titles are now promoted to "Programmer II". 1. Jonie Weber just got married to Bob Williams. She has requested that her last name be updated to Weber-Williams. update emp set lastname= 'Weber-Williams' where firstname= 'Jonie' and lastname= 'Weber'; 2. Dirk Smith's birthday is today, add 1 to his age. update emp set age=age+1 where firstname='Dirk' and lastname='Smith'; All secretaries are now called "Administrative Assistant". Update all titles accordingly. update emp set title = 'Administrative Assistant' where title = 'Secretary'; 3. Everyone that's making under 30000 are to receive a 3500 a year raise. update emp set salary = salary + 3500 where salary < 30000; 4. Everyone that's making over 33500 are to receive a 4500 a year raise. update emp set salary = salary + 4500 where salary > 33500; 5. All "Programmer II" titles are now promoted to "Programmer III". update emp set title = 'Programmer III' where title = 'Programmer II'

6. All "Programmer" titles are now promoted to "Programmer II". update emp set title = 'Programmer II' where title = 'Programmer' Deleting Records The delete statement is used to delete records or rows from the table. Examples: delete from employee; Note: if you leave off the where clause, all records will be deleted! delete from employee where lastname = 'May'; delete from employee where firstname = 'Mike' or firstname = 'Eric'; To delete an entire record/row from a table, enter "delete from" followed by the table name, followed by the where clause which contains the conditions to delete. If you leave off the where clause, all records will be deleted. Drop a Table Drop table command drops the complete table (both data and structure). Eg:Drop table emp;

Truncate:-

Truncate table command empties the table completely.. Truncate operation actually drop and recreate a table.So the structure of the table will still remain. Eg:- truncate table emp. GROUP BY clause Group by clause groups ros based on distinct values based on distict values that eist for specified columns.The group by clause creates a dataset containing several set of recors grouped together based on a condition. GROUP BY clause syntax: SELECT <column1>,<column2>,aggregate_function(<expression>) FROM table where <condition> GROUP BY <column-list>; Let's say you would like to retrieve a list of the highest paid salaries in each dept: SELECT max(salary), dept FROM employee GROUP BY dept; This statement will select the maximum salary for the people in each unique department. Basically, the salary for the person who makes the most in each department will be displayed. Their, salary and their department will be returned. 1. How many people are in each unique state in the customers table? Select the state and display the number of people in each.

SELECT state, count (state) FROM customers GROUP BY state; 2. From the items_ordered table, select the item, maximum price, and minimum price for each specific item in the table. Hint: The items will need to be broken up into separate groups. SELECT item, max(price), min(price) FROM items_ordered GROUP BY item; 3. How many orders did each customer make? Use the items_ordered table. Select the customerid, number of orders they made, and the sum of their orders. Click the Group By answers link below if you have any problems. SELECT customerid, count(customerid), sum(price) FROM items_ordered GROUP BY customerid;

HAVING clause The HAVING clause can be used along with group by clause which further filters the groups created by group by clause. In other words , which rows should be selected will be based on the conditions you specify. HAVING clause syntax: SELECT <column1>,<column2>,aggregate_function(<expression>) FROM table where <condition> GROUP BY <column-list>; HAVING can best be described by example. Let's say you have an employee table containing the employee's name, department,

salary, and age. If you would like to select the average salary for each employee in each department, you could enter: SELECT dept, avg(salary) FROM employee GROUP BY dept; But, let's say that you want to ONLY calculate & display the average if their salary is over 20000: SELECT dept, avg(salary) FROM employee GROUP BY dept HAVING avg(salary) > 20000; Review Exercises (note: yes, they are similar to the group by exercises, but these contain the HAVING clause requirements 1. How many people are in each unique state in the customers table that have more than one person in the state? Select the state and display the number of how many people are in each if it's greater than 1. SELECT state, count(state) FROM customers GROUP BY state HAVING count(state) > 1; 2. From the items_ordered table, select the item, maximum price, and minimum price for each specific item in the table. Only display the results if the maximum price for one of the items is greater than 190.00. SELECT item, max(price), min(price) FROM items_ordered GROUP BY item HAVING max(price) > 190.00;

3. How many orders did each customer make? Use the items_ordered table. Select the customerid, number of orders they made, and the sum of their orders if they purchased more than 1 item. SELECT customerid, count(customerid), sum(price) FROM items_ordered GROUP BY customerid HAVING count(customerid) > 1;

Click the HAVING exercise answers link below if you have any problems. Combining conditions and Boolean Operators The AND operator can be used to join two or more conditions in the WHERE clause. Both sides of the AND condition must be true in order for the condition to be met and for those rows to be displayed. The OR operator can be used to join two or more conditions in the WHERE clause also. However, either side of the OR operator can be true and the condition will be met - hence, the rows will be displayed. With the OR operator, either side can be true or both sides can be true. For example: 1.SELECT employeeid, firstname, lastname, title, salary FROM employee_info WHERE salary >= 50000.00 AND title = 'Programmer'; 2.SELECT employeeid, firstname, lastname, title, salary FROM employee_info WHERE (salary >= 50000.00) AND (title = 'Programmer');

3.SELECT firstname, lastname, title, salary FROM employee_info WHERE (title = 'Sales') OR (title = 'Programmer'); 1. Select the customerid, order_date, and item from the items_ordered table for all items unless they are 'Snow Shoes' or if they are 'Ear Muffs'. Display the rows as long as they are not either of these two items. SELECT customerid, order_date, item FROM items_ordered WHERE (item <> 'Snow shoes') AND (item <> 'Ear muffs'); 2. Select the item and price of all items that start with the letters 'S', 'P', or 'F'. SELECT item, price FROM items_ordered WHERE (item LIKE 'S%') OR (item LIKE 'P%') OR (item LIKE 'F%');

IN and BETWEEN Conditional Operators The IN conditional operator is really a set membership test operator. That is, it is used to test whether or not a value (stated before the keyword IN) is "in" the list of values provided after the keyword IN. For example: SELECT employeeid, lastname, salary FROM employee_info

WHERE lastname IN ('Hernandez', 'Jones', 'Roberts', 'Ruiz'); You can also use NOT IN to exclude the rows in your list. BETWEEN is used to select data within a range of values.Range coded after between is inclusive. Example:-SELECT employeeid, age, lastname, salary FROM employee_info WHERE age BETWEEN 30 AND 40; You can also use NOT BETWEEN to exclude the values between your range. Mathematical Operators Standard ANSI SQL-92 supports the following first four basic arithmetic operators: + * / % addition subtraction multiplication division modulo returns the absolute value of x returns the sign of input x as -1, 0, or 1 (negative, zero, or positive respectively) modulo - returns the integer remainder of x divided by y (same as x%y) returns the largest integer value that is less than or equal to x returns the smallest integer value that is greater than or equal to x returns the value of x raised to the power of y

ABS(x) SIGN(x) MOD(x,y) FLOOR(x) CEILING(x) or CEIL(x) POWER(x,y)

ROUND(x) ROUND(x,d) SQRT(x) For example:

returns the value of x rounded to the nearest whole integer returns the value of x rounded to the number of decimal places specified by the value d returns the square-root value of x

SELECT round(salary), firstname FROM employee_info 1. Select the item and per unit price for each item in the items_ordered table. Hint: Divide the price by the quantity. select item, sum(price)/sum(quantity) from items_ordered JOINS Table Joins, a must UP till you've been selecting from only one table at a time with your SELECT statement. It is time to introduce you to one of the most beneficial features of SQL & relational database systems - the "Join". To put it simply, the "Join" makes relational database systems "relational". Joins allow you to link data from two or more tables together into a single query result--from one single SELECT statement. Several types of join are there.
1)

Cross join:- creates a Cartesian product of the rows in both tables..It combins every row from left table to every row in the right table.This type of join can be used in situation when it is desirable to select all possible combinations of rows and columns..This kind

of join is usually not preferred as it may run for a very long time and produce a huge result set. Here there will not be any join clause. Eg:-SELECT first_name,lst_name, department_name FROM employees CROSS JOIN departments;
2)

NATURAL JOIN :-The NATURAL JOIN performs a join for all columns with matching names in the two tables. Join criteria is not needed. The names of the join columns must have to be identical in the two tables Eg:- SELECT first_name,lst_name, department_name FROM employees NATURAL JOIN departments;

3)

Inner Join :-. An inner join is one that returns data only when both tables have a row that matches the join conditions. Use the ON clause to specify your join conditions. Eg:- select cname,cno,city from customer inner join loan on customer.custno=loan.custno.

Join order When joining more than two tables, use parentheses to control the join order. The following query joins COURSE and ENROLLMENT first, and then joins the

table named STUDENT to the result: If you omit parentheses, Oracle processes the joins from left to right. SELECT c.course_name, c.period, s.student_name, s.grade FROM ( course c INNER JOIN enrollment e ON c.course_name=e.course_name AND c.period=e.period ) INNER JOIN student s ON e.student_name=s.student_name; The USING clause allows you to specify the joining key . The USING clause is used if several columns share the same name, but you do not wish to join using all of these common columns. The columns listed in the USING clause cannot have any qualifiers in the statement, including the WHERE clause:

4)

Eg:- SELECT d.department_name, l.city FROM departments JOIN locations USING (location_id);
5)

An outer join returns rows for one table, even when there are no matching rows in the other.Outer join are of three types. The LEFT OUTER JOIN returns all the rows from the table on the left side of the join, along with the values from the right hand side, or NULLs if a matching row doesn't exist. The RIGHT OUTER JOIN does the reverse of this. Finally, the FULL OUTER JOIN returns all rows from both tables, filling in any blanks with nulls: The values for which on condition is not satisfied it return null values. Eg:-SELECT d.department_id, e.last_name

FROM departments d LEFT OUTER JOIN employees e ON d.department_id = e.department_id ORDER BY d.department_id; Eg:-SELECT d.department_id, e.last_name FROM departments d RIGHT OUTER JOIN employees e ON d.department_id = e.department_id ORDER BY d.department_id; Eg:-SELECT d.department_id, e.last_name FROM departments d FULL OUTER JOIN employees e ON d.department_id = e.department_id ORDER BY d.department_id; Oracle supports the following shorthand syntax for natural joins: SELECT course_name, period, e.student_name FROM course c NATURAL FULL OUTER JOIN enrollment e; What is a subquery? A subquery is a query within a query. In Oracle, you can create subqueries within your SQL statements. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.

1.WHERE clause Most often, the subquery will be found in the WHERE clause. These subqueries are also called nested subqueries. For example: Limitations: Oracle allows up to 255 levels of subqueries in the WHERE clause. 2.FROM clause A subquery can also be found in the FROM clause. These are called inline views. For example: select suppliers.name, subquery1.total_amt from suppliers, (select supplier_id, Sum(orders.amount) as total_amt from orders group by supplier_id) subquery1, where subquery1.supplier_id = suppliers.supplier_id; Limitations: Oracle allows an unlimited number of subqueries in the FROM clause. 3.SELECT clause A subquery can also be found in the SELECT clause. For example: select tbls.owner, tbls.table_name, (select count(column_name) as total_columns from all_tab_columns cols where cols.owner = tbls.owner

and cols.table_name = tbls.table_name) subquery2 from all_tables tbls;

Correlated subquery:-A subquery becomes correlated when the subquery references a column from a table in the parent query. For each row processed by the parent statement subquery is executed once. Eg:- Select Accno,BranchNo,CurrentBalance From AccMstr Where currentbalance> ( Select avg(currentBalance) from AccMstr where BranchNo=AccMstr.BranchNo) Because SQL is a declarative language, you can write the same query in many forms, each getting the same result but with vastly different execution plans and performance. In this example, we select all books that do not have any sales. Note that this is a non-correlated sub-query, but it could be rewritten in several ways. Select book_key from book where book_key NOT IN (select book_key from sales); There are serious problems with subqueries that may return NULL values. It is a good idea to discourage the use of the NOT IN clause (which invokes a sub-query) and to prefer NOT EXISTS (which invokes a correlated sub-query), since the query returns no rows if any rows returned by the sub-query contain null values.

Select book_key from book where NOT EXISTS (select book_key from sales); Subqueries can often be re-written to use a standard outer join, resulting in faster performance. Select b.book_key from book join sales s on b.book_key = s.book_key and s.book_key IS NULL; b left outer

This execution plan will also be faster by eliminating the sub-query

Das könnte Ihnen auch gefallen