Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For a one-to-many relationship, where the “many” has a small number of known values, relationships can be stored as bitmasks in the parent table as an integer, replacing the need for an additional table.</p> <p>Say we have a table Person and we’d like to know how many Continents a person has visited. We’d start by assigning each Continent an “orthogonal” bit value. In C#, an enum is a good choice for this:</p> <pre><code>[Flags] public enum JobAdvertisingRegion { NorthAmerica = 1, // or 1 &lt;&lt; 0 SouthAmerica = 2, // 1 &lt;&lt; 1 Europe = 4, // 1 &lt;&lt; 2 Asia = 8, // 1 &lt;&lt; 3 Africa = = 16, // 1 &lt;&lt; 4 Australia = 32, // 1 &lt;&lt; 5 Anarctica = 64 // 1 &lt;&lt; 6 } </code></pre> <p>The Persons table could then simply have a int column called Contintents. To indicate that a Person has visited Europe and Asia:</p> <pre><code>UPDATE Persons SET Continents = (4 + 8) WHERE Id = whatever </code></pre> <p>To search for Persons who have visited Antarctica, we use bitwise math:</p> <pre><code>SELECT * FROM Persons WHERE Continents &amp; 64 = 64 </code></pre> <p>To search for Persons who have visited both Africa and Asia:</p> <pre><code>SELECT * FROM Persons WHERE Continents &amp; (16 + 8) = (16 + 8) </code></pre> <p>To search for Persons who have visited either Australia or South America:</p> <pre><code>SELECT * FROM Persons WHERE Continents &amp; (32 + 2) != 0 </code></pre> <p>One downside is that, while integer columns are indexable in SQL, their bit components are not. Some optimizations to get around this, for the above queries:</p> <pre><code>SELECT * FROM Persons WHERE Continents &amp; 64 = 64 AND Continents &gt;= 64 SELECT * FROM Persons WHERE Continents &amp; (16 + 8) = (16 + 8) AND Continents &gt;= (16 + 8) SELECT * FROM Persons WHERE Continents &amp; (32 + 2) != 0 AND Continents &gt;= 2 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload