by Sandeep Desai (http://www.thedesai.net)
Book: Mastering
Oracle SQL by Sanjay Mishra and Alan Beaulieu
INSERT ALL
INTO table1 (col1, col2)
VALUES (1, 2)
INTO table1 (col1, col2)
VALUES (3, 4)
INTO table2 (tcol1, tcol2)
VALUES (3, 4)
Insert rows returned by SELECT into different tables depending on WHEN condition
INSERT FIRST
WHEN condition1
INTO table1 (col1,...) VALUES (...)
WHEN condition2
INTO table2 (col1,...) VALUES (...)
SELECT ... FROM .. WHERE ...
MERGE allows you to insert new row or update existing row. (useful in Data Warehousing)
MERGE INTO table1dest
USING table2 src
ON (table1.key = table2.key)
WHEN MATCHED THEN UPDATE
SET src.col1 = dest.col1
WHEN NOT MATCHED THEN INSERT (...) VALUES (...)
WHERE REGEXP_LIKE(phone, “^781”)
WHERE mgr_empid IS NULL OR mgr_empid != 1234
WHERE NVL(mgr_empid, -999) != 1234 – NVL replace NULL with –999
-- ANSI JOIN
SELECT ...
FROM part p INNER JOIN supplier s
ON s.supplier_id = p.supplier_id
WHERE ....
Types of Joins
View that have a key preserved tables can be updated (insert, update and delete) where row deleted depends on order of join
USER_UPDATABLE_COLUMNS dictionary view describes which columns are updatable
Create View with check option prevent delete that will remove rows from view
COUNT(*) counts null
AVG(SALES) does not count null columns
AVG(NVL(SALES,0)) counts null
SELECT SUBSTR(lname, 1, 1), AVG(sales)
FROM emp
GROUP BY lname
HAVING AVG(sales) < 5000 – column referenced should be in select or group by
SELECT MAX(SUM(salary) FROM employee GROUP BY emp_id – nested group operations
ORDER BY foo NULLS FIRST
ORDER BY foo NULLS LAST
Inline views are executed prior to the containing query, inline views must be noncorrelated.
SELECT sizes.name order_size, SUM(co.sales_price) tot_dollars FROM cust_order co INNER JOIN
(select ‘SMALL’ name, 0 lower_bound, 29 upper_bound FROM DUAL
UNION ALL
select ‘LARGE’ name, 30 lower_bound, 79 upper_bound FROM DUAL
) sizes
ON co.saes_price BETWEEN sizes.lower_bound AND sizes.upper_bound WHERE ...
GROUP BY sizes.name
ORDER BY sizes.name DESC
Query cannot be joined
Will print tree depth first
SELECT child_id, name parent_id FROM hier START WITH name = ‘World’ CONNECT BY PRIOR child_id = parent_id
SELECT salesperson_id, SUM(tot_sales) tot_sales, RANK() OVER (ORDER BY SUM(tot_sales) DESC) sales_rank
FROM orders WHERE ... GROUP BY salesperson_id
ALTER SESSION SET TIME_ZONE = ‘EST’;
Temporal Data Types
Links