opposite to top - sql

I'm working with sql server 2005.
I have a view which sorts its columns according to order date. I call:
SELECT TOP 1 [OrderDate]
FROM [ordersview]
to get the latest time. How do I get the earliest time?

SELECT TOP 1 OrderDate FROM ordersview ORDER BY OrderDate DESC

Also:
SELECT MIN(OrderDate) FROM ordersview

Use a descending ordering:
select top 1 OrderDate from ordersview order by OrderDate desc

I think,
this is little bit tricky question.
Every body will say for white is opposite black.
And for first is it last.
but when u are not specifying initial order
what is really the first.
I think it is internal/vendor specific thing.
So both answers are right ,but actually not answering really your question.
I'm not really mssql-guy but think that your select will return random
row (maybe depending on inserting sequence , or same internal db thing like rowId).
And what is opposite for random ?
One more thing is that, ordering is pretty demanding(resource/performance) function ,
for such thing u should have index on column.
And basically when u are doing select like that u should thing about real paging
not only one item .
But then the result will have different order then original one ( so ... )

Related

getting same top 1 result in sql server

I have this query:
SELECT
IT_approvaldate
FROM
t_item
WHERE
IT_certID_fk_ind = (SELECT DISTINCT TOP 1 IT_certID_fk_ind
FROM t_item
WHERE IT_rfileID_fk = '4876')
ORDER BY
IT_typesort
Result when running this query:
I need get top 1 result. (2013-04-27 00:00:00) problem is when I select top 1, getting 2nd result.
I believe reason for that order by column value same in those two result.
please see below,
However I need get only IT_approvaldate column top 1 as result of my query.
How can I do this? Can anyone help me to solve this?
Hi use below query and check
SELECT IT_approvaldate FROM t_item WHERE IT_certID_fk_ind =(SELECT DISTINCT top 1 IT_certID_fk_ind FROM t_item WHERE IT_rfileID_fk ='4876' ) and IT_approvaldate is not null ORDER BY IT_typesort
This will remove null values from the result
If you want NULL to be the last value in the sorted list you can use ISNULL in ORDER BY clause to replace NULL by MAX value of DATETIME
Below code might help:
SELECT TOP 1 IT_approvaldate
FROM t_item
WHERE IT_certID_fk_ind = (SELECT DISTINCT top 1 IT_certID_fk_ind FROM t_item WHERE IT_rfileID_fk ='4876' )
ORDER BY IT_typesort ASC, ISNULL(IT_approvaldate,'12-31-9999 23:59:59') ASC;
TSQL Select queries are not inherently deterministic. You must add a tie-breaker or by another row that is not.
The theory is SQL Server will not presume that the NULL value is greater or lesser than your row, and because your select statement is not logically implemented until after your HAVING clause, the order depends on how the database is setup.
Understand that SQL Server may not necessarily choose the same path twice unless it thinks it is absolutely better. This is the reason for the ORDER BY clause, which will treat NULLs consistently (assuming there is a unique grouping).
UPDATE:
It seemed a good idea to add a link to MSDN's documentation on the ORDER BY. Truly, it is good practice to start from the Standard/MSDN. ORDER BY Clause - MSDN

sql query push certain records to top

Im looping through forum topics with a mySQL query, but id like records with the field sticky being 1 to always be pushed to the top, or first, then it looping through the rest.
How could I do this?
At the moment they are ordered like ORDER BY last_post DESC (last_post being a datetime)
I think ORDER BY sticky DESC, last_post DESC should work.

SQL Simple ORDER BY

I'm new to SQL and I don't think this question should be hard to answer. I have a high-score table for a game that contains the columns name, score, and rank. I want to know how I can order the table by descending order each time a new score is added so the table can always stay ordered by score.
I know this is the wrong way of doing this, but I hope this makes my point kind of clearer.
UPDATE `HSTable`.`Highscores` ORDER BY `Highscores`.`score` DESC;
What is the correct way of approaching this?
One more thing, is there a way I can set it so that the ranking value always stays where it's suppose to be from the SQL, for example, 1st place is always at the top regardless the score?
generally we use order by while fetching data from table
so we use
SELECT * FROM `HSTable` ORDER BY `score` DESC
Use a ranking function like RANK or DENSE_RANK to rank the results. For better performance you can add a clustered index that starts with score descending.
You can get ordered results using SELECT clause:
SELECT * FROM `HSTable` ORDER BY `score` DESC
I don't believe the order of the data in your database table should really matter because when you query the data you can sort it any which way you would like. What is the reason why you want to have the data stored in the database in the correct order?
That is not the correct way to select records in SQL. Use this instead:
SELECT * FROM `tablename` ORDER BY `id` DESC

