SELECT TOP 3 headline, news_id, body FROM ml_news WHERE date_added > cutoff_date ORDER by date_added DESC;
The problem is that where there only 3 valid rows that are within the acceptable date range, it still pulls back three records. If I remove the 'TOP 3' from the query, it then correctly only pulls the two valid records.
I'd like to use the TOP 3 to only pull three records when there are more than three but I want it to pull less than three when there are less than three valid records. So, does the TOP keyword cause a query to always pull that many records regardless of the where clause if there are at least that many records available?
If so, will setting the ROWCOUNT work the way I desire?
If not, any other ideas?
Thanks!
-DAGTANo, TOP does not trump a where clause. You WHERE clause and ORDER BY clause will provide you preliminary resultset, and your TOP will further filer those results.
For example, from Northwind:
SELECT TOP 5 * CustomerID FROM Customers --Returns 5 values,
SELECT TOP 5 * CustomerID FROM Customer WHERE CustomerID LIKE 'A%' --Returns 4 values|||Thanks for the reply.
If TOP does not trump the WHERE, can you see anything wrong with this?
SELECT TOP 3 headline, news_id, body FROM ml_news WHERE date_added > cutoff_date ORDER by date_added DESC;
When I run:
SELECT headline, news_id, body FROM ml_news WHERE date_added > cutoff_date ORDER by date_added DESC;
I get two results, but when I run the first query I get three results.
Thanks,
-DAGTA|||If those are the exact queries, and the second query (without the TOP) is only returning 2 rows, then the first query will only return 2 rows.
Are you absolutely certain that those are the EXACT 2 queries that are running?
Is cutoff_date truly a column in your table, or is there a parameter value being substituted in there when the query runs?
Terri
No comments:
Post a Comment