Practical Graph Structures in SQL Server and Azure SQL: Enabling Deeper Insights Using Highly Connected Data 1st Edition Louis Davidson download
Practical Graph Structures in SQL Server and Azure SQL: Enabling Deeper Insights Using Highly Connected Data 1st Edition Louis Davidson download
https://ebookmeta.com/product/practical-graph-structures-in-sql-
server-and-azure-sql-enabling-deeper-insights-using-highly-
connected-data-1st-edition-louis-davidson/
https://ebookmeta.com/product/pro-sql-server-2022-wait-
statistics-a-practical-guide-to-analyzing-performance-in-sql-
server-and-azure-sql-database-3rd-edition-thomas-larock-2/
https://ebookmeta.com/product/pro-sql-server-2022-wait-
statistics-a-practical-guide-to-analyzing-performance-in-sql-
server-and-azure-sql-database-3rd-edition-thomas-larock/
https://ebookmeta.com/product/a-cultural-history-of-hair-in-the-
age-of-enlightenment-1st-edition-margaret-k-powell-joseph-roach-
editors/
Heidegger in Russia and Eastern Europe Jeff Love
https://ebookmeta.com/product/heidegger-in-russia-and-eastern-
europe-jeff-love/
https://ebookmeta.com/product/diagnostics-and-gene-therapy-for-
human-genetic-disorders-k-v-chaitanya/
https://ebookmeta.com/product/psychology-themes-and-variations-
doug-mccann/
https://ebookmeta.com/product/upgrade-a-novel-2nd-edition-crouch-
blake/
https://ebookmeta.com/product/river-a-curvy-girl-mountain-man-
romance-matched-with-a-mountain-man-1st-edition-eve-london/
Explaining Cancer Finding Order in Disorder Anya
Plutynski
https://ebookmeta.com/product/explaining-cancer-finding-order-in-
disorder-anya-plutynski/
Practical Graph
Structures in
SQL Server and
Azure SQL
Enabling Deeper Insights Using
Highly Connected Data
—
Louis Davidson
Practical Graph
Structures in SQL Server
and Azure SQL
Enabling Deeper Insights Using
Highly Connected Data
Louis Davidson
Practical Graph Structures in SQL Server and Azure SQL: Enabling Deeper Insights
Using Highly Connected Data
Louis Davidson
Cleveland, TN, USA
Preface��������������������������������������������������������������������������������������������������������������������xv
v
Table of Contents
vi
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 235
vii
About the Author
Louis Davidson has been working with databases for
more than 25 years as a corporate database developer
and architect. He is now the editor for the Redgate Simple
Talk website. He has been a Microsoft MVP for 18 years. In
addition to this book on graphs in SQL Server, he has written
six editions of his general-purpose SQL Server database
design book (Apress) and has worked on multiple other
book projects over the years.
Louis has been active in speaking about database design and implementation at many
conferences over the past 25 years, including SQL PASS, SQL Rally, SQL Saturday events,
CA World, Music City Data, and the devLink Technical Conference. He has a bachelor’s
degree in computer science from the University of Tennessee at Chattanooga. For more
information, please visit his website at drsql.org.
ix
About the Technical Reviewer
Kathi Kellenberger is a Customer Success Engineer at
Redgate and a Data Platform MVP. She has worked with
SQL Server since 1998 and has authored, co-authored, or
tech reviewed over 20 technical books. Kathi is a longtime
volunteer at LaunchCode in St. Louis where she has taught
T-SQL in the LaunchCode Women + program. When Kathi
isn’t working, she enjoys spending time with family and
friends, cycling, singing, and climbing the stairs of tall
buildings.
xi
Acknowledgments
My wife, for suffering through yet another long and painful book writing process.
The Microsoft MVP Program for all the connections it has provided me to meet
wonderful, bizarrely smart people for 18 years. And my lead, Rie Merritt, for all she has
done for me through the years; amazing how we met so many years ago. Just meeting
Bob Ward and Conor Cunningham is thrill enough, and there have been hundreds
besides them.
Shreya Verma and Arvind Shyamsundar for their help over the past few years as I
attempted to do crazy things with the graph objects on my local personal computer.
Dr. David Rosenstein, who first got me interested in graphs in relational structures so
many years ago. Paul Nielsen for the talks we had on graph structures.
Kathi Kellenberger for tech editing this book. I appreciate the hard work!
All the doctors/medical professionals who kept me alive and kicking these past few
years. (If you want to know more, just ask, if you have a while to talk. There is a reason
this book took me over two years to write.)
My coworkers at CBN whom I left during the writing of this book. I hope the graph
objects I left you with are serving you nicely.
My new coworkers at Redgate. I have been a friend of Redgate (as well as a member
of Friends of Redgate) for many years, writing for them. My new manager and teammates
have been nothing but awesome.
Amber Davis, for giving me the chance to be a Dollywood Insider. Obviously being
a Dollywood insider has little to do with this book, but I just wanted to say it again
(which she may never see!) as I am writing the acknowledgements in the Dollywood
Dreammore lobby. I learned a lot from her that has been useful writing some of this book
and in my new job at Redgate as Simple-Talk editor.
xiii
Preface
I started working on my first book 23 years ago. It was on relational database design.
I had learned a little about graphs at that point from a class I took by Dr. David
Rozenshtein (his 1997 book The Essence of SQL : A Guide to Learning Most of SQL in the
Least Amount of Time was essential). His class was very influential and taught me a lot
about how to think about SQL problems. This was a really long time ago (clearly), but
in that same class, one of the sections was on trees in SQL Server. I was hooked on the
subject.
In my 2012 edition of my database design book, I started to include hierarchies
as one of the topics. In my latest book, that came out after SQL Server 2019 arrived, I
promised a book of SQL Graph. This book in your hands is the answer to that challenge.
This is my first programming-based book in many years. Usually I am more
interested in helping you shape a design, but in this case, I want to show you the
mechanics of building a graph database solution using SQL Server and leave it more
to you to decide what to do with it from there. Part of this is due to the newness and
relative complexity of the topic, but also because graphs are meant to be very flexible
structures…way more flexible than the standard relational databases.
The chapters of the book are as follows:
• Chapter 2: How graphs are implemented and the algorithms that are
used to process them. While the basic structure of the graph is really
simple, there is some value to understanding how graph structures
are built in coding and having some idea of what you will see in the
rest of the book.
xv
Preface
• Chapter 3: The syntax that Microsoft has implemented for use with
graph data stored in SQL Server tables is similar to what you probably
already know from working with relational tables, but it is so much
more. In this chapter, I teach you how to use the syntax provided by
Microsoft to query graph tables in interesting ways.
xvi
Preface
xvii
CHAPTER 1
Introduction to Graphs
With great power comes great responsibility.
--Voltaire (and Spider-Man’s Uncle Ben)
At its core, a graph data structure is simply a model representing the connection of one
thing to one other thing and then those things to even more other things. Essentially a
graph database formalizes a database based on many-to-many relationships as the core
relationship.
Everyone who has ever modeled a relational database will either have modeled
a graph purposefully or inadvertently because many-to-many relationships begin to
appear as you add more concepts to your data model. The vast difference you will see is
that relational implementations, ideally, are rigidly modeled.
The term frequently used to decide whether to model a many-to-many relationship
in a relational database or a graph structure is whether the data is highly connected.
With a graph database structure, you can connect many tables to many other tables
and query that structure in a different (yet quite similar) manner to how you query a
relational database.
There are many examples of graphs, but some of the most common examples you
probably hear about are
• Social networks, where you record the relationship from one person
to another
1
© Louis Davidson 2023
L. Davidson, Practical Graph Structures in SQL Server and Azure SQL,
https://doi.org/10.1007/978-1-4842-9459-8_1
Chapter 1 Introduction to Graphs
With this information, you can discover interesting things about an object based on
its relationships and similarity to relationships other entities have.
Possibly the most famous graph that most people will have heard of is the basis of the
parlor game “Six Degrees of Kevin Bacon.” This game suggests that everyone is no more
than six connections away from anyone else, including Kevin Bacon (and not just that
your favorite breakfast meat is bacon.)
The fact that graphs are very natural data structures does not make them easy
to work with. Because they are less rigid data structures than relational tables, the
flexibility makes them quite complex to work with (certainly in the database engine).
Graph objects can represent a very messy reality, and the more complex the data you
are modeling, the more complicated it is to work with. Of course, the reward for that
complexity is the solutions you create are often quite tremendous.
Like many computer science topics, graphs are also a fundamental mathematical
concept. Some of the insights you can get from the math of graphs will help once we
start analyzing data. So, to begin this book on graphs, I will provide a very cursory look
at some mathematical concepts as I define what a graph is and how it can be used in
software.
Note that the concepts in this chapter were gleaned from many resources and are
generally common knowledge. However, when I was searching for resources to read
for an introduction to the concepts of graphs, including mathematical proofs (none of
which will come up in this book, so no worries!) of such concepts, one was Introduction
to Graph Theory by Richard J. Trudeau from Dover Publications in 1993. It is far deeper
than this chapter and definitely more than you need to learn to code with SQL Server’s
graph database extensions, and mathematical proofs have always been my Kryptonite!
However, I highly recommend this as a place to ascend to the next level beyond what I
will show you.
This chapter will be a quick, high-level overview of the many topics you will find
in this book and many other sources, plus ideas you may wish to use in the graph table
objects I will cover once you start building objects. The book itself will be mostly focused
on very practical applications and how to write certain types of code, but I found that
knowing some of the graph fundamentals really helped me to envision what I was
attempting to accomplish.
2
Another Random Scribd Document
with Unrelated Content
THE FINESSE OBLIGATORY
This is an arbitrary finesse, which is often forced upon you,
when, unless the cards of a suit are in a certain position, there is no
possibility of winning. Perhaps the best way of defining the finesse
obligatory is to give an example showing the position as it most
frequently occurs:
“Z” is the dealer, and leads a low card to the king in dummy,
which wins the first trick. The suit is returned, the ace being marked
with “A.” If “A” holds both ace and knave, no matter how the dealer
plays, “A” must win two tricks. Unless the knave is in “B’s” hand, and
“A” holds the singleton ace, the adversary must win two tricks. The
dealer should, therefore, play his lowest card, not the queen.
WHEN TO TRUMP
If the adversary attempts to force your strong hand, it is usually
advisable to accept the force. Only in rare cases does it pay to allow
the opponent to continue the lead of his established suit.
At times you can afford to give the adversary one trick, knowing
that, on the next lead, your weak hand can take the “ruff.”
With two trumps against you it is often good play to discard
rather than to “ruff” with the commanding trump. But to gain by
your play, you should hold a certain entry card in the suit that the
adversary must lead.
With one trump against you, do not use your one remaining
trump until the leader’s partner is exhausted in the leader’s suit.
If the adversary leads a suit which you can trump in either hand,
the “ruff” should invariably be taken in the weak hand, and a discard
made in the strong one.
You are sometimes in a position to know that if you trump, your
adversary will overtrump. When the best card is led, it is usually
good play to trump immediately and if possible with a card which
will not unguard an honour in your own hand, but will force a high
card from the opponent. If a suit is led, of which you hold the
commanding card in the opposite hand, your best defence is to take
a discard, which will prevent the adversary from making a high card
later in the hand. If you can make no advantageous discard, your
best play is to trump, especially if the trumps in your combined
hands are in sequence, for, if the adversary wins the trick, his high
trump will probably make in any case.
OVERTRUMPING
It is only the experienced player who can resist the temptation to
overtrump. The beginner jumps at every trick without realising that
he can often gain by waiting. Overtrump when your hand is weak
and your trumps low; but, if overtrumping takes out your only high
card in the trump suit, especially if it is the commanding trump, it is
nearly always better to discard. Your winning trump is bound to
make, and it is better play to throw away a suit that you can ruff
later with one of your small trumps.
Frequently by overtrumping you make it easy for the adversary
to draw your remaining trumps, which, had you not weakened your
hand, he would be powerless to do. For instance, where you hold
the best and the fourth best trump, with the second and third best in
your adversary’s hand, should you overtrump, your adversary will, of
course, be in a position to catch your smaller trump, while by
refusing the trick you retain the extra trump and are enabled to
draw the adversary’s last trump.
RE-ENTRY CARDS
It is of little use to establish a suit unless it is possible to get the
lead in the hand that contains it; therefore, the reservation of a re-
entry card in the hand that has the long suit is of great importance.
A preferable re-entry is, of course, the last trump or trumps.
Arranging the trump lead so that the last round will be taken in
the desired hand is often a necessary precaution.
After the adversaries’ trumps are exhausted, you may be
compelled to place the lead in the opposite hand by an extra round
of trumps, and often it is necessary to trump with a high card,
saving the low trump to lead to the opposite hand.
It not infrequently happens that in order to get the lead in the
opposite hand, you are forced to trump your own commanding card.
FORCING DISCARDS
Should you find as dealer that you have a losing card and a
number of winning trumps, always lead the trumps to give the
adversaries a chance to make an error in discarding.
If the adversary holds the ace, dummy the king, and you a
singleton of a suit, your hand otherwise consisting of long trumps
and established cards, by first leading the singleton you may tempt
the second hand adversary to hold up the ace; while if you lead the
established cards, the adversaries can count your hand and will
make no such mistake.
Whenever you hold but six or seven cards of a suit in the
combined hands, endeavour to make your adversaries discard before
you indicate any strength. You will find that many times the discards
will necessarily benefit your hand.
With two or three remaining trumps in your hand, you should
lead at least two rounds of trumps before opening the suit of which
you have but six cards. An example of the situation is given below:
In this case hearts are trumps. The dealer is left with the two
remaining trumps, and holds in his combined hands but six clubs.
Should the clubs be led before the trump suit, the adversaries would
be left with the commanding club. The dealer should play his two
trumps to force discards from his opponents’ hands before he opens
the club suit.
With four or five long trumps, when but one other suit has been
opened, you will almost invariably gain tricks by forcing the
adversaries to discard. Any error they may make in selecting the suit
to protect may enable you to take tricks with cards that would
otherwise be valueless.
CHOICE OF SUITS
There is no rule so necessary to good play as that of retaining
the control of the shorter suits and playing to establish the longest
suit in the combined hands. Do not let the fact that your long suit
contains but a few high cards discourage you—the lead can entail
but small loss as the commanding cards would probably make in any
case.
When, as frequently happens, your combined hands contain two
suits of equal length, make a careful selection of the suit to be
played for.
When the ace of one suit and the king or the queen of the other
are against you, play for the suit of which the adversary holds the
ace. The ace must win, while the fuller information that comes later
in the hand may enable you to catch the king or queen by a finesse.
Then you can better afford to discard from a suit headed by the ace
than from a suit in which an honour must be protected. Moreover,
you deprive the adversary of a sure re-entry card.
With two suits of equal length, be careful not to play for one in a
hand that contains no re-entry card.
When you hold two suits of equal length, it is usually wise to play
for the suit that is exposed on the table and conceal the strength in
your own hand. In other words, don’t give the adversaries
unnecessary information.
In choosing between two suits select the one that will gain you
the greater number of tricks. For instance, when you hold two eight-
card suits, one divided five and three and the other four and four,
there are clearly more tricks to be made in the former.
Be cautious about playing for a suit of no more than seven cards,
for you will often find the remaining cards most unequally divided.
When you hold but six cards in the combined hands the balance of
strength is with the adversaries, one of whom must hold at least
four cards. Try to force your opponents to discard before you
indicate strength in six- or seven-card suits.
With two entire suits against you, you cannot afford to lose the
lead. Make what tricks you need to save the game and pin your
hope on successful finesses.
With but one suit against you, do not fear to establish your long
suit. It is not so dangerous to give up the lead when you hold a
protection in the suit led originally. The adversary, not knowing your
weakness, will probably return the original lead.
Should you wait to win the second trick with the ace, there is a
chance that your right-hand adversary will be exhausted in the suit,
and unless the original leader has two cards of re-entry his suit
cannot be made.
RE-ENTRY CARDS
Clear your long suit before you take out your card of re-entry is a
simple rule that is often violated. When you have made the “no-
trump” declaration, any possible re-entry in the dummy hand should
be used to bring in a suit or to lead a suit advantageously from the
weak hand. In fact, much of the success of a “no-trump” hand
depends on the dealers’ skill in saving and making re-entries in the
weaker hand.
A re-entry may be an ace or a three. It may be the master card
of your long suit or a guarded honour in the adversaries’ suit.
When you can win the original lead in either hand, consider well
the question of re-entries before you touch one of dummy’s cards.
Save all possible re-entry cards, remembering that often in order
to gain any material advantage from a finesse you must be in a
position to lead twice from the weak hand.
For instance, holding any one of the following combinations:
In order to make an entry card in the suit led originally, it may
occasionally be necessary to overtake a card played by the dummy.
When your long suit is blocked, try to establish an entry card
before you make the situation clear to the opponents. Otherwise
they will not allow you to enter and make your suit.
If you hold four cards of a suit in each hand, it may be possible
to obtain the lead twice in one hand. For instance, holding
If you lead the deuce and play the king, you have deprived
dummy of the only entry card in the suit. If, however, you lead the
eight, dummy’s seven will probably be the master card on the fourth
round. Such a re-entry is often of great assistance in opening the
next suit.
When you hold a nine-card suit divided five and four, it may be
necessary to use both the third and fourth rounds of the suits as re-
entries to lead another suit advantageously. This is a chance for
good play that is often overlooked in the pleasure of making a long
suit.
When dummy’s re-entry is a guarded king or queen, and you
have no means of knowing the position of the ace, try to establish
this re-entry by sacrificing a high card from your own hand.
In both of the examples given above, the dealer to make a re-
entry card for the dummy should sacrifice a high card from his hand.
UNBLOCKING
There is frequent necessity in the dealer’s play for ridding one
hand of high cards in order not to interrupt the lead of smaller cards
from the other hand. It is well to look ahead and prepare for this
contingency, for often in the middle of a hand you will quite
unexpectedly find that unblocking will enable you to make small
cards that the adversaries have made good by reckless discarding.
When you hold more cards of a suit in one hand than in the
other, you can invariably prevent blocking, if you lead or play the
high cards from the shorter hand. At times a suit may be unblocked
by discarding the winning card or cards from one hand, but the first
rule covers the majority of cases where there is necessity for
unblocking.