Running a query without GROUP BY and aggregation functions

Let's say that you are limited to use only this syntax (you can't use aggregation functions like MAX or MIN, and neither you can't use GROUP BY clauses; please don't ask me why):
{SQL query} ::= SELECT [DISTINCT | ALL] [TOP {integer}]
{select_list}
FROM {table_reference}
[WHERE {search_condition}]
[ORDER BY {orderby} { ',' {orderby} } ]
Let's say that we have an ITEM table, where the identifier is called ITEM_ID. For a given ITEM_ID you could have many rows with the same ITEM_ID but different SHIP_DATE. How would you write a query to return only the ITEMS with the most recent SHIP_DATE given the previous syntax?
I already tried using TOP N (to retrieve the first row in the result set) combined with an ORDER BY (to sort from the max SHIP_DATE to the min SHIP_DATE). Any ideas or suggestions?
What I tried is something like this:
SELECT TOP N * FROM ITEM WHERE ITEM_ID='X' ORDER BY SHIP_DATE DESC
Actually the previous query seems to be working, but I'm wondering if there is a better way to do it.
This is not homework, I need to create a query using the supported FileNet P8 syntax: http://publib.boulder.ibm.com/infocenter/p8docs/v4r5m1/index.jsp?topic=/com.ibm.p8.doc/developer_help/content_engine_api/guide/query_sql_syntax_ref.htm
Assuming that ITEM.ship_date doesn't fall on the same date for any other ITEM record:
SELECT TOP x
i.item_id,
i.ship_date
FROM ITEM i
ORDER BY i.ship_date DESC
...where x is the number of unique/distinct ITEM.item_id records. How'd you'd get that without being able to use COUNT...
You have to use ORDER BY i.ship_date DESC in order to have the most recent ship_date records at the top of the result set.
You just want the one item with the absolute latest ship_date? If so then your query is exactly right:
SELECT TOP 1 * FROM ITEM WHERE ITEM_ID='X' ORDER BY SHIP_DATE DESC
The only problem might be that if SHIP_DATE is something coarse (like a calendar date), rather than fine (like a datetime) then you could have ties. In that case, you database engine is just going to pick one of them and you won't know in advance how it will figure that out. So you might want to consider adding another column to your order by just to make it deterministic.
select distinct item_id from item
where ship_date =
(select top 1 ship_date from item order by ship_date desc)
Is your syntax as strict as it seems there, or can distinct versus all be specified on a per-column basis? For instance, could you do something like this:
SELECT ship_date, DISTINCT item_id FROM tablename ORDER BY ship_date;
and if so, does that work?
If it doesn't, are you able to nest queries? (i.e. use a subquery in place of table_reference)

How can I order entries in a UNION without ORDER BY?

How can I be sure that my result set will have a first and b second? It would help me to solve a tricky ordering problem.
Here is a simplified example of what I'm doing:
SELECT a FROM A LIMIT 1
UNION
SELECT b FROM B LIMIT 1;
SELECT col
FROM
(
SELECT a col, 0 ordinal FROM A LIMIT 1
UNION ALL
SELECT b, 1 FROM B LIMIT 1
) t
ORDER BY ordinal
I don't think order is guaranteed, at least not across all DBMS.
What I've done in the past to control the ordering in UNIONs is:
(SELECT a, 0 AS Foo FROM A LIMIT 1)
UNION
(SELECT b, 1 AS Foo FROM B LIMIT 1)
ORDER BY Foo
Your result set with UNION will eliminate distinct values.
I can't find any proof in documentation, but from 10 years experience I can tell that UNION ALL does preserve order, at least in Oracle.
Do not rely on this, however, if you're building a nuclear plant or something like that.
No, the order of results in a SQL query is controlled only by the ORDER BY clause. It may be that you happen to see ordered results without an ORDER BY clause in some situation, but that is by chance (e.g. a side-effect of the optimiser's current query plan) and not guaranteed.
What is the tricky ordering problem?
I know for Oracle there is no way to guarantee which will come out first without an order by. The problem is if you try it it may come out in the correct order even for most of the times you run it. But as soon as you rely on it in production, it will come out wrong.
I would have thought not, since the database would most likely need to do an ORDER BY in order to the UNION.
UNION ALL might behave differently, but YMMV.
The short answer is yes, you will get A then B.