title: Are these SQL statements equal?
body: <p>I have the following table:</p>
  
  <pre><code>| sample_id (varchar, unique) | field1 (int) | field2 (int) | ... 
  --------------------------------------------------------------------
  | 9b7acb476c4ab04c7ddbc       | 100          | 56           | ...
  | a2e4df67e98ccaf088abf       | 23           | NULL         | ...
  | fcbe9cecd6b96cba7c6ee       | NULL         | 43           | ...
  ...
  </code></pre>
  
  <p>I have the following code created by a prior user to query two fields at the same time and getting a random subset of the rows:</p>
  
  <pre><code>SELECT   sample_id, field1, field2
  FROM     samples
  WHERE    field1 != NULL
  UNION ALL
  SELECT   sample_id, field1, field2
  FROM     samples
  WHERE    field2 != NULL
  ORDER BY RAND()
  LIMIT    1000
  </code></pre>
  
  <p>I thought of optimizing the code by rewriting the query as:</p>
  
  <pre><code>SELECT   sample_id, field1, field2
  FROM     samples
  WHERE    field1 != NULL
  OR       field2 != NULL
  ORDER BY RAND()
  LIMIT    1000
  </code></pre>
  
  <p>Based on some documentation I read <a href="http://www.techonthenet.com/sql/union_all.php" rel="nofollow">here</a> it seems that both the queries are equivalent but I'm not sure how the <code>ORDER BY RAND()</code> line would be handled in the query. Is it only applied to the second query (i.e. the query after the <code>UNION ALL</code>)?</p>