title: Select multiple entries in SQLite where multiple rows need to match the same condition (including AND, OR and NOT)
body: <p>I have a question regarding selecting in SQLite. I have given entries in a DB, where i need to select all rows which match my criterion. These criterion can be combined with AND, OR or NOT.</p>
  
  <p>For example, I have</p>
  
  <pre><code>     id  |  image  |  tag
      -----|---------|------
       21  |     21  |   35
       25  |    240  |   45
       36  |     21  |   40
       43  |    155  |   35
       56  |    243  |   35
       65  |    312  |   40
  </code></pre>
  
  <p>as data in my DB.</p>
  
  <p>What I want to do now, is to search for example for all entries with the tag 35. So far so easy (simple SELECT query).
  This gives me the images <em>21</em>, <em>155</em> and <em>243</em>.</p>
  
  <ol>
  <li><p>But now, I want every entry with the tag 35, BUT ONLY the ones, that have 40 as tag as well. This would be a <strong>AND</strong> constrain.</p>
  
  <ul>
  <li>This would result in only <em>21</em></li>
  </ul></li>
  <li><p>Besides from an <em>AND</em> constrain, I want also to search for entries, which have a tag of 35, BUT ALSO for the ones with a tag of 40 (an <strong>OR</strong> constrain).</p>
  
  <ul>
  <li>This should result in the images <em>21</em>, <em>155</em>, <em>243</em> and <em>312</em></li>
  </ul></li>
  <li><p>Furthermore, I want to exclude some entries with a <strong>NOT</strong> constrain. For example, I want every entry with a tag 35, BUT NOT the ones with a tag 40.</p>
  
  <ul>
  <li>The result of this would be the images <em>155</em> and <em>243</em></li>
  </ul></li>
  </ol>
  
  <p>How can I achieve this with SQLite-queries? I know, how to search for multiple criterion inside an entry, but I have at this time no idea, how to search over multiple entries with this constrains. I could solve this by selecting two different lists, and then <em>intersect</em>, <em>union</em> or <em>except</em> them with each other. But I think, there must be a better, direct way.</p>
  
  <p>I hope, this goal can be reached, without writing horribly long queries which contain thousands of sql-statements. ;)</p>
  
  <p>Does someone know, how to search for entries like described above?</p>
  
  <p>Thank you in advance for your help</p>
  
  <p>Kind regards
  Ramon</p>
  
  <p>(Please keep some of my English mistakes; there are free of charge ;))</p>