title: MySQL - select first 10 bytes of a string
body: <p>Hello wise men &amp; women,</p>
  
  <p>How would you select the first x bytes of a string?</p>
  
  <p>The use case: I'm optimizing product description texts for upload to Amazon, and Amazon measures field lengths by bytes in utf8 (not latin1 as I stated earlier), not by characters. MySQL on the other hand, seems to operate character-based. (e.g., the function left() is character-based, not byte-based). The difference (using English, French, Spanish &amp; German) is roughly 10%, but it can vary widely.</p>
  
  <p>Some tests concerning a field with #bytes &lt; 250 (details: <a href="http://wiki.devliegendebrigade.nl/Format_inventarisbestanden_(Amazon)#Veldlengte" rel="nofollow noreferrer">http://wiki.devliegendebrigade.nl/Format_inventarisbestanden_(Amazon)#Veldlengte</a>):</p>
  
  <pre><code>OK, char_length: 248,   byte length latin1: 248,   byte length utf8: 248
  OK, char_length: 249,   byte length latin1: 249,   byte length utf8: 249
  OK, char_length: 249,   byte length latin1: 249,   byte length utf8: 249
  OK, char_length: 249,   byte length latin1: 249,   byte length utf8: 249
  
  Not OK, char_length: 250,   byte length latin1: 250,   byte length utf8: 250
  Not OK, char_length: 249,   byte length latin1: 249,   byte length utf8: 252
  Not OK, char_length: 248,   byte length latin1: 248,   byte length utf8: 252
  Not OK, char_length: 249,   byte length latin1: 249,   byte length utf8: 252
  Not OK, char_length: 249,   byte length latin1: 249,   byte length utf8: 257
  </code></pre>
  
  <p>Illustration:</p>
  
  <pre><code>set @tekst="Jantje zag € pruimen hangen";
  
  select
     char_length(@tekst),   # 27 characters
     length(@tekst);        # 29 bytes
  
  select left(@tekst, 15)   # Result: "Jantje zag € pr"
  
  # Ideally, I'm looking for something like this:
  
  select left_bytes_utf8(@tekst, 15)   # Result: "Jantje zag € "
  </code></pre>
  
  <p>One approach would maybe be through a sproc that iteratively calls itself, but I suspect there are more efficient solutions around.</p>
  
  <p>Thanks already &amp; regards, Jeroen</p>
  
  <p>P.s.: Edited the question: Changed 2x "latin1" to "utf8". It's actually a bit more confusing: Uploads should be in Latin1, but field sizes are measured in bytes using utf8</p>
  
  <p>P.p.s: Update: These uploads are for English, French, Spanish &amp; German Amazon-sites. Characters don't get more exotic than 'ø' (diameter), '€', 'è', 'é', 'ü' and 'ö'. All within Latin1-encoding, but multibyte in utf8.</p>