Beruflich Dokumente
Kultur Dokumente
org
https://www.1keydata.com
The following sections present a variety of examples illustrating the uses of conditional logic in SQL
statements. Although we recommend that you use the CASE expression rather than the DECODE
function, where feasible we provide both DECODE and CASE versions of each example to help
illustrate the differences between the two approaches.
SUM(sale_price) tot_sales
FROM cust_order
ORDER BY 2 DESC;
DAY_OF_WEEK TOT_SALES
------------ ----------
SUNDAY 396
WEDNESDAY 180
MONDAY 112
FRIDAY 50
SATURDAY 50
In order to transform this result set into a single row with seven columns (one for each day in the
week), you will need to fabricate a column for each day of the week and, within each column, sum
only those records whose order date falls in the desired day. You can do that with DECODE:
SELECT
FROM cust_order
Each of the seven columns in the previous query are identical, except for the day being checked by
the DECODE function. For the SUN column, for example, a value of 0 is returned unless an order
was booked on a Sunday, in which case the sale_price column is returned. When the values from
all orders are summed, only Sunday orders are added to the total, which has the effect of summing
all Sunday orders while ignoring orders for all other days of the week. The same logic is used for
Monday, Tuesday, etc., to sum orders for each of the other days.
The CASE version of this query is as follows:
SELECT
FROM cust_order
Obviously, such transformations are only practical when the number of values is relatively small.
Aggregating sales for each weekday or month works fine, but expanding the query to aggregate
sales for each week, with a column for each week, would quickly become tedious.
my_pkg.get_resupply_date(p.part_nbr) acme_resupply_date
FROM part p INNER JOIN supplier s
ON p.supplier_id = s.supplier_id;
You then include logic in your reporting tool to use the acme_resupply_date instead of
the resupply_date column if the supplier's name is Acme Industries. You kick off the report, sit
back, and wait for the results. And wait. And wait...
Unfortunately, the server is forced to make 10,000 trips across the gateway when only 100 are
required. In these types of situations, it is far more efficient to call the function only when necessary,
instead of always calling the function and discarding the results when not needed:
p.inventory_qty in_stock,
my_pkg.get_resupply_date(p.part_nbr),
p.resupply_date) resupply_date
ON p.supplier_id = s.supplier_id;
The DECODE function checks if the supplier name is 'Acme Industries'. If so, it calls the function
to retrieve the resupply date via the gateway; otherwise, it returns the resupply date from the local
part table. The CASE version of this query looks as follows:
p.inventory_qty in_stock,
ELSE p.resupply_date
END resupply_date
ON p.supplier_id = s.supplier_id;
Now the user-defined function is only executed if the supplier is Acme, reducing the query's
execution time drastically. For more information on calling user-defined functions from SQL, see
Chapter 11.
Given that columns such as inventory_qty and resupply_date are unlikely to be indexed, each
of the four UPDATE statements would require a full table-scan of the part table. By adding
conditional expressions to the statement, however, the four UPDATE statements can be combined,
resulting in a single scan of the part table:
DECODE(inventory_qty, 0,
'ENROUTE', 'BACKORD')),
'INSTOCK');
The readability advantage of the CASE expression is especially apparent here, since the DECODE
version requires three nested levels to implement the same conditional logic handled by a single
CASE expression.
describe mtd_orders;
Each night, the table is updated with that day's order information. While most of the columns will be
modified each night, the column for the largest order, which is called max_sale_price, will only
change if one of the day's orders exceeds the current value of the column. The following PL/SQL
block shows how this might be accomplished using a procedural language:
DECLARE
tot_ord NUMBER;
tot_price NUMBER;
max_price NUMBER;
prev_max_price NUMBER;
BEGIN
FROM cust_order
UPDATE mtd_orders
END IF;
END;
After calculating the total number of orders, the aggregate order price, and the maximum order price
for the current day, the tot_orders and tot_sale_price columns of the mtd_orders table are
modified with today's sales data. After the update is complete, the maximum sale price is returned
from mtd_orders so that it can be compared with today's maximum sale price. If
today's max_sale_price exceeds that stored in the mtd_orders table, a second UPDATE
statement is executed to update the field.
Using DECODE or CASE, however, you can update
the tot_orders and tot_sale_price columns and optionally update the max_sale_pricecolumn
in the same UPDATE statement. Additionally, since you now have a single UPDATE statement, you
can aggregate the data from thecust_order table within a subquery and eliminate the need for
PL/SQL:
DECODE(GREATEST(mtdo.max_sale_price,
mtdo.max_sale_price, day_tot.max_sale_price)
FROM
MAX(sale_price) max_sale_price
FROM cust_order
In this statement, the max_sale_price column is set equal to itself unless the value returned from
the subquery is greater than the current column value, in which case the column is set to the value
returned from the subquery. The next statement uses CASE to perform the same optional update:
mtdo.tot_sale_price + day_tot.tot_sale_price,
CASE WHEN day_tot.max_sale_price > mtdo.max_sale_price
THEN day_tot.max_sale_price
FROM
MAX(sale_price) max_sale_price
FROM cust_order
One thing to keep in mind when using this approach is that setting a value equal to itself is still seen
as a modification by the database and may trigger an audit record, a new value for
the last_modified_date column, etc.
/* Europe buckets */
THEN eur_day_tot.max_sale_price
FROM
MAX(co.sale_price) max_sale_price
ON co.cust_nbr = c.cust_nbr
AND c.region_id IN
mtdo.northamerica_max_sale_price) =
THEN na_day_tot.max_sale_price
FROM
MAX(co.sale_price) max_sale_price
ON co.cust_nbr = c.cust_nbr
AND c.region_id IN
However, why not save yourself a trip through the cust_order table and aggregate the North
American and European totals at the same time? The trick here is to put conditional logic within the
aggregation functions so that only the appropriate rows influence each calculation. This approach is
similar to the example from Section 9.3.1. in that it selectively aggregates data based on data stored
in the table:
mtdo.northamerica_max_sale_price, mtdo.europe_tot_orders,
mtdo.europe_tot_sale_price, mtdo.europe_max_sale_price) =
THEN day_tot.na_max_sale_price
THEN day_tot.eur_max_sale_price
FROM
ON co.cust_nbr = c.cust_nbr
ON c.region_id = na_regions.region_id
ON c.region_id = eur_regions.region_id
This is a fairly robust statement, so let's break it down. Within the day_tot inline view, you are
joining the cust_order table to the customer table, and then outer-joining
from customer.region_id to each of two inline views (na_regions and eur_regions) that
perform hierarchical queries on the region table. Thus, orders from European customers will have a
non-null value for eur_regions.region_id, since the outer join would find a matching row in
the eur_regions inline view. Six aggregations are performed on this result set; three check for a
join against the na_regions inline view (North American orders), and three check for a join against
the eur_regions inline view (European orders). The six aggregations are then used to modify the
six columns in mtd_orders.
This statement could (and should) be combined with the statement from the previous example
(which updated the first three columns) to create an UPDATE statement that touches every column
in the mtd_orders table via one pass through the cust_order table. For data warehouse
applications, where large data sets must be manipulated each night within tight time constraints,
such an approach can often make the difference between success and failure.
FROM customer c;
CUST_NBR NAME H
---------- ------------------------------ -
1 Cooper Industries Y
2 Emblazon Corp. N
3 Ditech Corp. N
4 Flowtech Inc. Y
5 Gentech Industries Y
6 Spartan Industries N
7 Wallace Labs N
8 Zantech Inc. Y
9 Cardinal Technologies N
10 Flowrite Corp. N
11 Glaven Technologies N
12 Johnson Labs N
13 Kimball Corp. N
14 Madden Industries N
15 Turntech Inc. N
16 Paulson Labs N
19 Kendall-Taylor Corp. N
20 Malden Labs N
22 Nichols Industries N
23 Owens-Baxter Corp. N
25 Worcester Technologies N
26 Alpha Technologies Y
27 Phillips Labs N
28 Jaztech Corp. N
29 Madden-Taylor Inc. N
30 Wallace Industries N
FROM customer c;
DECODE(my_pkg.get_daily_part_usage(p.part_nbr), NULL, 1,
0, 1, my_pkg.get_daily_part_usage(p.part_nbr))) anticipated_shortage_dt
FROM part p
The DECODE function ensures that the divisor is something other than zero. Here is the CASE
version of the statement:
THEN my_pkg.get_daily_part_usage(p.part_nbr)
FROM part p
THEN parts.daily_part_usage
FROM
my_pkg.get_daily_part_usage(p.part_nbr) daily_part_usage
FROM part p
RETURN VARCHAR2 is
BEGIN
SELECT DECODE(status,
'REJECTED', status,
'CANCELLED', status,
'SHIPPED', status,
INTO next_state
FROM cust_order
RETURN next_state;
EXCEPTION
RETURN next_state;
END get_next_order_state;
As of Oracle8i, the PL/SQL language does not include the CASE expression in its grammar, so you
would need to be running Oracle9i or later to use the CASE version of the function:
RETURN VARCHAR2 is
BEGIN
SELECT CASE
WHEN status = 'REJECTED' THEN status
ELSE 'UNKNOWN'
END
INTO next_state
FROM cust_order
WHERE order_nbr = ord_nbr;
RETURN next_state;
EXCEPTION
RETURN next_state;
END get_next_order_state;
This example handles only the simple case in which there are just two paths out of each state, but it
does demonstrate one strategy for managing state transitions in your database. To demonstrate how
the previous function could be used, here is the UPDATE statement used to change the status of an
order once it has made a successful state transition:
UPDATE cust_order
Syntax
The syntax of the DECODE function is:
DECODE ( expression, search, result [, search, result]... [,default] )
Get Your Free PDF: 9 Ways to Improve your Database Skills
Yes, Send Me The PDF
Mark UK (null)
You can see that when the country = ‘USA’, the DECODE_RESULT is ‘North America’,
otherwise it shows NULL.
Example 2
This is an example of the DECODE function with two character searches.
SELECT first_name, country,
DECODE(country, 'USA', 'North America', 'UK', 'Europe') AS Decode_Result
FROM customers;
Result:
FIRST_NAME COUNTRY DECODE_RESULT
Mark UK Europe
Similar to Example 1, this shows different results for USA and UK.
Example 3
This example shows the DECODE function with a default value.
SELECT first_name, country,
DECODE(country, 'USA', 'North America', 'UK', 'Europe', 'Other') AS Decode_Result
FROM customers;
Result:
Mark UK Europe
This is the same query as above, but with a default value. You can see that it shows
Other instead of NULL.
Example 4
This is a DECODE function with many character searches.
SELECT first_name, country,
DECODE(country, 'USA', 'North America', 'Canada', 'North America', 'UK', 'Europe', 'France',
'Europe', 'Other') AS Decode_Result
FROM customers;
Result:
Mark UK Europe
This shows many different results from the DECODE function, as well as the Other for
anything that was not considered.
Example 5
This query performs a DECODE on number values.
SELECT first_name, employees,
DECODE(employees, 1, 'Small') AS Decode_Result
FROM customers;
Result:
John 4 (null)
Sally 10 (null)
Steve 15 (null)
Mark 23 (null)
Adam 55 (null)
Josh 1 Small
As there is only one check being done, there is only one matching result in this table.
Example 6
This uses the Oracle DECODE function with three number searches.
SELECT first_name, employees,
DECODE(employees, 1, 'Small', 10, 'Medium', 50, 'Large', 'Unknown') AS Decode_Result
FROM customers;
Result:
John 4 Unknown
Sally 10 Medium
Steve 15 Unknown
Mark 23 Unknown
Adam 55 Unknown
Josh 1 Small
Notice that only exact matches are found, not a range or a greater than.
Example 7
This example uses the DECODE function with NULL to see how it works.
SELECT first_name, country,
DECODE(country, 'USA', 'North America', NULL, 'No Country') AS Decode_Result
FROM customers;
Result:
Mark UK (null)
You can see that the record with NULL for a country is shown as No Country, and
anything that does not match is shown as NULL.
Example 8
This is an example of using Oracle DECODE in a WHERE clause.
SELECT first_name, country
FROM customers
WHERE DECODE(country, 'USA', 'North America', 'Canada', 'North America', 'UK', 'Europe',
'France', 'Europe', 'Other') = 'North America';
Result:
FIRST_NAME COUNTRY
John USA
Sally USA
Steve Canada
Adam USA
This only shows records where the DECODE function returns ‘North America’.
Example 9
This example uses DECODE to find if a value is contained in another value, similar to
the LIKE function.
SELECT first_name, country,
DECODE(SIGN(INSTR(country, 'U')), 1, 'Found U', 0, 'Did not find U', 'Unsure') AS
Decode_Result
FROM customers;
Result:
Mark UK Found U
This checks for the value of U and displays a message if it finds it or not.
Example 10
This is an example of DECODE with greater than functionality.
SELECT first_name, employees,
DECODE(SIGN(20 - employees), 1, 'Less than 20', -1, 'Greater than 20', 'Unsure') AS
Decode_Result
FROM customers;
Result:
FIRST_NAME EMPLOYEES DECODE_RESULT
As you can see, any record where employees is greater than 20 will show one value,
and less than will show another value.
Example 11
This is an example of using an UPDATE statement with DECODE.
SELECT first_name, last_name, country
FROM customers;
Result:
Mark Allan UK
UPDATE customers
SET last_name = DECODE(country, 'USA', 'American', last_name);
7 rows updated.
SELECT first_name, last_name, country
FROM customers;
Result:
Mark Allan UK
As you can see, those records where country is USA have had their last name updated
to be ‘American’.
Similar Functions
Some functions which are similar to the Oracle DECODE function are:
CASE – A statement that was introduced to replace DECODE. Offers more functionality and
easier readability compared to DECODE.
You can find a full list of Oracle functions here.
Get Your Free PDF: 9 Ways to Improve your Database Skills
Yes, Send Me The PDF
1.
Ravi on July 7, 2018 at 4:33 pm
how to convert the numbers to characters like 1 to ‘positive’ and -1 to ‘negative’ using
functions.
Reply
Ben on July 8, 2018 at 10:19 am
Hi Ravi, you could use the DECODE function in this article. However I
recommend using the CASE function to check number and convert to
‘positive’ if 1 or ‘negative’ if -1. You can use the SIGN function to determine
if a number is positive or negative, or use greater than or less than.
Reply
2.
Ravi on July 8, 2018 at 12:54 pm
Ben on July 9, 2018 at 4:49 am
Try this:
SELECT
CASE WHEN numvalue < 0 THEN 'negative' CASE WHEN numvalue > 0
THEN ‘positive’
ELSE ‘even’
END AS numtest
FROM yourtable;
Reply
Ravi on July 9, 2018 at 2:51 pm
3.
Ravi on July 9, 2018 at 2:49 pm
Hi sir,
I have one table like tester2 val1 val2 val3
A B 10
C D 20
E A 25
B A 10
A E 25
D C 20
E F 25 and output is given below
val1 val2 val3
A B 10
C D 20
A E 25
E F 25
we can use the functions or joins. So,please send the syntax and which function used in
this problem.
Reply
4.
Ravi on July 14, 2018 at 2:38 am
Hi Sir,
I have string like x12abde#_13-89. I want to print out the only ‘xabde’ by using functions
so, give an syntax for this problem
SQL Functions
INSTR
The INSTR function in SQL is used to find the starting location of a pattern in a string. This function is avail
MySQL and Oracle, though they have slightly different syntaxes:
Syntax
MySQL:
Oracle:
Find the starting location of the nth occurrence of pattern beginning in the starting position-th position in str
Examples
Table Geography
Region_Name Store_Name
East Boston
Result:
The first occurrence of 'o' is the second character in the word 'Los Angeles.'
Result:
In this case, the pattern p does not exist in string 'Los Angeles,' so the function returns 0.
SELECT INSTR(Store_Name,'e', 1, 2)
FROM Geography
WHERE Store_Name = 'Los Angeles';
Result:
10
In this case, we are looking for the second occurrence of the character 'e' in the word 'Los Angeles,' and we
the start with the first character of the word.
The function returns 10 as the second occurrence of 'e' is in the 10th position.
Copyright © 2019 1keydata.com All Rights Reserved Privacy Policy About Contact
COALESCE
You can also use COALESCE as a variety of the CASE expression. For example,
is equivalent to:
CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE expr2 END
Similarly,
is equivalent to:
The following example uses the sample oe.product_information table to organize a clearance sale of products. It
gives a 10% discount to all products with a list price. If there is no list price, then the sale price is the minimum price.
If there is no minimum price, then the sale price is "5":
FROM product_information
1769 48 43.2
1770 73 73
3355 5
Joins
A join is a query that combines rows from two or more tables, views, or materialized views. Oracle Database
performs a join whenever multiple tables appear in the FROM clause of the query. The select list of the query can
select any columns from any of these tables. If any two of these tables have a column name in common, then you
must qualify all references to these columns throughout the query with table names to avoid ambiguity.
Join Conditions
Most join queries contain at least one join condition, either in the FROM clause or in the WHERE clause. The join condition
compares two columns, each from a different table. To execute a join, Oracle Database combines pairs of rows, each containing
one row from each table, for which the join condition evaluates to TRUE. The columns in the join conditions need not also appear
in the select list.
To execute a join of three or more tables, Oracle first joins two of the tables based on the join conditions comparing their
columns and then joins the result to another table based on join conditions containing columns of the joined tables and the new
table. Oracle continues this process until all tables are joined into the result. The optimizer determines the order in which Oracle
joins tables based on the join conditions, indexes on the tables, and, any available statistics for the tables.
IA WHERE clause that contains a join condition can also contain other conditions that refer to columns of only one table. These
conditions can further restrict the rows returned by the join query.
Note:
You cannot specify LOB columns in the WHERE clause if the WHERE clause contains the join condition. The use of LOBs
in WHERE clauses is also subject to other restrictions. See Oracle Database SecureFiles and Large Objects
Developer's Guide for more information.
Equijoins
An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that have equivalent
values for the specified columns. Depending on the internal algorithm the optimizer chooses to execute the join, the total size of
the columns in the equijoin condition in a single table may be limited to the size of a data block minus some overhead. The size
of a data block is specified by the initialization parameter DB_BLOCK_SIZE.
See Also:
"Using Join Queries: Examples"
Self Joins
A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify
column names in the join condition. To perform a self join, Oracle Database combines and returns rows of the table that satisfy
the join condition.
See Also:
"Using Self Joins: Example"
Cartesian Products
If two tables in a join query have no join condition, then Oracle Database returns their Cartesian product. Oracle combines each
row of one table with each row of the other. A Cartesian product always generates many rows and is rarely useful. For example,
the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include a join condition unless you specifically
need a Cartesian product. If a query joins three or more tables and you do not specify a join condition for a specific pair, then the
optimizer may choose a join order that avoids producing an intermediate Cartesian product.
Inner Joins
An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy the join
condition.
Outer Joins
An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and also returns
some or all of those rows from one table for which no rows from the other satisfy the join condition.
To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer join), use
the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+) to all columns of B in the join
condition in the WHERE clause. For all rows in A that have no matching rows in B, Oracle Database returns null for any
select list expressions containing columns of B.
To write a query that performs an outer join of tables A and B and returns all rows from B (a right outer join), use
the RIGHT [OUTER] JOINsyntax in the FROM clause, or apply the outer join operator (+) to all columns of A in the join
condition in the WHERE clause. For all rows in B that have no matching rows in A, Oracle returns null for any select list
expressions containing columns of A.
To write a query that performs an outer join and returns all rows from A and B, extended with nulls if they do not
satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the FROM clause.
You cannot compare a column with a subquery in the WHERE clause of any outer join, regardless which form you specify.
You can use outer joins to fill gaps in sparse data. Such a join is called a partitioned outer join and is formed using
the query_partition_clause of the join_clause syntax. Sparse data is data that does not have rows for all possible values
of a dimension such as time or department. For example, tables of sales data typically do not have rows for products that had no
sales on a given date. Filling data gaps is useful in situations where data sparsity complicates analytic computation or where some
data might be missed if the sparse data is queried directly.
See Also:
join_clause for more information about using outer joins to fill gaps in sparse data
Oracle Database Data Warehousing Guide for a complete discussion of group outer joins and filling gaps in sparse
data
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that
use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to
the FROM clause OUTER JOIN syntax:
You cannot specify the (+) operator in a query block that also contains FROM clause join syntax.
The (+) operator can appear only in the WHERE clause or, in the context of left-correlation (when specifying
the TABLE clause) in the FROMclause, and can be applied only to a column of a table or view.
If A and B are joined by multiple join conditions, then you must use the (+) operator in all of these conditions. If you
do not, then Oracle Database will return only the rows resulting from a simple join, but without a warning or error to
advise you that you do not have the results of an outer join.
The (+) operator does not produce an outer join if you specify one table in the outer query and the other table in an
inner query.
You cannot use the (+) operator to outer-join a table to itself, although self joins are valid. For example, the following
statement is not valid:
-- The following statement is not valid:
FROM employees
The (+) operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary expression can
contain one or more columns marked with the (+) operator.
A WHERE condition containing the (+) operator cannot be combined with another condition using the OR logical
operator.
A WHERE condition cannot use the IN comparison condition to compare a column marked with the (+) operator with an
expression.
If the WHERE clause contains a condition that compares a column from table B with a constant, then the (+) operator must be
applied to the column so that Oracle returns the rows from table A for which it has generated nulls for this column. Otherwise
Oracle returns only the results of a simple join.
In a query that performs outer joins of more than two pairs of tables, a single table can be the null-generated table for only one
other table. For this reason, you cannot apply the (+) operator to columns of B in the join condition for A and B and the join
condition for B and C. Refer to SELECT for the syntax for an outer join.
Antijoins
An antijoin returns rows from the left side of the predicate for which there are no corresponding rows on the right side of the
predicate. It returns rows that fail to match (NOT IN) the subquery on the right side.
See Also:
"Using Antijoins: Example"
Semijoins
A semijoin returns rows that match an EXISTS subquery without duplicating rows from the left side of the predicate when
multiple rows on the right side satisfy the criteria of the subquery.
Semijoin and antijoin transformation cannot be done if the subquery is on an OR branch of the WHERE clause.
--0075077159842
--Final_Query first to identify how many branches are working in manual group Session_ID from
select
branch_code,EOC_REF_NO,EOC_SEQ_NO,EOD_DATE,BRANCH_DATE,CURR_STAGE,TARGET_STAGE,RUN
_MODE,RUNNING_STAGE,EOC_STATUS
from AETB_EOC_BRANCHES
from AETB_EOC_BRANCHES
branch_code,Session_ID;
246
55
I'm doing some maintenance work on a database application and I've discovered that, joy of joys, even though values from
one table are being used in the style of foreign keys, there's no foreign key constraints on the tables.
I'm trying to add FK constraints on these columns, but I'm finding that, because there's already a whole load of bad data in
the tables from previous errors which have been naively corrected, I need to find the rows which don't match up to the
other table and then delete them.
I've found some examples of this kind of query on the web, but they all seem to provide examples rather than explanations,
and I don't understand why they work.
Can someone explain to me how to construct a query which returns all the rows with no matches in another table, and
what it's doing, so that I can make these queries myself, rather than coming running to SO for every table in this mess that
has no FK constraints?
sql foreign-keys
Kara
4,024104353
Frosty840
2,84684075
add a comment
9 Answers
activeoldest votes
473
SELECT t1.ID
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL
The key points are:
1. LEFT JOIN is used; this will return ALL rows from Table1, regardless of whether or not there is a matching row
in Table2.
2. The WHERE t2.ID IS NULL clause; this will restrict the results returned to only those rows where the ID returned
from Table2 is null - in other words there is NO record in Table2 for that particular ID from Table1. Table2.ID will
be returned as NULL for all records from Table1 where the ID is not matched in Table2.
shareimprove this answer
Toby Speight
17.1k134367
AdaTheDev
108k22164175
3
Fails if an ID is NULL – Michael Aug 13 '13 at 3:53
120
@Michael - If having a NULL ID is valid in your schema, you might have bigger problems, wouldn't you agree? :) – rinogo Nov 7 '13 at
4:44
5
@Martin - if this (correct example) "crashes" your MySQL server, I think you are blaming (and downvoting) the wrong thing. There
are of course many ways to skin a cat, of which this is a perfectly valid one. – AdaTheDev Mar 24 '14 at 14:05
will this work even if table1 has more records then table2? if table1 has 100 records and table2 has 200 records (100 that match/join
and 100 that don't match/join) would we get all 200 records returned?– Juan Velez Aug 8 '16 at 20:15
1
@pokerplayer23 - yes (see point 1 above) – AdaTheDev Aug 9 '16 at 8:14
48
I would use EXISTS expression since it is more powerfull, you can i.e more precisely choose rows you would like to join,
in case of LEFT JOIN you have to take everything what's in joined table. Its efficiency is probably same as in case of LEFT
JOIN with null test.
SELECT t1.ID
FROM Table1 t1
WHERE NOT EXISTS (SELECT t2.ID FROM Table2 t2 WHERE t1.ID = t2.ID)
shareimprove this answer
Ondrej Bozek
6,41934061
Something this simple is easily handled by the query optimizer for best execution. – Andrew WolfeFeb 7 '17 at 0:44
1
Yes, main advantage of EXISTS is its variability. – Ondrej Bozek Feb 7 '17 at 12:31
is it supposed to work in mysql ? I keep getting #1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near – Pavel Niedoba Mar 21 '18 at 13:46
It shoudl work for MySQL see docs: dev.mysql.com/doc/refman/5.5/en/… – Ondrej Bozek Mar 26 '18 at 10:03
1
Simple, elegant and it solved my problem! Nice one! – Mike D Wakelyn Nov 10 '18 at 20:17
1
Actually reduced the speed of one query i had from 7 sec to 200ms... (compared to WHERE t2.id IS NULL ) Thank You. – Moti
Korets Feb 12 at 20:56
add a comment
5,80232954
Theo Voss
11112
@zb226: Your link to has to do with limits on the IN clause with a list of literal values. It doesn't apply to using an IN clause with the
result of a sub-query. That accepted answer to that question actually solves the problem by using a sub-query. (A large list of literal
values is problematic because it creates a huge SQL expression. A sub-query works fine because, even if the resulting list is large,
the SQL expression itself is small.) – Kannan Goundan Feb 8 at 0:26
@KannanGoundan You're absolute right. Withdrawing the flawed comment. – zb226 Feb 8 at 9:46
add a comment
zb226
5,80232954
7912
add a comment
employee)
Now i want those records from employee table which are not in salary. We can do this in 3 ways-
1. Using inner Join
select * from employee where id not in(select e.id from employee e inner join salary s on e.id=s.id)
Debendra Dash
2,2911922
add a comment
From similar question here MySQL Inner Join Query To Get Records Not Present in Other Table I got this to work
SELECT * FROM bigtable
LEFT JOIN smalltable ON bigtable.id = smalltable.id
WHERE smalltable.id IS NULL
smalltable is where you have missing records, bigtable is where you have all the records. The query list all the records
that not exist in smalltable but exists on the bigtable. You could replace id by any other matching criteria.
shareimprove this answer
Luis H Cabrejo
577
add a comment
I Dont Knew Which one Is Optimized (compared to @AdaTheDev ) but This one seems to be quicker when I use (atleast
for me)
SELECT id FROM table_1 EXCEPT SELECT DISTINCT (table1_id) table1_id FROM table_2
If You want to get any other specific attribute you can use:
SELECT COUNT(*) FROM table_1 where id in (SELECT id FROM table_1 EXCEPT SELECT DISTINCT (table1_id)
table1_id FROM table_2);
shareimprove this answer
answered Jan 25 '18 at 6:59
Jerin K. John
353313
add a comment
Nitesh singh
51
add a comment
-4
union
Clearly, COUNT(*) and COUNT(1) will always return the same result. Therefore, if one were slower than the
other it would effectively be due to an optimiser bug. Since both forms are used very frequently in queries, it
would make no sense for a DBMS to allow such a bug to remain unfixed. Hence you will find that the
performance of both forms is (probably) identical in all major SQL DBMSs.
Example of count(*)
Example of count(1)
User of Joins using Trial Balance concept in Oracle Flexcube:
SELECT
FROM
GLTB_GL_BAL gl_bal
WHERE
gl_bal.LEAF = 'Y'
Syntax
The syntax for the CREATE TABLE AS statement that copies all of the columns in Oracle/PLSQL is:
Example
Let's look at a CREATE TABLE AS example that shows how to create a table by copying all columns
from another table.
This example would create a new table called suppliers that included all columns from
the companies table.
If there were records in the companies table, then the new suppliers table would be populated with the
records returned by the SELECT statement.
Syntax
The syntax for the CREATE TABLE AS statement that copies the selected columns in Oracle/PLSQL is:
This example would create a new table called suppliers, but the new table would only include the
specified columns (ie: company_id, address, city, state, and zip) from the companies table.
Again, if there were records in the companies table, then the new suppliers table would be populated with
the records returned by the SELECT statement.
Syntax
The syntax for the CREATE TABLE AS statement that copies columns from multiple tables in
Oracle/PLSQL is:
Example
Let's look at a CREATE TABLE AS example that shows how to create a table by copying selected
columns from multiple tables.
For example:
This example would create a new table called suppliers based on columns definitions from both
the companies and categories tables (ie: company_id, address, and category_type).
Frequently Asked Questions
Question: How can I create an Oracle table from another table without copying any values from the old
table?
Answer: To do this, the Oracle CREATE TABLE syntax is:
For example:
Use of two columns condtion in where clause + use of Brackets in where clause instead of = operator:
set array 1
set head on
set feedback on
set echo on
SPOOL C:\MULTI_BRN_EODM_MANUAL.SPL
BEGIN
--DBMS_OUTPUT.PUT_LINE('RESETTING FBTB_TILL_TOTALS');
CCYCODE,
BRANCHCODE,
POSTINGDATE,
OPENINGBALANCE,
INFLOW,
OUTFLOW)
SELECT totals.TILL_ID,
totals.CCYCODE,
totals.BRANCHCODE,
info.nextpostingdate,
NVL(totals.openingbalance, 0) + NVL(totals.inflow, 0) -
NVL(totals.outflow, 0),
0.00,
0.00
--DBMS_OUTPUT.PUT_LINE('RESETTING FBTB_TILL_DETAIL_CCY');
UPDATE fbtb_till_detail_ccy
UPDATE FBTB_CUST_ACCOUNT
FROM fbtm_branch_info
UPDATE FBTM_BRANCH_INFO BI
end loop;
END;
COMMIT;
SPOOL OFF
USE OF SIMPLE LOOP IN ORACLE FLEXCUBE:
BEGIN
FOR BR IN (select branch_code from sttm_branch where branch_code in ('002', '003', '011',
'012', '020', '021', '022', '024', '025', '026', '027', '028', '029', '030', '032',
'033', '034', '035', '036', '037', '038', '039', '040', '041', '042', '043', '044',
'045', '046', '047', '048', '049', '051', '052', '053', '054', '055', '056', '057',
'058', '059', '061', '065', '066', '067', '068', '069', '070', '071', '072', '073',
'074', '075', '076', '077', '078', '079', '080', '081', '082', '083', '084', '085',
'086', '087', '088', '089', '090', '091', '092', '093', '094', '095', '096', '097',
'098', '099', '100', '101', '102', '103', '104', '105', '106', '108', '109', '110',
'111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122',
'123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134',
'135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146',
'147', '150', '151', '155', '156', '157', '158', '159', '160', '161', '162', '163',
'165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176',
'177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188',
'189', '190', '192', '193', '194', '195', '196', '197', '201', '202', '203', '204',
'205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216',
'217', '218', '220', '221', '222', '224', '225', '226') order by 1) LOOP
--===============================================================================
--===============================================================================
commit;
END LOOP;
END;
USE OF TIME IN ORACLE:
--Written by Adeel
x.branch_code,
x.eod_date,
x.eoc_stage,
x.eoc_stage_seq,
2) total_min_taken
from aetb_eoc_runchart_history x
union all
Select * from(
select
i.branch_code,
i.eod_date,
i.eoc_stage,
i.eoc_stage_seq,
2) tot_min_taken
from aetb_eoc_runchart i