title: How to efficiently SQL select newest entries from a MySQL database?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price">SQL Query to get latest price</a>  </p>
  </blockquote>
  
  
  
  <p>I have a database containing stock price history. I want to select most recent prices for every stock that is listed. I know PostreSQL has a <a href="https://stackoverflow.com/questions/25224/joining-latest-of-various-usermetadata-tags-to-user-rows#27159">DISTINCT ON</a> statement that would suit ideally here.</p>
  
  <p>Table columns are <code>name</code>, <code>closingPrice</code> and <code>date</code>; <code>name</code> and <code>date</code> together form a unique index.</p>
  
  <p>The <em>easiest</em> (and very uneffective) way is</p>
  
  <pre><code>SELECT * FROM stockPrices s
  WHERE s.date =
  (SELECT MAX(date) FROM stockPrices si WHERE si.name = s.name);
  </code></pre>
  
  <p>Much better approach I found is</p>
  
  <pre><code>SELECT *
  FROM stockPrices s JOIN (
    SELECT name, MAX(date) AS date
    FROM stockPrices si
    GROUP BY name
  ) lastEntry ON s.name = lastEntry.name AND s.date = lastEntry.date;
  </code></pre>
  
  <p>What would be an efficient way to do this? What indexes should I create?</p>
  
  <blockquote>
    <p>duplicate of:<br>
    <a href="https://stackoverflow.com/questions/49404/sql-query-to-get-latest-price">SQL Query to get latest price</a></p>
  </blockquote>