title: Write native SQL in Core Data
body: <p>I need to write a native SQL Query while I'm using Core Data in my project. I really need to do that, since I'm using <code>NSPredicate</code> right now and it's not efficient enough (in just one single case). I just need to write a couple of subqueries and joins to fetch a big number of rows and sort them by a special field. In particular, I need to sort it by the sum of values of their child-entites. Right now I'm fetching everything using NSPredicate and then I'm sorting my result (array) manually, but this just takes too long since there are many thousands of results. </p>
  
  <p>Please correct me if I'm wrong, but I'm pretty sure this can't be a huge challenge, since there's a way of using sqlite in iOS applications.</p>
  
  <p>It would be awesome if someone could guide me into the right direction.
  Thanks in advance.</p>
  
  <p><b>EDIT:</b>
  Let me explain what I'm doing.
  Here's my Coredata model:</p>
  
  <p><img src="https://i.stack.imgur.com/uw0sc.png" alt="Coredata model"></p>
  
  <p>And here's how my result looks on the iPad:
  <img src="https://i.stack.imgur.com/H1CN0.png" alt="iPad screenshot"></p>
  
  <p>I'm showing a table with one row per customer, where every customer has an amount of sales he made from January to June 2012 (Last) AND 2013 (Curr). Next to the <code>Curr</code> there's the variance between those two values. The same thing for gross margin and coverage ratio.</p>
  
  <p>Every customer is saved in the <code>Kunde</code> table and every <code>Kunde</code> has a couple of <code>PbsRow</code>s. <code>PbsRow</code> actually holds the sum of sales amounts per month.</p>
  
  <p>So what I'm doing in order to show these results, is to fetch all the <code>PbsRows</code> between January and June 2013 and then do this: </p>
  
  <pre><code>self.kunden = [NSMutableOrderedSet orderedSetWithArray:[pbsRows valueForKeyPath:@"kunde"]];
  </code></pre>
  
  <p>Now I have all customers (Kunde) which have records between January and June 2013. 
  Then I'm using a for loop to calculate the sum for each single customer.</p>
  
  <p>The idea is to get the amounts of sales of the current year and compare them to the last year. 
  The bad thing is that there are a lot of customers and the <code>for</code>-loop just takes very long :-(</p>