{"id":4270,"date":"2024-01-10T20:00:00","date_gmt":"2024-01-10T19:00:00","guid":{"rendered":"https:\/\/www.skillup.cloud\/cte-ricorsive-leleganza-della-semplicita-in-sql-1\/"},"modified":"2024-02-12T09:38:50","modified_gmt":"2024-02-12T08:38:50","slug":"recursive-cte-the-elegance-of-simplicity-in-sql-1","status":"publish","type":"post","link":"https:\/\/www.skillup.cloud\/en\/recursive-cte-the-elegance-of-simplicity-in-sql-1\/","title":{"rendered":"Recursive CTE: The Elegance of Simplicity in SQL &#8211; 1"},"content":{"rendered":"\n<p>Common Table Expressions (CTE) in SQL on IBM iSeries (AS\/400) are a powerful and flexible tool for creating temporary, reusable queries, simplifying and improving the readability of complex SQL queries.<\/p>\n\n\n\n<p>Below are the articles in the CTE series (including this current one):<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"text-decoration: underline\"> <\/span><a href=\"https:\/\/www.skillup.cloud\/en\/iseries-sql-cte-common-table-expressions-definitions-and-usage\/\" target=\"_blank\" rel=\"noreferrer noopener\">iSeries Sql &#8211; CTE Common Table Expressions &#8211; definitions and usage<\/a><span style=\"text-decoration: underline\"> <\/span><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"text-decoration: underline\"> <\/span><a href=\"https:\/\/www.skillup.cloud\/en\/recursive-cte-the-elegance-of-simplicity-in-sql-1\/\" target=\"_blank\" rel=\"noreferrer noopener\">Recursive CTE: The Elegance of Simplicity in SQL &#8211; 1<\/a><span style=\"text-decoration: underline\"> <\/span><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"text-decoration: underline\"> <\/span><a href=\"https:\/\/www.skillup.cloud\/en\/recursive-cte-the-elegance-of-simplicity-in-sql-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">Recursive CTE: The Elegance of Simplicity in SQL \u2013 2<\/a><span style=\"text-decoration: underline\"> <\/span><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"text-decoration: underline\"> <\/span><a href=\"https:\/\/www.skillup.cloud\/en\/recursive-cte-the-elegance-of-simplicity-in-sql-3\/\" target=\"_blank\" rel=\"noreferrer noopener\">Recursive CTE: The Elegance of Simplicity in SQL \u2013 3<\/a><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"text-decoration: underline\"> <\/span><a href=\"https:\/\/www.skillup.cloud\/en\/recursive-cte-how-to-concatenate-the-results-onto-a-single-line\/\" target=\"_blank\" rel=\"noreferrer noopener\">Recursive CTE how to concatenate the results onto a single line<\/a><span style=\"text-decoration: underline\"> <\/span><\/li>\n<\/ul>\n\n\n\n<p><strong>Recursive<\/strong> Common Table Expressions (CTE) are a powerful tool in SQL that allows you to <strong>perform operations that, in the absence of this functionality, would require the development of specific programs or the use of complex loops<\/strong>.<\/p>\n\n\n\n<p>These CTEs are particularly useful for working with hierarchical data, such as trees or tree structures, and for performing iterative or recursive calculations.<\/p>\n\n\n\n<p>In this article we will see a significant example in detail relating to &#8216;Navigation in hierarchical structures&#8217;<\/p>\n\n\n\n<p class=\"has-large-font-size\"><strong>Hierarchical level assignment with Recursive CTE<\/strong><\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Description Context and Objective<\/strong><\/p>\n\n\n\n<p>This query is designed to display the organizational structure of a company in a hierarchical form. It can be used to understand reporting relationships between employees and managers and to identify the depth of the organizational hierarchy.<\/p>\n\n\n\n<p>While the original table may contain other relevant information, for the purpose of this query, the focus is solely on Employee Identifier (ID), Employee Name (Name), and Manager Identifier (IdManagerI.<\/p>\n\n\n\n<p>The main objective is to generate a list in which each employee (ID and Name) is associated with the hierarchical level from 0 to n, where 0 represents the top Manager or Company, 1 the employees who depend on the top Manager, and so on.<\/p>\n\n\n\n<p>Suppose we have an archive that represents the following hierarchical structure (where the top Manager is I011):<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" src=\"https:\/\/www.skillup.cloud\/wp-content\/uploads\/2024\/01\/employee_manager.png\" alt=\"\" style=\"width:642px;height:auto\"\/><\/figure><\/div>\n\n\n<p>the contents of the employee archive:<\/p>\n\n\n\n<div class=\"wp-block-columns\">\n<div class=\"wp-block-column\">\n<figure class=\"wp-block-table\"><table><tbody><tr><td>ID<\/td><td>NAME<\/td><td>IDMANAGER<\/td><\/tr><tr><td>I011<\/td><td>Employee_011<\/td><td><\/td><\/tr><tr><td>I021<\/td><td>Employee_021<\/td><td>I011<\/td><\/tr><tr><td>I022<\/td><td>Employee_022<\/td><td>I011<\/td><\/tr><tr><td>I023<\/td><td>Employee_023<\/td><td>I011<\/td><\/tr><tr><td>I031<\/td><td>Employee_031<\/td><td>I022<\/td><\/tr><tr><td>I032<\/td><td>Employee_032<\/td><td>I022<\/td><\/tr><tr><td>I041<\/td><td>Employee_041<\/td><td>I031<\/td><\/tr><tr><td>I042<\/td><td>Employee_042<\/td><td>I031<\/td><\/tr><tr><td>I043<\/td><td>Employee_043<\/td><td>I031<\/td><\/tr><tr><td>I045<\/td><td>Employee_045<\/td><td>I032<\/td><\/tr><tr><td>I046<\/td><td>Employee_046<\/td><td>I032<\/td><\/tr><tr><td>I047<\/td><td>Employee_047<\/td><td>I032<\/td><\/tr><tr><td>I051<\/td><td>Employee_051<\/td><td>I042<\/td><\/tr><tr><td>I052<\/td><td>Employee_052<\/td><td>I046<\/td><\/tr><tr><td>I061<\/td><td>Employee_061<\/td><td>I051<\/td><\/tr><tr><td>I062<\/td><td>Employee_062<\/td><td>I051<\/td><\/tr><tr><td>I063<\/td><td>Employee_063<\/td><td>I051<\/td><\/tr><tr><td>I064<\/td><td>Employee_064<\/td><td>I052<\/td><\/tr><tr><td>I065<\/td><td>Employee_065<\/td><td>I052<\/td><\/tr><tr><td>I066<\/td><td>Employee_066<\/td><td>I052<\/td><\/tr><\/tbody><\/table><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column\"><\/div>\n<\/div>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Query<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">WITH -- starting data\n     employee (ID, Name, IdManager) AS (\n         VALUES  ('I011', 'Employee_011',  NULL) , ('I021', 'Employee_021', 'I011'),\n                 ('I022', 'Employee_022', 'I011'), ('I023', 'Employee_023', 'I011'),\n                 ('I031', 'Employee_031', 'I022'), ('I032', 'Employee_032', 'I022')\n,\n                 ('I041', 'Employee_041', 'I031'), ('I042', 'Employee_042', 'I031'),\n                 ('I043', 'Employee_043', 'I031'), ('I045', 'Employee_045', 'I032'),\n                 ('I046', 'Employee_046', 'I032'), ('I047', 'Employee_047', 'I032')\n,\n                 ('I051', 'Employee_051', 'I042'), ('I052', 'Employee_052', 'I046'),\n                 ('I061', 'Employee_061', 'I051')\n, ('I062', 'Employee_062', 'I051'),\n                 ('I063', 'Employee_063', 'I051'), ('I064', 'Employee_064', 'I052')\n               , ('I065', 'Employee_065', 'I052'), ('I066', 'Employee_066', 'I052'))\n  ,  hierarchy (ID, Name, Level) AS (\n         SELECT ID, Name\n              , 0 AS Level\n           FROM employee\n          WHERE IdManager IS NULL\n        UNION ALL\n         SELECT e.ID, e.Name, h.Level + 1\n           FROM employee e\n          INNER JOIN hierarchy h ON e.IDManager = h.ID\n          )\nSELECT * FROM hierarchy;\n<\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Result<\/strong><\/p>\n\n\n\n<p><strong>Result table (hierarchy)<\/strong><\/p>\n\n\n\n<div class=\"wp-block-columns\">\n<div class=\"wp-block-column\">\n<figure class=\"wp-block-table\"><table><tbody><tr><td>ID<\/td><td>NAME<\/td><td>LEVEL<\/td><\/tr><tr><td>I011<\/td><td>Employee_011<\/td><td>0<\/td><\/tr><tr><td>I021<\/td><td>Employee_021<\/td><td>1<\/td><\/tr><tr><td>I022<\/td><td>Employee_022<\/td><td>1<\/td><\/tr><tr><td>I023<\/td><td>Employee_023<\/td><td>1<\/td><\/tr><tr><td>I031<\/td><td>Employee_031<\/td><td>2<\/td><\/tr><tr><td>I032<\/td><td>Employee_032<\/td><td>2<\/td><\/tr><tr><td>I041<\/td><td>Employee_041<\/td><td>3<\/td><\/tr><tr><td>I042<\/td><td>Employee_042<\/td><td>3<\/td><\/tr><tr><td>I043<\/td><td>Employee_043<\/td><td>3<\/td><\/tr><tr><td>I045<\/td><td>Employee_045<\/td><td>3<\/td><\/tr><tr><td>I046<\/td><td>Employee_046<\/td><td>3<\/td><\/tr><tr><td>I047<\/td><td>Employee_047<\/td><td>3<\/td><\/tr><tr><td>I051<\/td><td>Employee_051<\/td><td>4<\/td><\/tr><tr><td>I052<\/td><td>Employee_052<\/td><td>4<\/td><\/tr><tr><td>I061<\/td><td>Employee_061<\/td><td>5<\/td><\/tr><tr><td>I062<\/td><td>Employee_062<\/td><td>5<\/td><\/tr><tr><td>I063<\/td><td>Employee_063<\/td><td>5<\/td><\/tr><tr><td>I064<\/td><td>Employee_064<\/td><td>5<\/td><\/tr><tr><td>I065<\/td><td>Employee_065<\/td><td>5<\/td><\/tr><tr><td>I066<\/td><td>Employee_066<\/td><td>5<\/td><\/tr><\/tbody><\/table><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column\"><\/div>\n<\/div>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Detailed description of the query<\/strong><\/p>\n\n\n\n<p><strong>Definition of the Employee Table:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <strong>employee<\/strong> CTE is defined as a temporary table containing three columns: <strong>ID<\/strong> (employee identifier), <strong>Name<\/strong> (employee name), and <strong>IdManager<\/strong> (identifier of each employee&#8217;s manager).<br>&nbsp;<\/li>\n\n\n\n<li>The table is populated with a series of values \u200b\u200bthat represent a company organizational structure. For example, &#8216;I011&#8217; is an employee with no manager (<strong>NULL<\/strong>), which implies that he could be a manager or a department head (top Manager).<\/li>\n<\/ul>\n\n\n\n<p><strong>Hierarchy construction:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The CTE <strong>hierarchy<\/strong> is a recursive CTE composed of two parts: a base part and a recursive part, separated by the <strong>UNION ALL<\/strong> operator.<br>&nbsp;<\/li>\n\n\n\n<li><strong>Basic Part<\/strong>: Select employees who do not have a manager (<strong>IdManager IS NULL<\/strong>). These employees represent the starting point of the hierarchy (for example, company management). These are assigned a <strong>Level<\/strong> 0, indicating the highest level of the hierarchy.<br>&nbsp;<\/li>\n\n\n\n<li><strong>Recursive Part<\/strong>: Connects each employee to their manager through an <strong>INNER<\/strong> <strong>JOIN<\/strong> between the CTE <strong>employee<\/strong> and the <strong>hierarchy<\/strong> itself. At each step of the recursion, the level increases by 1 (<strong>h.Level + 1<\/strong>), thus representing each employee&#8217;s position in the company hierarchy.<\/li>\n<\/ul>\n\n\n\n<p><strong>Final Selection:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The final query <strong>SELECT * FROM hierarchy<\/strong>; selects all records from the CTE <strong>hierarchy<\/strong>, resulting in a list of employees with their respective levels in the organizational structure.<\/li>\n<\/ul>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Consideration<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Recursive CTE is an effective way to handle hierarchical or recursive data in SQL, especially when the data structure is not flat but nested or multi-level.<br>&nbsp;<\/li>\n\n\n\n<li>This type of query can be particularly useful in corporate environments where the organizational structure is complex.<br>&nbsp;<\/li>\n\n\n\n<li>This type of query can be particularly useful in corporate environments where the organizational structure is complex.<\/li>\n<\/ul>\n\n\n\n<p>Please note that actual implementation and functionality may vary depending on the version of the iSeries operating system and DB2 database. It is always good practice to refer to the official IBM documentation for more precise and detailed information<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Common Table Expressions (CTE) in SQL on IBM iSeries (AS\/400) are a powerful and flexible tool for creating temporary, reusable queries, simplifying and improving the readability of complex SQL queries. Below are the articles in the CTE series (including this&#8230;<\/p>\n","protected":false},"author":3,"featured_media":4183,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_kadence_starter_templates_imported_post":false,"_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_kad_post_classname":"","footnotes":""},"categories":[143,141],"tags":[160,162,46],"class_list":["post-4270","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-more-in-depth","category-manage-as400-with-sql","tag-cte-common-table-expression-en","tag-recursive-cte","tag-sql"],"_links":{"self":[{"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/posts\/4270","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/comments?post=4270"}],"version-history":[{"count":3,"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/posts\/4270\/revisions"}],"predecessor-version":[{"id":4386,"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/posts\/4270\/revisions\/4386"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/media\/4183"}],"wp:attachment":[{"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/media?parent=4270"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/categories?post=4270"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillup.cloud\/en\/wp-json\/wp\/v2\/tags?post=4270"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}