title: Unpack tuple within SQL statement
body: <p>I am using <code>Python</code> and <code>PyMySQL</code>. I want to fetch a number of items from a  MySQL database according to their ids:</p>
  
  <pre><code>items_ids = tuple([3, 2])
  sql = f"SELECT * FROM items WHERE item_id IN {items_ids};"
  </code></pre>
  
  <p>I am using the formatted string literals (<code>f" "</code>, <a href="https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498" rel="nofollow noreferrer">https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498</a>) to evaluate the tuple inside the SQL statement.</p>
  
  <p>However,I want to get back the items in the order specified by the tuple so firstly the item with <code>item_id = 3</code> and then the item with <code>item_id = 2</code>. To accomplish this I have to use the <code>ORDER BY FIELD</code> clause (see also here: <a href="https://stackoverflow.com/questions/396748/ordering-by-the-order-of-values-in-a-sql-in-clause?utm_medium=organic&amp;utm_source=google_rich_qa&amp;utm_campaign=google_rich_qa">Ordering by the order of values in a SQL IN() clause</a>). </p>
  
  <p>But if I write something like this:</p>
  
  <pre><code>items_ids = tuple([3, 2])
  sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{(item_id,) + items_ids};"
  </code></pre>
  
  <p>then <code>item_id</code> in the <code>ORDER BY FIELD</code> clause is considered as an undeclared python variable</p>
  
  <p>and if I write something like this:</p>
  
  <pre><code>items_ids = tuple([3, 2])
  sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{('item_id',) + items_ids};"
  </code></pre>
  
  <p>then <code>item_id</code> in the <code>ORDER BY FIELD</code> clause is considered as a string and not as a SQL variable and in this case <code>ORDER BY FIELD</code> does not do anything. </p>
  
  <p><strong>How can I evaluate the tuple <code>(item_id,) + items_ids</code> in the SQL statement by maintaining <code>item_id</code> as a SQL variable in the <code>ORDER BY FIELD</code> clause?</strong></p>
  
  <p>Obviously I can sort the items after they have returned from the database according to <code>items_ids</code> and without bothering so much with MySQL but I was just wondering how to do this.</p>