SELECT TOP 1 result from table ordered by field - sql

I have a table like this :
id package start_date option
1 342323 2012-02-02 1
2 3423333 2012-02-06 1
3 552234 2012-02-14 2
I want to select only the (top 1) row that has the minimum start_date.
I tried where start_date = MIN(start_date) but it's not working.
I'm using SQL Server 2008.

select top 1 * from table
order by start_date

try:
where start_date = (select min(start_date) from yourtable)

SELECT * FROM myTable
ORDER BY start_date ASC
LIMIT 1

SELECT * from Yourtable
WHERE start_date = (SELECT (Min(yt1.Start_Date) FROM YourTable as yt1)

For MSSQL
select top 1 * from your_table order by start_date asc

For Sql server
select top 1 * from tbl_name order by start_date
For Mysql
select * from tbl_name order by start_date asc limit 1

You could also use:
;With top_record as
(
SELECt *
,row_number() OVER (order by start_date ASC) as row
FROM yourtable
)
SELECT * from top_record WHERE row = 1
This would then give you the flexibility to determine what to do with ties by using DENSE_RANK / RANK instead of ROW_NUMBER()

This SQL Server-specific query should get you the data you want. Try using this:
select top 1 * from tbl_name order by start_date asc

Related

fetch records from the column with the max date column

For the below table
ID DATE FIELD1 FIELD2 FIELD4
123456 01.07.2014 00:00:00 EMPLOYER GROUPS TMC SELECT CARE HMO
123789 01.07.2017 00:00:00 EMPLOYER GROUPS MQC SELECT CARE HMO
How to select only one row that have max(date)? i.e. 01.07.2017
select *
from theTable
where Date = (select max(date) from theTable)
Should do it. Add a top 1 if multiple rows have the same date.
In Oracle 12+, you can use:
select t.*
from t
order by date desc
fetch first 1 row only;
In earlier versions, you an use a subquery:
select t.*
from (select t.*
from t
order by date desc
) t
where rownum = 1;
If you need more than one record with the same maximum date:
select t.*
from t
where t.date = (select max(t2.date) from t);
For tsql / SQL Server you can use the below
DECLARE #max_date datetime;
SELECT #max_date = max(DATE) from table_name;
SELECT TOP 1 * FROM table_name WHERE DATE = #max_date;
The 'TOP 1' makes sure you only receive 1 row.
Which row this is will arbitrary though, unless you add an 'ORDER BY' statement in your query.
Alternatively
dense_rank() function may be used as :
select dt, ID
from
(
select dense_rank() over (order by "Date" desc) as dr,
"Date" as dt,
ID
from tab
)
where dr = 1;
or if you're sure about there's no tie(for the column "Date"), even row_number() function may be used :
select dt, ID
from
(
select row_number() over (order by "Date" desc) as rn,
"Date" as dt,
ID
from tab
)
where rn = 1;
SQL Fiddle Demo

Get first record by latest date

Please help complete this sql string? I want to get 1st record from table 1 where createddate = most recent/latest.
Select TOP 1 * From Table1 Where CreateDate = "latest date??"
the other way to do it:
select * From Table1 order by CreateDate DESC Limit 1
Or without TOP, using subquery:
Select *
From Table1
Where CreateDate = (select max(CreateDate) from Table1)
;
use order by
Select TOP 1 * From Table1 order by createddate desc

get id value when max is on other column

is this the best way to get the id value of the most recent date?
table1
id,entrydate
1,8/23/2012
2,8/24/2012
3,8/23/2012
select id from table1 where entrydate = ( select MAX(entrydate) from table1 )
Assuming you're using SQL-Server, you can use ORDER BY and then take one row:
SELECT TOP 1 id
FROM table
ORDER BY entrydate DESC
In MySql it is LIMIT:
SELECT id
FROM table
ORDER BY entrydate DESC
LIMIT 1
In Oracle:
SELECT id
FROM (SELECT id FROM table ORDER BY entrydate DESC)
WHERE ROWNUM = 1
You already have a good way there. I'd watch out for ties:
select top id from table1 where entrydate = ( select MAX(entrydate) from table1 )
This, of course, assuming you are using SQL Server.
SELECT id FROM table1 ORDER BY entrydate DESC LIMIT 1
You should be able to do SELECT id FROM table1 ORDER BY entrydate DESC LIMIT 1
Not exactly, you want to do this:
For SQL Server:
SELECT TOP 1 id, MAX(entrydate) FROM table1 GROUP BY id
For MySQL:
SELECT id, MAX(entrydate) FROM table1 GROUP BY id LIMIT 1

SQL Query to Select the 'Next' record (similar to First or Top N)

I need to do a query to return the next (or prev) record if a certain record is not present. For instance consider the following table:
ID (primary key) value
1 John
3 Bob
9 Mike
10 Tom.
I'd like to query a record that has id 7 or greater if 7 is not present.
My questions are,
Are these type of queries possible with SQL?
What are such queries called in the DB world?
Thanks!
Yes, it's possible, but implementation will depend on your RDBMS.
Here's what it looks like in MySQL, PostgreSQL and SQLite:
select ID, value
from YourTable
where id >= 7
order by id
limit 1
In MS SQL-Server, Sybase and MS-Access:
select top 1 ID, value
from YourTable
where id >= 7
order by id
In Oracle:
select * from (
select ID, value
from YourTable
where id >= 7
order by id
)
where rownum = 1
In Firebird and Informix:
select first 1 ID, value
from YourTable
where id >= 7
order by id
In DB/2 (this syntax is in SQL-2008 standard):
select id, value
from YourTable
where id >= 7
order by id
fetch first 1 rows only
In those RDBMS that have "window" functions (in SQL-2003 standard):
select ID, Value
from (
select
ROW_NUMBER() OVER (ORDER BY id) as rownumber,
Id, Value
from YourTable
where id >= 7
) as tmp --- remove the "as" for Oracle
where rownumber = 1
And if you are not sure which RDBMS you have:
select ID, value
from YourTable
where id =
( select min(id)
from YourTable
where id >= 7
)
Try this for MS-SQL:
SELECT TOP 1
id, value
FROM your_table
WHERE id >= 7
ORDER BY id
or for MySql
SELECT id, value
FROM your_table
WHERE id >= 7
ORDER BY id
LIMIT 0,1
I would simply do it like this:
select top 1 * from myTable where id >=7
order by id
implementation of the top 1 part is T-SQL (MSSQL/Sybase), other implementations vary but it is always possible (mysql/postgre LIMIT 1, oracle rownum = 1)
select top 1 * from Persons where Id >= #Id order by Id

Select top and bottom rows

I'm using SQL Server 2005 and I'm trying to achieve something like this:
I want to get the first x rows and the last x rows in the same select statement.
SELECT TOP(5) BOTTOM(5)
Of course BOTTOM does not exist, so I need another solution. I believe there is an easy and elegant solution that I'm not getting. Doing the select again with GROUP BY DESC is not an option.
Using a union is the only thing I can think of to accomplish this
select * from (select top(5) * from logins order by USERNAME ASC) a
union
select * from (select top(5) * from logins order by USERNAME DESC) b
Check the link
SQL SERVER – How to Retrieve TOP and BOTTOM Rows Together using T-SQL
Did you try to using rownumber?
SELECT *
FROM
(SELECT *, ROW_NUMBER() OVER (Order BY columnName) as TopFive
,ROW_NUMBER() OVER (Order BY columnName Desc) as BottomFive
FROM Table
)
WHERE TopFive <=5 or BottomFive <=5
http://www.sqlservercurry.com/2009/02/select-top-n-and-bottom-n-rows-using.html
I think you've two main options:
SELECT TOP 5 ...
FROM ...
ORDER BY ... ASC
UNION
SELECT TOP 5 ...
FROM ...
ORDER BY ... DESC
Or, if you know how many items there are in the table:
SELECT ...
FROM (
SELECT ..., ROW_NUMBER() OVER (ORDER BY ... ASC) AS intRow
FROM ...
) AS T
WHERE intRow BETWEEN 1 AND 5 OR intRow BETWEEN #Number - 5 AND #Number
Is it an option for you to use a union?
E.g.
select top 5 ... order by {specify columns asc}
union
select top 5 ... order by {specify columns desc}
i guess you have to do it using subquery only
select * from table where id in (
(SELECT id ORDER BY columnName LIMIT 5) OR
(SELECT id ORDER BY columnName DESC LIMIT 5)
)
select * from table where id in (
(SELECT TOP(5) id ORDER BY columnName) OR
(SELECT TOP(5) id ORDER BY columnName DESC)
)
EDITED
select * from table where id in (
(SELECT TOP 5 id ORDER BY columnName) OR
(SELECT TOP 5 id ORDER BY columnName DESC)
)
No real difference between this and the union that I'm aware of, but technically it is a single query.
select t.*
from table t
where t.id in (select top 5 t2.id from table t2 order by MyColumn)
or
t.id in (select top 5 t2.id from table t2 order by MyColumn desc);
SELECT *
FROM (
SELECT x, rank() over (order by x asc) as rown
FROM table
) temp
where temp.rown = 1
or temp.rown = (select count(x) from table)
Then you are out - doing the select again IS the only option, unless you want to pull in the complete result set and then throwing away everything in between.
ANY sql I cna think of is the same way - for the bottom you need to know first either how many items you have (materialize everything or use count(*)) or a reverse sort order.
Sorry if that does not suit you, but at the end.... reality does not care, and I do not see any other way to do that.
I had to do this recently for a very large stored procedure; if your query is quite large, and you want to minimize the amount of queries you could declare a #tempTable, insert into that #tempTable then query from that #tempTable,
DECLARE #tempTable TABLE ( columns.. )
INSERT INTO #tempTable
VALUES ( SELECT.. your query here ..)
SELECT TOP(5) columns FROM #tempTable ORDER BY column ASC -- returns first to last
SELECT TOP(5) columns FROM #tempTable ORDER BY column DESC -- returns last to first