Yes, you got that right, the old CONNECT BY as used by recursive SQL with Oracle has been replaced by Common Table Expressions, or the WITH statement in SQL:1999 which is now also available in MariaDB 10.2. Now, the SQL WITH construct, using Common Table Expressions or CTE, is useful for other things than just recursive queries, but this is the one feature that WITH enables that was previously very hard to do without some procedural code, the non-recursive use of Common Table Expressions could previously mostly be replaced by using temporary tables.
This blog post will explain what recursive SQL is all about and why this is useful, and I will show some examples of both CONNECT BY and how the same SQL is written using the WITH clause.
The most common example for recursive SQL is probably for doing a parts explosion, where we have a table of parts of some component where each part is either a main, top level, part or is a part of another part. For example a car with an engine, where the engine consists of pistons, cylinders and a camshaft, where the latter also includes some camshaft bearings. I think you get the basic idea here. To query this data to create a list of components that make up some other component, you need to recursively visit the data, i.e.. each row is evaluated using conditions from any other row already fetched, except the first row fetched that is.
Now, let's look at some data first. I assume we have two tables here, one table that contains information on the different parts and then one table that contains information on the individual parts and then one table that contains the hierarchy of the parts, called components. Like this:
CREATE TABLE parts(part_id INTEGER NOT NULL PRIMARY KEY,
part_name VARCHAR(60) NOT NULL);
CREATE TABLE components(comp_id INTEGER NOT NULL PRIMARY KEY,
comp_name VARCHAR(60),
comp_count INTEGER NOT NULL,
comp_part INTEGER NOT NULL,
comp_partof INTEGER,
FOREIGN KEY(comp_part) REFERENCES parts(part_id));
ALTER TABLE components ADD FOREIGN KEY(comp_partof) REFERENCES components(comp_id);
The two things to note here is that the components table has a column, comp_partof, that implements the hierarchy and that there is a self-referencing FOREIGN KEY constraint on this table. Given these tables, assuming that we are a small privately held car-manufacturing company in southern Germany, let's insert some data:
INSERT INTO parts VALUES(1, 'Car');
INSERT INTO parts VALUES(2, 'Bolt');
INSERT INTO parts VALUES(3, 'Nut');
INSERT INTO parts VALUES(4, 'V8 engine');
INSERT INTO parts VALUES(5, '6-cylinder engine');
INSERT INTO parts VALUES(6, '4-cylinder engine');
INSERT INTO parts VALUES(7, 'Cylinder block');
INSERT INTO parts VALUES(8, 'Cylinder');
INSERT INTO parts VALUES(9, 'Piston');
INSERT INTO parts VALUES(10, 'Camshaft');
INSERT INTO parts VALUES(11, 'Camshaft bearings');
INSERT INTO parts VALUES(12, 'Body');
INSERT INTO parts VALUES(13, 'Gearbox');
INSERT INTO parts VALUES(14, 'Chassie');
INSERT INTO parts VALUES(15, 'Rear axle');
INSERT INTO parts VALUES(16, 'Rear break');
INSERT INTO parts VALUES(17, 'Wheel');
INSERT INTO parts VALUES(18, 'Wheel bolts');
INSERT INTO components VALUES(1, '320', 1, 1, NULL);
INSERT INTO components VALUES(2, NULL, 1, 6, 1);
INSERT INTO components VALUES(3, NULL, 1, 7, 2);
INSERT INTO components VALUES(4, NULL, 4, 8, 3);
INSERT INTO components VALUES(5, NULL, 4, 9, 3);
INSERT INTO components VALUES(6, NULL, 1, 10, 3);
INSERT INTO components VALUES(7, NULL, 3, 11, 6);
INSERT INTO components VALUES(8, NULL, 1, 12, 1);
INSERT INTO components VALUES(9, NULL, 1, 14, 1);
INSERT INTO components VALUES(10, NULL, 1, 15, 9);
INSERT INTO components VALUES(11, NULL, 2, 16, 10);
INSERT INTO components VALUES(12, '323 i', 1, 1, NULL);
INSERT INTO components VALUES(13, NULL, 1, 5, 12);
If you are not into mechanics, let me tell you that there are more parts than this to a car, for example I left out a few critical components, such as the cupholder, the dog that stands on the pickup cargo area and the insulting bumber-sticker, but I think you get the idea. Note that there are two "main" components, the '320' and '323 i' and that these are top level components are indicated by the comp_partof column being set to NULL.
Now, assume you want to list all the parts that make up a 320. The way this works when using the CONNECT BY syntax, you compose one single SQL statement and provide a CONNECT BY clause to indicate the relationship. Like this:
SELECT LPAD('-', level, '-')||'>' level_text, comp_count, NVL(comp_name, part_name) name
FROM components c, parts p
WHERE c.comp_part = p.part_id
START WITH c.comp_name = '320'
CONNECT BY PRIOR c.comp_id = c.comp_partof;
Let me explain this a bit, but there is nothing really magic here. We are selecting from the two tables and joining them just as usual. Then we use the START WITH clause to define the top level component and then the rest of the components are have a comp_partof of a component that matches the comp_id of the START WITH component or a comp_id of any other component that has been fetched.
This way of writing recursive SQL has some advantages, such as it is relatively compact and is easy to understand. The disadvantage is that there are some quirks and limitation to this and that once your queries gets more complex, CONNECT BY gets a bit hairy. One sure sign that CONNECT BY is going away, even though I and many others tend to like it because of the ease of use, is that even Oracle, as of Oracle 11g, also has implemented the WITH construct, or Common Table Expressions or CTE. So looking at the above statement how this would work in MariaDB 10.2, this is what it would look like using the WITH construct:
WITH RECURSIVE comp(comp_id, comp_name, comp_partof, comp_count) AS (
SELECT comp_id, comp_name, comp_partof, comp_count
FROM components JOIN parts ON comp_part = part_id
WHERE comp_partof IS NULL AND comp_name = '320'
UNION ALL
SELECT c1.comp_id, p.part_name, c1.comp_partof, c1.comp_count
FROM components c1 JOIN parts p ON c1.comp_part = p.part_id
JOIN comp c2 ON c1.comp_partof = c2.comp_id)
SELECT comp_count, comp_name FROM comp;
Comparing this CTE version to the CONNECT BY version as above, this is a bit more complex, but how it works is actually pretty clear once you look at it carefully. To begin with, the top level item or anchor is the first SELECT in the UNION ALL and the following components are fetched using the second SELECT. Then the recursive aspect is handled by this UNION being run until there are no more rows returned from it? As you can see, although this requires more text and more complex SQL to write, it is also a fair bit more flexible. For example, the anchor point is defined by a completely separate SELECT which means it can be whatever SELECT you want, selecting from any odd table. Secondly, the column you use and the conditions for defining the hierarchy can be as complex as you want. And thirdly, there is also the power of that last SELECT which in the case above just gets the data from the UNION, but you can actually apply any kind of filter, ordering or column filter to this query. The result of the query above is this:
comp_count comp_name
1 320
1 4-cylinder engine
1 Body
1 Chassie
1 Cylinder block
1 Rear axle
4 Cylinder
4 Piston
1 Camshaft
2 Rear break
3 Camshaft bearings
Before I finish this off, the WITH RECURSIVE statement is somewhat overly complex, in MariaDB 10.2 you can for example skip listing the column names of the recursive table, like this:
WITH RECURSIVE comp AS (
SELECT comp_id, comp_name, comp_partof, comp_count
FROM components JOIN parts ON comp_part = part_id
WHERE comp_partof IS NULL AND comp_name = '320'
UNION ALL
SELECT c1.comp_id, p.part_name, c1.comp_partof, c1.comp_count
FROM components c1 JOIN parts p ON c1.comp_part = p.part_id
JOIN comp c2 ON c1.comp_partof = c2.comp_id)
SELECT comp_count, comp_name FROM comp;
And although Oracle 11 and up supports the CTEs, it works a bit differently. For one thing, the RECURSIVE keyword isn't supported (it is assumed to be recursive by default) and the way I read the SQL standard, this is actually wrong, for recursive queries you have to use the RECURSIVE keyword. Second, Oracle does require the SELECT-list. So in Oracle, you would see something like this:
WITH comp(comp_id, comp_name, comp_partof, comp_count) AS (
SELECT comp_id, comp_name, comp_partof, comp_count
FROM components JOIN parts ON comp_part = part_id
WHERE comp_partof IS NULL AND comp_name = '320'
UNION ALL
SELECT c1.comp_id, p.part_name, c1.comp_partof, c1.comp_count
FROM components c1 JOIN parts p ON c1.comp_part = p.part_id
JOIN comp c2 ON c1.comp_partof = c2.comp_id)
SELECT comp_count, comp_name FROM comp;
Yes, we are all happily following the same SQL standard. Somewhat...
See the MariaDB Knowledge Base for more information on common table expressions.
Happy SQL'ing
/Karlsson
25 comments:
Hey Guys Choose Your Online Assignment Help Services when you have no time to write your Dissertation Proposal Writing Service Assignments. You can’t make your academic papers effective if you have less time to infuse in your assignments. So, Here is a option for online Dissertation Proofreading Service and connect with Our experts services for your homework.
SQL is a domain-specific language used in programming and designed for managing data held in a relational database management system and it has great importance for developers. Assignment writing services.
The most not unusual example for recursive SQL might be for doing a parts explosion, in which we've got a desk of components of a few component where in each element is either a primary, pinnacle level, element or is part swot analysis of Samsung of any other component. For instance a vehicle with an engine.
Everything is very open with a precise description of the challenges. It was truly informative. Your site is useful. Thanks for sharing! for More Information Click the Link:QuickBooks Error 189
Hi guys! I would like to thank you for suggestions of the best writing service https://best-writing-service.com/lab-report-writing. I use it because it is a top-notch service. It helps me get what I want. I do not worry about my papers anymore.
There can be various purposes behind Gmail error 400 condition and one of them being dreadful accreditations. To decide this issue, you can use the help that is offered by the tech gatherings or you can show up at the customer care for additional help by tending to the rep and mentioning tips to deal with the error.
To recover a how to fix Facebook login problem without a phone number, you are asked to launch your web browser and then navigate to the account recovery page of Facebook. Here, you need to enter your email address or select answer security questions to verify your account as well as your identity.
You need to submit an essay soon and you haven't started writing anything yet? Don't know how best to write and what topic to choose? I think they will be able to help you with this https://primeessay.org/ms-powerpoint-presentations.html
Thanks for Sharing such an amazing article. Keep working... Your Site is very nice, and it's very helping us.. this post is unique and interesting, thank you for sharing this awesome information
sspmis | sspmis bihar | sspmis login
When buying essays on the Internet, students are always concerned about the quality of the written papers. All your doubts will be dispelled if you panda writing paper service online.
Your blog is filled with unique good articles! I was impressed how well you express your thoughts.
BIMS Kerala , BIMS Kerala Treasury, BIMS Kerala Login
Excel assignments may be daunting and time-consuming. Why not to find some excel experts for hire and get a perfect homework.
Thanks for your post's information which I may use in my quality writing paperwork about recursive SQL.
Such a great post as you share it & That really helps me because knowledgeable and informative articles have their importance thanks for sharing. by affordable embroidery digitizing
Amazing Information. It is really very helpful information for me. Thanks for sharing with us.
Honeymoon Destinations In India
Places To Visit In India
Places To Visit In Manali
Places To Visit In Goa
Nice Information. It is really very helpful and well-explained information. Thanks for sharing.
The cash app support will assist you to how to get Cash App Refund in no time. In case of any confusion, just feel free to call the techies. Your all technical glitch of cash app account will be solved instantly by the technical team of cash app.
Hi, I am Sofia Vergara from New York, USA. I am an ATT Yahoo Email technical expert. We provide solutions to fix ATT mail Login Problems. If you are worried due to ATT Yahoo Email login issues, then you may contact the ATT Yahoo Email Support team. They will guide you in a quiet manner.
You have written a well-written article. The article is short and sweet. Thanks! This is a fun game you can play in your free time. The Scroll Test Tool estimates how many pixels a user can scroll in a certain amount of time. To learn more, click here Mouse scroll test.
I like this article thank you so much. 789 ทางเข้า
Women's ethnic tops and kurti can be purchased in India. Sabhyata has a large selection of ethnic tops online and kurti at affordable costs. Now is the time to shop!
123HelpMe.org employs a team of expert writers capable of composing high-quality speeches for students. You may ask write my speech for me and get a great speech to deal with your academic problems.
I really appreciate the kind of topics you post here. Thanks for sharing great information that is actually helpful. Good day!
Megri Embroidery Digitizing
Hi.
Thank you for your kind words and appreciation for the article I shared. I'm glad you found it amazing. Your encouragement means a lot to me and motivates me to keep working. I'm delighted to know that my website has been helpful to you. I strive to provide unique and interesting posts, and I'm grateful that you found the information shared in this post to be awesome.
Here is sharing some OTM Training information may be its helpful to you.
OTM Training
Watch Hindi drama shows in Australia with Maxx TV. Enjoy a wide range of popular Hindi serials and shows with high-quality streaming. Maxx TV brings the best of Indian entertainment to your screen in Australia.
Axcel Gases is a trusted butane gas manufacturer in India. We provide high-quality butane gas for various industries at affordable prices. Our cylinders are safe, reliable, and made to meet customer needs. Choose Axcel Gases for all your butane gas needs in India.
Post a Comment