More On SQL
More On SQL
Arithmetic Operators: Oracle allows arithmetic operators to be used while viewing records from a table or while performing Data Manipulation operations such as Insert, Update and Delete. These are + / * ** () Logical Operators: Logical operators that be used in SQL sentence are: The AND Operator: The Oracle engine will process all rows in a table and display the result only when all of the conditions specified using the AND operator are satisfied. Example: 1. Retrieve the contents of the columns product_no, description, profit_percent, sell_price from the table product_master where the values contained in the field profit_percent is between 10 and 20 both inclusive. SELECT product_no, description, profit_percent, sell_price FROM product_master WHERE profit_percent >=10 AND profit_percent <=20; The OR Operator: The Oracle engine will process all rows in a table and display the result only when any of the conditions specified using the OR operators are satisfied. Example: 2. Retrieve client in formation like client_no, name, address, city and pincode for all the clients where the field pincode has the value 2020 OR 4040. SELECT client_no, name, address, city and pincode FROM client_master WHERE (pincode=2020 OR pincode=4040); Addition Subtraction Division Multiplication Exponentiation Enclosed operation
CHAPTER3
ORACLE
The NOT Operator: The Oracle engine will process all rows in a table and display the result only when none of the conditions specified using the NOT operator are satisfied. Example: 3. Retrieve specified client information for the clients who are NOT in Bombay OR Delhi. SELECT clent_no, name,address,city,pincode FROM client_master WHERE NOT (city=Bombay OR city=Dilhi); The oracle engine will not display the rows from the client_master table where the value of the field city is either Bombay OR Delhi Range Searching: In order to select data that is within a range of values, the BETWEEN operator is used. The BETWEEN operator allows the selection of rows that contain values within a specified lower and upper limit. The range coded after the word BETWEEN us inclusive. The lower value must be coded first. The two values in between the range must be linked with the keyword AND. A BETWEEN operator can be used with both character and numeric data types. However, one cannot mix the data types i.e. the lower value of a range of values from a character column and other from a numeric column. Example for the BETWEEN Operator: 1. Retrieve product_no, description, profit_percent, sell_price from the table product_master where the values contained within the field profit_percent is between 10 and 20 both inclusive. SELECT product_no, description, profit_percent, sell_price FROM product-master WHERE profit_percent BETWEEN 10 AND 20; 2. Retrieve product_no, description, profit_percent and sell_price from the table product_master where the values contained within the field profit_percent are not between 10 and 20 both inclusive. SELECT product_no, description, profit_percent, sell_price FROM product_master WHERE profit_percent NOT BETWEEN 10 AND 20; The above select will retrieve all the records from the product_master table except where the profit_percent is in between 10 and 20 (both values inclusive).
ORACLE
Pattern Matching: The use of the LIKE predicate: The comparison operator discussed so far has compared one value, exactly to one other value. Such a precision may not always be desired or necessary. For this purpose Oracle provides a predicate LIKE. The LIKE predicate allows for a comparison of one string value with another string value, which is not identical. This is achieved by using wildcard characters. Two wildcard characters that are available are: For character data types: The percent sign (%) matches any string The Underscore (_) matches any single character Example: 1. Retrieve all information about suppliers whose names begin with the ja from supplier_master. SELECT * FROM supplier_master WHERE supplier_name LIKE ja; 2. Retrieve all information about suppliers where the second character of names is either r or h SELECT * FROM supplier_master WHERE supplier_name LIKE _r% OR supplier_name LIKE _h%; 3. Retrieve the supplier_name, address, city and pincode from the table supplier_master where the supplier_name is 3 charecters long and the first two characters are ja. SELECT supplier_name, address, city, pincode FROM supplier_master WHERE supplier_name LIKE ja; The IN and NOT IN predicates: The arithmetic operator (=) compares a single value to another single value. In case a value needs to be compared to a list of values then the IN predicate is used. One can check a single value against multiple values by using the IN predicate.
ORACLE
Example: 1. Retrieve the supplier_master, address, city and pincode from the table Supplier_master where the supplier_name is either Gajendra or Ravindra or Narendra. SELECT supplier_name, address, city, pincode FROM supplier_master WHERE supplier_name IN(Gajendra,Ravindra,Narendra) The NOT IN predicate is the opposite of the IN predicate. This will select all the rows where values do not match all of the values in the list. Example: SELECT supplier_name, address, city, pincode FROM supplier_master WHERE supplier_name NOT IN(Gajendra,Ravindra,Narendra) In the above example by just changing the predicate to NOT IN the select statement will now retrieve all the rows from the suppier_master table where supplier_name is not equal to the ones supplied. In other words, information about supplier whose names are not Gajendra, Ravindra, Narendra will be displayed. The Oracle Table DUAL: Dual is a small Oracle worktable, which consists of only one row and one column, and contains the value X in that column. Besides arithmetic calculations, it also supports date retrieval and its formatting. When an arithmetic exercise is to be performed such as 2*2 or 4/2 etc, there really is no table being referenced; only numeric literals are being used. To facilitate such calculations via a SELECT, oracle provides a dummy table called DUAL, against which SELECT statements that are required to manipulate numeric literals can be fired, and output obtained. Example: SQL> SELECT 2*2 FROM dual; Output: 2*2 ---------4 The current date can be obtained from the table DUAL in the required format as shown below. Example: SQL> SELECT sysdate FROM dual; Output: SYSDATE -------------12-DEC-09
MIN
MAX
SUM
ORACLE
COUNT (expr) Syntax Purpose Example Output COUNT (*) Syntax Purpose Example Output COUNT ([DISTINCT|ALL] expr) Returns the number of rows where expr is not null. SELECT COUNT (product_no) No of products FROM product_master; No of products -------------------9 COUNT(*) Returns the number of rows in the table, Including duplicates and those with nulls. SELECT COUNT(*) Total FROM client_master; Total --------14
Single Row function:1.Numeric Functions:ABS Syntax Purpose Example Output ABS (n) Returns the absolute value of n. SELECT ABS (-15)Absolute FROM dual; Absolute ------------15 POWER (m,n) Returns m raised to nth power. n must be an integer. SELECT POWER (3,2)Raised FROM dual; Raised ------------9 ROUND (n[,M]) Returns n, rounded to m places right of the decimal Point. If m is omitted, n is rounded to 0 places. m can be negative to round off digits left of the decimal point. m must be an integer. an integer. SELECT ROUND (15.19,1)Round FROM dual; Round ------------15.2
Example Output
ORACLE
SQRT Syntax Purpose Example Output String Functions:LOWER Syntax Purpose Example Output LOWER (char) Returns char, with all letters in lower case. SELECT LOWER(GAJENDRA)Lower FROM dual; Lower ----------------gajendra UPPER (char) Returns char, with all letters in upper case. SELECT UPPER(gajendra)Upper FROM dual; Upper ----------------GAJENDRA INITCAP (char) Returns string with all first letters in upper case. SELECT LOWER(GAJENDRA)Initcap FROM dual; Initcap ------------Gajendra SUBSTR (char,m[,n]) Returns a portion of char, beginning at character m, exceeding up to n characters. If n is omitted, result is returned up to the end char. The first position of char is 1. SELECT SUBSTR(GAJENDRA2,7)Substring FROM dual; Substring --------------AJENDR SQRT (n) Returns square root of n. If n<0, NULL. SQRT returns a real result. SELECT SQRT(25)Square Root FROM dual; Square Root ----------------5
UPPER
Example Output
ORACLE
LENGTH Syntax Purpose Example Output LENGTH (char) Returns the length of char. SELECT LENGTH(GAJENDRA)Length FROM dual; Length -----------8 LTRIM (char[,set]) Removes characters from the left of char with initial characters removed upto the first character not in set. SELECT LTRIM(GAJENDRA,G)Ltrim FROM dual; Ltrim ------------AJENDRA RTRIM (char[,set]) Removes char, with final characters removed after the last character not in the set. set is optional, it defaults to spaces. SELECT RTRIM(GAJENDRA,A)Rtrim FROM dual; Rtrim ------------GAJENDR LPAD (char1,n [,char2]) Returns char1, left padded to length n with the Sequence of characters in char2, char2 defaults to blanks. SELECT LPAD(GAJENDRA,10,*)Lpad FROM dual; Lpad ------------**GAJENDRA RPAD (char1,n [,char2]) Returns char1, right- padded to length n with the characters in char2, replicated as many times as necessary. If char2 is omitted, right-paded is with blanks. SELECT RPAD(GAJENDRA,10,#)Rpad FROM dual; Rpad -------------------GAJENDRA##
LTRIM
RTRIM
LPAD
RPAD
Syntax Purpose
Example Output
ORACLE
Conversion Functions:TO_NUMBER Syntax Purpose Example TO_NUMBER(char) Convert char, a CHARACTER value containing a number, to a value of NUMBER datatype. UPDATE product_master SET sell_price=sell_price+ TO_NUMBER (SUBSTR($100,2,3)); TO_CHAR (n [,fmt]) Convert a value of NUMBER datatype to a value of CHAR datatype, using the optional format string. It accepts a number (n) and a numeric format (fmt) in which the number has to appear. If fmt is omitted, n is converted to a char value exactly long enough to hold significant digits. SELECT TO_CHAR (17145,$099,999) char FROM dual; Char ------------$017,145 TO_CHAR (date [,fmt]) Convert a value of DATE datatype to CHAR value. It accepts a date (date), as well as the format (fmt) in which the date has to appear. fmt must be a date format. It fmt is omitted; date is converted to a charcter value in the default date format, i.e. DD-MM-YY. SELECT TO_CHAR (order_date, Month DD,YYYY) New Date Format FROM sales_order WHERE order_no=04254; New Date Format -----------------------January 28, 2009
TO_CHAR
Syntax Purpose
Example Output
TO_CHAR
Syntax Purpose
Example
Output
ORACLE
Date Functions:To manipulate and extract values from the date column of a table some date functions have been provided by Oracle. These are discussed below: ADD_MONTHS Syntax Purpose Example Output ADD_MONTHS (d,n) Returns date after adding the number of months specified with the function. SELECT ADD_MONTHS(SYSDAYE,4) FROM dual; ADD_MONTHS --------------------13-OCT-09 LAST_DAY (d) Returns the last date of the month Specified with the function. SELECT LAST_DAY (SYSDAYE)LAST FROM dual;
LAST_DAY
Output
SYSDATE LAST --------------- --------------13-OCT-09 31-OCT-09 Syntax Purpose Example MONTHS_BETWEEN (d1,d2) Returns number of months between d1 and d2. SELECT MONTHS_BETWEEN (02-FEB-09, 02-JAN-09)MONTHS FROM dual; MONTHS --------------1 NEXT_DAY (date,char) Returns the date of the first weekday name by char that is after the date named by date. char must be a day of the week SELECT NEXT_DAY (04-FEB-9,FRIDAY) NEXT DAY FROM dual;
MONTHS_ BETWEEN
Output
NEXT_DAY
Syntax Purpose
Example
Output
10
11
ORACLE
The UNIQUE Constraint:Unique Key concepts: The purposes of a unique key are to ensure that information in the column(s) is unique, i.e. a value entered in column(s) defined in the unique constraint must not be repeated across the column(s). A table may have unique keys. UNIQUE constraint defined at the column level:Syntax: Columnname datatype(size) UNIQUE Example: Create a table client_master such that the contents of the column client_no are unique across the entire column. CREATE TABLR client_master (client_no varchar2 (6) UNIQUE, name varchar2 (20), address varchar2(30)); UNIQUE constraint defined at the table level:Syntax: UNIQUE (Columnname [, columnname, ..]) Example: Create a table client_master such that the unique constraint on the column client_no is described as a table level constraint. CREATE TABLE client_master (client_no varchar2 (6), name varchar2(20) , address varchar2(20) UNIQUE (client_no)); The PRIMARY KEY Constraint:Primary Key concepts: A primary key is one or more column(s) in a table used to uniquely identify each row in the table. A primary key column in a table has special attributes: It defines the column as a mandatory (give order) column i.e. the column cannot be left blank. The NOT NULL attribute is active. The data held across the column MUST be UNIQUE. A single column primary key is called a Simple key. A multicolumn primary key is called a Composite primary key. The only function of a primary key in a table is to uniquely identify a row.
12
ORACLE
PRIMARY KEY constraint defined at the column level: Syntax: Columnname datatype(size) PRIMARY KEY Example: Create a table sales_order where the column order_no is its primary key. Since this is a simple key, define the constraint at column level. CREATE TABLE sales_order (order_no varchar2 (6) PRIMARY KEY, oder_date date, client_no varchar2 (20), address varchar2 (20)); PRIMARY KEY constraint defined at the table level: Syntax: PRIMARY KEY (columnname [, columnname,..]) Example: Create a table sales_order_details where there is a composite primary key on the column detlorder_no and product_no. since the constraint spans across columns, describe it at table level. CREATE TABLE sales_order_details ( detlorder_no varchar2(8), product_no varchar2(6), Qty_ordered number(8), product_rate number(8,2), PRIMARY KEY ( detlorder_no, product_no)); The FOREIGN KEY Constraint: Foreign Key concept: Foreign keys represent relationships between tables. A foreign key is a column (or a group of columns) whose values are derived from the primary key or unique key of some other table. The table in which the foreign key is defined is called a Foreign table or Detail table. The table that defines the primary or unique key and is referenced by the foreign key is called the Primary table or Master table. Principle of Foreign Key / References constraint: Rejects an INSERT or UPDATE of a value, if a corresponding value does not currently exit in the master key table. Rejects a DELETE for the master table if corresponding records in the DETAIL table exist. Must reference a PRIMARY KEY or UNIQUE column(s) in primary table. Will automatically reference the PRIMARY KEY of the MASTER table if no column or group of columns is specified when creating the FOREIGN KEY. Requires that the FOREIGN KEY column(s) and the CONSTRAINT column(s) have matching data types. May reference the same table named in the CREATE TABLE statement.
13
ORACLE
FOREIGN KEY constraint defined at the column level: Syntax: Columnname datatype(size) REFERENCES tablename [(columnname)] [NO DELETE CASCADE] Example: Create a table sales_order_details table with its primary key as detlorder_no and product_no. The foreign key is detlorder_no, referencing column order_no in the sales_order table. CREATE TABLE sales_order_details (detlorder_no varchar2(8) REFERENCES sales_order, product_no varchar2(6), qty_ordered number(6), product_rate number(6,2), PRIMARY KEY (detlorder_no, product_no)); The REFERENCE key word points to the table sales_order. The table sales_order has the column order_no as its primary key column. Since no column is specifed in the foreign key definition, Oracle applies an automatic link to the primary key column i.e. order_no of the table sales_order. FOREIGN KEY constraint defined at the table level: Syntax: FOREIGN KEY (Columnname [,columnname]) REFERENCES tablename [(columnname [,columnname]) Example: Create table sales_order_details with the primary key as detlorder_no and product_no and foreign key at table level as detlorder_no referencing column order_no in the sales_order table. CREATE TABLE sales_order_details (detlorder_no varchar2(6), product_no varchar2(7), qty_ordered number(7), product_rate number(5) PRIMARY KEY (detlorder_no, product_no), FOREIGN KEY (detlorder_no) REFERENCE sales_order); Assigning User Defined Names to Constraints: Constraints can be given a unique user-defined name along with the constraint definition. A constraint can be dropped by referring to the constraint by its name. Under these circumstances a user defined constraint name becomes very convenient. if Oracle generated names are to be used, it becomes difficult to search for and identify the required constraint to be dropped. Hence, user named constraints simplifies the task of dropping constraints. A constraint can be given a user-defined name by preceding the constraint definition with the reserve word CONSTRAINT and a user-defined name.
14
ORACLE
Syntax: CONSTRAINT <constraintname><constraint definition> Example: 1. Create a table client_master with a primary key constraint on the column client_no. The constraint name must be p_clientkey. CREATE TABLE client-master (client_no varchar2(6), CONSTRAINT p_clientkey PRIMARY KEY, name varchar2(20), address varchar2(20), city varchar2(20)); 2. Create a table sales_order_details with a table-level foreign key as detlorder_no referencing column order_no in the sales_order table. The constraint name must be f_orderkey. CREATE TABLE sales_order_details (detlorder_no varchar2(7), product_no varchar2(4), qty_order number(8), product_rate number(7,2) CONSTRAINT f_orderkey FOREIGN KEY (detlorder_no) REFERENCES sales_order); 2. Business rule Constraint Oracle allows the application of business rule to table columns. Business managers determine business rule. These rules applied to data being inserted into table columns. Business rules can be implemented in Oracle by using CHECK constraints. Constraints can be connected to a column or a table by the CREATE TABLE or ALTER TABLE command. The CHECK Constraint: Business Rule validation can be applied to a table column by using CHECK constraint. CHECK constraints must be specified as a logical expression that evaluates either to TRUE or FALSE. CHECK constraint defined at the columnlevel: Syntax: Columnname datatype (size) CHECK (logical expression) Example: Create a table client_master with the following check constraints: Data vales being inserted into the column client_no must start with the capital letter C. Data values being inserted into the column name should be in upper case only. Only allow Bombay, Delhi,Madras and Calcutta as legitimate values for the column city.
15
ORACLE
CREATE TABLE client_master ( client_no. varchar2(6) CHECK (client_no like C%), name varchar2(20) CHECK (name = upper(name)), address1 varchar2 (30), address2 varchar2 (30), city varchar2(15) CHECK (city IN (Delhi, Bombay, Calcutta, Madras)), state varchar2(15), pincode number(6); CHECK constraint defined at the table level: Syntax: CHECK (logical expression) Example: CREATE TABLE client_master ( client_no varchar2(6), name varchar2(20), address1 varcha2(30), address2 varchar2(30), city varchar2(15), state vatrchar2(15), pincode number(6), CHECK (client_no like C %) CHECK (name= upper (name)), CHECK (city IN (Delhi, Bombay, Calcutta, Madras)); Restrictions on CHEK Constraints: A CHECK integrity constraint requires that a condition be true or unknown for the row to be processed. If an SQL statement causes the condition to evaluate to false, an appropriate error message is displayed and processing stops. A CHECK constraint has the following limitations: The condition must be a Boolean expression that can be evaluated using the values in the row being inserted or updated. The condition cannot contain subqueries or sequences. The condition cannot include the SYSDATE, UID, USER or USERENV SQL functions.
16
ORACLE
2. Add FOREIGN KEY constraint on the column order_no belonging to the table sales_order_details, which references the table sales_order. Modify column qty_ordered to include the NOT NULL constraint. ALTER TABLE sales_order_details ADD CONSTRAINT order_key FOREIGN KEY (detlorder_no) REFRENCES sales_order MODIFY (qty_ordered number(8) NOT NULL);
17
ORACLE
Syntax: Columnname data type (size) DEFAULT (value); Example: Create a sales_order table where the default valye for the column dely_type is the character, upper case F.
CEREATE TABLE sales_order (order_no varchar2(6) PRIMARY KEY, order_date date, dely_type char(1) DEFAULT F, dely_date date); Note: The data type of the degault value should match the data type of the column. Character and date values will be specified in single quotes. If a column level constraint is defined on the column with a default value, the default value clause must precede the constraint definition. Thus the syntax will be: Columnname datatype(size) DEFAULT value constraint definition
18
ORACLE
Qty Ordered 10 3 7 4 8 2 2
Qty Disp 10 3 7 4 8 2 2
SELECT product_no, sum(qty_order)Total Quantity FROM sales_order_details GROUP BY product_no; Output: Product No --------------P0001 P0002 P0003 P0004 Total Quantity -------------------17 4 5 10
In the above example, the common rows in the column product_no are grouped together and the total quality ordered for each product is displayed on screen.
19
ORACLE
HAVING Clause: The HAVING clause can be used in conjunction with GROUP BY clause. HAVING imposes a condition on the group by clause, which further filters the groups created by the group by clause. Example: Retrieve the product no and the total quantity ordered for products P0001, P0004 from the sales_order_datails. SELECT product_no, sum(qty_ordered) Total Quantity FROM sales_order_datails GROUP BY product_no HAVING product_no=P0001 OR product_no=P0004; Output: Product No --------------P0001 P0004 Total Quantity ------------------17 10
In the above example, the common rows in the column product_no are grouped together and the total quantity ordered for only the product numbers specified in the having clause are displayed on screen.
20
ORACLE
TO_DATE: TO_DATE converts a char value into a date value. It allows a user to insert date into a date column in any required format, by specifying the character value of the date to be inserted and its format. Syntax: TO_DATE (char value [, fmt]) Where char value stands for the value to be inserted in the date column, and fmt is a date format in which the char value is specified. Example: TO_DATE (23/12/09, DD/MM/YY); 1. Retrieve order information like order_no, client_no, order_date for all the orders placed by the client in the ascending order of date. The order_date should be displayed in DD/MM/YY format. SELECT order_no, client_no, to_char(Order_date, DD/MM/YY) FROM sales_order ORDER BY to_char(order_date, MM); 2. Insert the following data in the table sales_order, where in the time component has to be stored along with the date in the column order_date. Order No 019100 Client No C00100 Order Date 31/DEC/09 11:32:45
INSERT INTO sales_order (order_no, client_no, ordr_date) VALUES ( 019100, C00100,to_date(31/DEC/09 11:32:45, DD/MON/YY hh:min:ss)); 3. Use of TH in the TO_CHAR function: TH place TH, RD, ND for the date (DD), for example, 2ND, 3RD, 8TH etc SELECT order_no, TO_CHAR (order_date, DDTH-MON-YY) 4. Use of SP IN TO_CHAR function DDSP indicates that the date (DD) must be displayed by spelling the date such as ONE, TWELVE etc. SELECT order_no, TO-CHAR (order_date, DDSP) FROM sales_order;
21
ORACLE SUBQUERIES
A subquery is a form of an SQL statement that appears inside another SQL statement. It is also termed as nested query. The statement containing a subquery is called a parent statement. The parent statement uses the rows returned by the subquery. It can be used by the following commands: To insert records in a target table. To create tables and insert records in the table created. To update records in a target table. To create views. To provide values for conditions in WHERE, HAVING,IN etc. used with SELECT. UPDATE, and DELETE statements. Example: 1. Retrieve all orders placed a client named Rahul Dhole from the sales_order table. Table name: sales_order Order_no 019001 019002 019003 019004 Table name: client_master Client _no C0006 C0002 C0001 C0005 Name Ajay Mehta Rohit Roy Prem Iyer Rahul Dhole Bal_Due 1000 00 00 1500 Client _no C0005 C0002 C0005 C0003 Order_ Date 12-Apr-08 25-Dec-08 03-Oct-09 20-Aug-09
SELECT * FROM sales_Order WHERE client_no= (SELECT client_no FROM client_master WHERE name= Rahul Dhole); Output: Order_no Client_no Order_Date
22
ORACLE
------------019001 019003 ------------C0005 C0005 ---------------12-Apr-08 03-Oct-09
Output of the Union Clause Example: Retrieve the names of all the clients and salesman in the city of Mumbai from the client_master and salesman_master. Table name: client_master Client_no C0001 C0002 C0003 C0004 C0005 Name GAJENDRA RAJENDRA NARENDRA RAVINDRA MAHENDRA City Mumbai Delhi Mumbai Calcutta Delhi
23
ORACLE
SELECT client_no ID, name FROM client_master WHERE city=Mumbai; Oracle executes the queries as follows: SELECT salesman_no ID, name FROM salesman_master WHERE city=Mumbai; The target table will be as follows: ID C0001 C0003 Then, SELECT client_no ID, name FROM client_master WHERE city=Mumbai; The target table will be as follows: ID S0001 S0004 Name GAJU SANJU Name GAJENDRA NARENDRA
The UNION clause picks up the common records as well as the individual records in both queries. Thus, the output after applying the UNION clause will be: Output: ID ---------------C0001 C0003 S0001 S0004 NAME -------------GAJENDRA NARENDRA GAJU SANJU
The Restrictions on using a union are as follows: Number of columns in all the queries should be the same. The datatype of the columns in each query must be same. Unions cannot be used in subqueries. Aggregate functions cannot be used with union clause.
24
ORACLE
INTERSECT Clause: Multiple queries can be put together and their output combined using the intersect clause. The intersect clause outputs only rows produced by both the queries intersected i.e. the output in an intersect clause will include only those rows that are retrieved by both the queries.
Output of the Intersect Clause Example: Retrieve the salesman name in Mumbai whose efforts have resulted into atleast one sales transaction. Table name: salesman_master Salesman_no S0001 S0002 S0003 S0004 Table name: sales_order Order_no 019001 019002 019003 019004 Salesman _no S0005 S0002 S0005 S0003 Order_ Date 12-Apr-08 25-Dec-08 03-Oct-09 20-Aug-09 Name GAJU RAJU VIJU SANJU City Mumbai Delhi Calcutta Mumbai
25
ORACLE
SELECT salesman_no, name FROM salesman_master WHERE city=Mumbai INTERSECT SELECT salesman_master.salesman_no, name FROM salesman_master, sales_order WHERE salesman_master.salesman_no=sales_order.salesman_no
The first query in the INTERSECT example is as follows: SELECT salesman_no, name FROM salesman_master WHERE city=Mumbai; The target table will be as follows: Salesman_no S0001 S0004 Name GAJU SANJU
The second query in the INTERSECT example is as follows: SELECT salesman_master.salesman_no, name FROM salesman_master, sales_order WHERE salesman_master.salesman_no=sales_order.salesman_no;
The INTERSECT clause picks up records that are common in both queries. Thus, the output after applying the INTERSECT clause will be: Output: Salesman_no ------------------S0001 S0004 Name ----------GAJU SANJU
26
ORACLE
MINUS Clause: Multiple queries can be put together and their output combined using the minus clause. The Minus clause outputs the rows produced by the first query, after filtering the rows retrieved by the second query.
Output of the Minus Clause Example: Retrieve all the product product_master table. numbers of non-moving items from the
Table name: sales_Order_details Order No 019001 019001 019001 019002 019002 019003 019004 Product No P0001 P0004 P0006 P0002 P0005 P0003 P0001
27
ORACLE
P0001 P0002 P0003 P0004 P0005 P0006 P0007 P0008 1.44 Floppies Monitors Mouse CD Drive HDD Keyboards 1.22 Floppies 1.44 Floppies
SELECT product_no FROM product_master MINUS SELECT product_no FROM sales_order_details; The first query in the MINUS example is as follows: SELECT product_no FROM product_master; The target table will be as follows: Product No P0001 P0002 P0003 P0004 P0005 P0006 P0007 P0008 The first query in the MINUS example is as follows: SELECT product_no FROM sales_order_details; The target table will be as follows: Product No P0001 P0004 P0006 P0002 P0005 P0003 P0001
28
ORACLE
The MINUS clause picks up records in first query after filtering the records retrieved by the second query. Thus, the output after applying the MINUS clause will be: Output: Product No --------------P0007 P0008
29