Question

Possible uses of Cartesian joins

Asked by: BobMc

I'm asking this just for fun folloing a long standing discussion at work...

Does anyone know of a decent real-world situation where a cartesian join is actually useful and/or preffered
?
I can come up with some situations where I can use one, but there is always a better way to do it, normally with a PL/SQL loop.

Points available for simple or ingenious examples that I can demo to colleagues, although theoretical discussions are always welcome!

Cheers
Bob

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2002-12-30 at 14:20:09ID20439756
Tags

cartesian

,

join

Topic

Oracle Database

Participating Experts
5
Points
50
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Cartesian problem
    OK, I have a query that is supposed to return hits from web sites containing key words. The problem is that my query is returning a cartesian product of everything. This is my SQL: SELECT DISTINCT TITLE.TITLE, URL.SYSTEM, URL.GID, URL.URL, KEY_WORDS.KEY_WORD FROM TITLE,...
  2. Cartesian join
    Hi all, What is the right way to deal with Cartesian Join? Thanks in advance sam
  3. Detecting a cartesian product
    I am developing a query builder form something similar to TOAD. When the user selects multiple columns from various tables i need to detect whether the tables can be joined or not. I want this to be done so that i can avoid a cartesian product when the final query is built an...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: gmyersPosted on 2002-12-30 at 15:57:38ID: 7648328

One candidate is a matrix report where the detail table can't be used to 'drive' it.

create table customer (name varchar2(100));
create table product (name varchar2(100));
create table orders (cust_name varchar2(100), prod_name varchar2(100), qty number);

insert into customer values ('fred');
insert into customer values ('bill');
insert into customer values ('john');
insert into customer values ('tom');

insert into product values ('bread');
insert into product values ('milk');
insert into product values ('butter');
insert into product values ('eggs');
insert into product values ('flour');

insert into orders values ('fred','bread',75);
insert into orders values ('fred','bread',25);
insert into orders values ('fred','flour',90);
insert into orders values ('bill','milk',20);
insert into orders values ('bill','eggs',100);
insert into orders values ('bill','flour',130);
insert into orders values ('john','bread',50);
insert into orders values ('john','milk',10);
insert into orders values ('john','eggs',117);
insert into orders values ('john','flour',500);


select cp.cust_name, cp.prod_name, nvl(sum(orders.qty),0)
from orders,
  (select customer.name cust_name, product.name prod_name
  from customer, product) cp
where orders.cust_name(+) = cp.cust_name
and orders.prod_name(+) = cp.prod_name
group by cp.cust_name, cp.prod_name

 

by: Bigfam5Posted on 2002-12-31 at 04:47:51ID: 7649705

gmyers,
This would not, by definition, be a cartesian join.
Cartesian Join : If two tables in a join query have no join condition.  If a query
joins three or more tables and you do not specify a join condition for a specific pair,
the optimizer may choose a join order that avoids producing an intermediate
Cartesian product.

BobMc
The only time I have used a cartesian join is if I needed counts of tables.
Example:

Select Count_Tab1, Count_Tab2, Count_Tab3
  from (select count(1) Count_Tab1 from table1 where ... ),
           (select count(1) Count_Tab2 from table2 where ... ),
           (select count(1) Count_Tab3 from table3 where ... )
;

 

by: wes_wilsonPosted on 2002-12-31 at 06:50:38ID: 7649973

I have two examples for you.  First is probably not what you are looking for but its one handy use for them.  I sometimes use them to generate heavy loads on a server.  Doing a cartesian join on large tables will give you plenty of time to look at memory and disk structures, check your parallelism and in general make sure everything is working well.  =)  

Second, is to generate a complete list of all possible combinations between two tables and then use this for further processing.  While this can be done in PL/SQL there are a number of instances where this is a poor choice.  First, if your application needs to be database generic and run on multiple platforms, your code will probably be on an app server and it would be extremely inefficient to pull all of this data back to the app server.  Second, even in PL/SQL, I assume you are going to want to use this complete list to do more work or queries.  If you did it in PL/SQL, you're going to have to write it all back to a table so you can run more queries against it, slow slow slow.  

