Multiple LIKE clauses in a single WHERE statement

I recently came up against a scenario where, in amongst a number of other filters, I had to deal with a couple of wildcard criteria. As there is no option to have multiple LIKE clauses in native SQL, such as WHERE Field LIKE IN (’%Option1%’,'%Option2%’), I feared I was stuck with having to duplicate my WHERE clause in its entirety for each LIKE operation – until I found this cunning bit of code (from the thread here):

/* Apply Multiple LIKE clauses in a single WHERE clause */
SELECT *
 
FROM [AdventureWorks].[Person].[Contact]
 
WHERE CASE
  WHEN FirstName LIKE ‘Gusta%’ THEN 1
  WHEN FirstName LIKE ‘Cath%’ THEN 1
  END = 1

An elegant solution!

Handling Recursive Hierarchies in SQL Server

I was recently posed a question on handling recursive hierarchies which left me completely stumped, so I had to find a good solution to it. This post will cover all that, but first -

…what is a Recursive Hierarchy?

A recursive hierarchy is a one where children of parent members can be parents themselves, such as an Organisation chart, or chart of accounts. A simple example is shown below, where the node A2 is both a child of A1 and a parent of A4 & A5:

b

Fig 1: A Simple Recursive Hierarchy

Handling these within a database environment can be difficult because the number of parent / child relationships (aka “Depth”) can vary, so it is impossible to create a fixed width table to accomodate them for their future growth. Consequently, most operational systems store these in a simple two level tabel which records the parent / child relationships only, as shown below.

b

Fig 2: The Parent Child Table

From the operation systems point of view this is usually all it needs to function as they usually only need to know the relationship one step in either direction, which this table satisfies. Determining the parent of A2 or the children of A2 can be determined with a simple SELECT query.

How do they cause difficulties for reporting?

The difficulty faced in a SQL based reporting situation is that you cannot easily determine relationships between parents and grandchildren, great-grandchildren, etc. without nesting queries. The specific problem with this is that you cannot know from a parent exactly how many levels of children lie below it. Vice versa, you cannot know how many levels of parents a child record has. Consequently you cannot know in advance how deep to nest your queries. From a practical standpoint as well, these relationships could be hundreds or thousands deep, and writing that query can pose problems in itself, even if you know there are exactly 1,567 levels in it!

The problem I was posed was superficially simple – if every level of such a hierarchy can have values, such as laid out below, how do you determine the aggregate value for a given parent and all its children?

b

Fig 3: The Values Table

For a tiny example such as this, nested queries is an option – your sub selects would only have to go two deep at most. But what if the depth changed, or ran into the tens or hundreds? Also, how do you create the generic query for any node in the tree? And for added complexity, what if there are multiple trees in the hierarchy? The problems are not trivial to resolve, but I have located two good solutions.

Solution 1: The LR Method

The first, and in my view most elegant, comes from Michael J. Kamfonas in his article “Recursive Hierarchies: The Relational Taboo!“, which I strongly recommend reading to fully grasp the solution. His solution is to pre-number each node in the hierarchy with a value that on the Left forms a lower bound and on the Right an upper bound that allows you to select all nodes under it using a BETWEEN clause. A picture explains this concept clearly, with the L Value in Pink and the R Value in Green:

b

Fig 4: The LR Method applied to a Recursive Hierachy

So as you can see for node A2, the range between its L Value of 2 and R Value of 7 encompasses the L Values of all its children (A4 with 3, and A5 with 5). So to select all the nodes below A2 there is no need to resolve any relationships, you can simply select all children nodes based on their L values.

In database terms, the output looks like this:

b

Fig 5: The L R Table

So, if I wanted to know the sum of all the values below any given node, I would use this pseudo SQL:

SELECT SUM(Value)
FROM ValuesTable v

LEFT JOIN LR_Table lr
ON v.Node = lr.Node

WHERE lr.L_Value
BETWEEN (SELECT L_Value FROM LRTable WHERE Node = ‘ParentNode’)
AND (SELECT R_Value FROM LRTable WHERE Node = ‘ParentNode’)

To demonstrate this in practice, I have created some SQL which creates a recursive hierarchy table as in Fig 2, a values table as in Fig 3 and an LR table as in Fig 5. The LR table is then populated with L/R values by a simple cursor which logs its activity to the message window so you can see what it is doing. I don’t think it will win any prizes for efficiency, but it works! The code sample then closes out with a T-SQL sample which calculates the sum of all it and its childrens values. Download the sample code here.

Solution 2: Kimball Helper Table

Unsurprisingly, Ralph Kimball also has an approach. His involves the use of a “Helper Table” which he describes in his article “Helper tables handle dimensions with complex hierarchies“. As for solution 1 I advise reading the article as I will only go into the practical implications of his approach.

The Kimball approach requires creating a table that stores every path from each node in the tree to itself and to every node below it. Looking at the example below, this means creating one row per node, plus one row for each path down the tree for each parent node to all of its children.

b

Fig 6: Paths to capture in a Helper Table

The helper table also includes a few extra flags – the Level Depth from the top parent, and flags for the top level parent nodes (Topmost) and lowest level children nodes (Lowest). The output table ends up looking like this:

b

Fig 7: The Kimball Helper Table

This makes navigating relative positions in the hierarchy simpler, and allows the answering of the original question easy as all that is required is to join on the Values table to the Helper table for the given parent node, as below:

SELECT SUM(Value)
FROM HelperTable r

LEFT JOIN ValuesTable v
ON r.ChildNode = v.Node

WHERE ParentNode = ‘ParentNode’

However – as you will see from my sample code – populating these tables is much more complex. The sample code creates and populates the recursive hierarchy table as in Fig 2, a values table as in Fig 3 and an Helper table as in Fig 7. The process of populating the table is a mix of cursors, inserts and updates and is much trickier to get right than the LR method, because of the higher demands for information, such as Depth from Parent.

Recursive Hierarchies – no problem!

Above are two solid approaches to the Recursive Hierarchy problem. The code samples provided should help you get started on understanding how to handle these scenarios when trying to report against them in Database based reporting scenarios such as in SSRS. SSAS and other OLAP based reporting handles all of this in its stride however, as described here, for example.

If you find issues with my code samples or see improvements, i’d love to know about them, so please keep me posted about your experiences with them.

Finally, I will close out with the old joke on the subject:

To truly understand recursion,

you must first understand recursion

10 Essential SQL Tips for Developers

10 Essential SQL Tips for Developers courtesy of Eric Shafer – covers some important basics – if you scan through that list and don’t understand all 10 points, make an effort to ensure you do – they aren’t mind boggling obscurities but important basics.

ti7mfkj6sr

Count the number of rows in every Table in a Database in no time!

Here is a piece of T-SQL code that uses DMV’s (Dynamic Management Views) to give an approximate row count of every table in your database in virtually no time at all. Bear in mind it is running off collected statistics so won’t always be 100% accurate – but it’s far quicker than doing a Count(*) on a table by table basis when you just need a rough idea when doing sizing. In case you don’t know what DMV’s there are, go poke around in SSMS – [Database] > Views > System Views and see what’s there. Anyway, the code:

SELECT    s.[Name] as [Schema]
,        t.[name] as [Table]
,        SUM(p.rows) as [RowCount]

FROM sys.schemas s
LEFT JOIN sys.tables t
ON s.schema_id = t.schema_id

LEFT JOIN sys.partitions p
ON t.object_id = p.object_id

LEFT JOIN  sys.allocation_units a
ON  p.partition_id = a.container_id

WHERE    p.index_id  in(0,1) -- 0 heap table , 1 table with clustered index
AND        p.rows is not null
AND        a.type = 1  -- row-data only , not LOB

GROUP BY s.[Name], t.[name]
ORDER BY 1,2

For a very swift explanation – sys.schemas and sys.tables list the schemas and tables in the database, so joining these together on schema_id gives a list of all tables by schema in the database. Adding on sys.partitions then pulls in the partitions associated with each table, and finally sys.allocation_units pulls in the allocation units, which i’m not quite sure what they are – the guts of this query were pulled from another blog which I embarrasingly can’t trace back to now.

I’m no expert on DMV’s so if you have any views on the quality of this query – please leave a comment with your thoughts.