title: How to use Oracle ORDER BY and ROWNUM correctly?
body: <p>I am having a hard time converting stored procedures from SQL Server to Oracle to have our product compatible with it.</p>
  
  <p>I have queries which returns the most recent record of some tables, based on a timestamp :</p>
  
  <p><strong>SQL Server:</strong></p>
  
  <pre><code>SELECT TOP 1 *
  FROM RACEWAY_INPUT_LABO
  ORDER BY t_stamp DESC
  </code></pre>
  
  <p>=> That will returns me the most recent record</p>
  
  <p>But <strong>Oracle:</strong></p>
  
  <pre><code>SELECT *
  FROM raceway_input_labo 
  WHERE  rownum &lt;= 1
  ORDER BY t_stamp DESC
  </code></pre>
  
  <p>=> That will returns me the oldest record (probably depending on the index), regardless the <code>ORDER BY</code> statement!</p>
  
  <p>I encapsulated the Oracle query this way to match my requirements:</p>
  
  <pre><code>SELECT * 
  FROM 
      (SELECT *
       FROM raceway_input_labo 
       ORDER BY t_stamp DESC)
  WHERE  rownum &lt;= 1
  </code></pre>
  
  <p>and it works. But it sounds like a horrible hack to me, especially if I have a lot of records in the involved tables.</p>
  
  <p>What is the best way to achieve this ?</p>