As for a specific example, when you do things similar to Market Basket analysis you almost always start by generating a complete set of all possible combinations, then you match this up against sales, pricing, inventory and customers to look for patterns in the data.  Without the cartesian there is no way to get every element with every other element, an outer join just gives you nulls on one side or the other.  If you do the cartesian in a loop then you have to write it back to a table for further joins and if you are cartesianing multiple tables your PL/SQL code will almost always be slower because you don't have access to the statistics to determine the optimal order to cartesian.

Another specific example is if your users do "what if" scenarios.  Suppose you want to see what your sales for a specific store would have been if you had carried every item in a department.  You simply perform a restricted cartesian that limits by department and store to get a list of every item with that store number, then join this to your sales information to see what your sales would have been.  You could write this query in about 5 minutes, I suspect the program would several hours even for a good programmer.  You may also choose to use a minus in this situation as well to make it more accurate.  You may want to use the actual sales for items that were carried in that store/dept, and averages for the items that weren't carried from all other stores.  Then combine these two together with a union and sum for a more accurate "what if".  Again, fairly easy in sql, more involved and less flexible in code.

Hope these help, let us know how your debate goes.

-Wes

 

by: gmyersPosted on 2003-01-01 at 14:14:23ID: 7652607

For BigFam,

The tables I tested had a lot more rows than the example given, and were analyzed (to use cost rather than rule based optimizer).
The explain plan (shown below) included the catesian join.

Regarding your quote, there is no join condition between product and customer. There is a third table, but because of the outer join, it cannot be used to provide a better query plan than the cartesian join.

Lvl Optimizer Operation           Options         Obj_Name    No_Rows
1   CHOOSE    SELECT STATEMENT                                1
2             SORT                GROUP BY NOSORT             1
3             MERGE JOIN          OUTER                       6448970
4             SORT                JOIN                        6448970
4             SORT                JOIN                        82
5             VIEW                                            6448970
6             MERGE JOIN          CARTESIAN                   6448970
7   ANALYZED  TABLE ACCESS        FULL            PRODUCT     2530
7             SORT                JOIN                        2549
8   ANALYZED  TABLE ACCESS        FULL            CUSTOMER    2549
5   ANALYZED  TABLE ACCESS        FULL            ORDERS      10

 

by: BobMcPosted on 2003-01-20 at 11:29:10ID: 7762720

Thanks for the input guys - I should be able to put this one to bed now.

Cheers
Bob

 

by: KroniquePosted on 2004-03-26 at 15:10:43ID: 10692049

I have a situation here

Table A
columns are
YEARMONTH (number like 200403), LEASENBR,AMT1,AMT2

Table B
column
YEARMONTH (number like 200403) always has 1 record thats current monthyear


Now i have written a query:

(select A.LEASENBR, sum(A.AMT1),sum(case when B.YEARMONTH >= A.YEARMONTH  
and ((round(B.YEARMONTH /100,0)*12 + mod(B.YEARMONTH ,100))-(round(A.YEARMONTH/100,0)*12 + mod(A.YEARMONTH ,100))) <=6 then A.AMT2 else 0 end)
from A,B
group by LEASENBR)

Is this not a useful case of cartesian join. If not can anybody suggest a better way ?

The Case statement is pulling all the AMT2 for which YEARMONTH is <= 6 months from current month






 

by: CarlovskiPosted on 2004-07-28 at 07:48:22ID: 11657098

Know this topic is dead, but one use I have found (Apart from generating fixture lists!) is to break columns of data into rows e.g

select ref,                                          
decode(rn, 1 , column1, 2, column2, 3 , column3)    
value                                                    
from wide_table, (select rownum rn from all_objects
where rownum <=3)                                        
order by ref                                          

Using all_objects is arbitrary, just need a nice available, big table.
This turns

ref    column1    column2  column3 ........
1         a               b             c
2         d               e             f

into

ref      value
1            a
1            b
1            c
2            d
2            e
2            f
Just keep adding to the decode, and up the  rownum <= value to add more columns.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...