Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I force SQL Server 2005 to run a join before the where?
    primarykey
    data
    text
    <p>I've got a SQL query that joins a pricing table to a table containing user-provided answers. My query is used to get the price based on the entered quantity. Below is my SQL statement:</p> <pre><code>SELECT JobQuestion.Value, Price.Min, Price.Max, Price.Amount FROM Price INNER JOIN JobQuestion ON Price.QuestionFK=JobQuestion.QuestionFK AND JobQuestion.JobFK=1 WHERE Price.Min &lt;= JobQuestion.Value AND Price.Max &gt;= JobQuestion.Value </code></pre> <p>The problem is SQL Server is running the where clause before the JOIN and it is throwing the error:</p> <blockquote> <p>Conversion failed when converting the varchar value 'TEST' to data type int.</p> </blockquote> <p>because it is doing the min and max comparisons before the join ('TEST' is a valid user entered value in the JobQuestion table, but should not be returned when JobQuestion is joined to Price). I believe SQL Server is choosing to run the WHERE because for some reason the parser thinks that would be a more efficient query. If i Just run</p> <pre><code>SELECT JobQuestion.Value, Price.Min, Price.Max, Price.Amount FROM Price INNER JOIN JobQuestion ON Price.QuestionFK=JobQuestion.QuestionFK AND JobQuestion.JobFK=1 </code></pre> <p>I get these results back: </p> <pre><code>500 1 500 272.00 500 501 1000 442.00 500 1001 2000 782.00 </code></pre> <p>So, adding the WHERE should filter out the last two and just return the first record. How do I force SQL to run the JOIN first or use another technique to filter out just the records I need?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload