473,750 Members | 2,648 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

simple query question: return latest


Still too new to SQL to have run across this yet ...

How does one return the latest row from a table, given multiple entries
of varying data?
i.e.: given a table that looks like this:

color | date
--------+------------
red | 2004-01-19
blue | 2004-05-24
red | 2004-04-12
blue | 2004-05-24
How do I select the most recent entry for 'red'?

Thanks in advance!
Scott
---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postg resql.org

Nov 23 '05 #1
7 6363
Scott,

On Nov 12, 2004, at 10:00 AM, Scott Frankel wrote:
color | date
--------+------------
red | 2004-01-19
blue | 2004-05-24
red | 2004-04-12
blue | 2004-05-24
How do I select the most recent entry for 'red'?


SELECT color, MAX(date)
FROM giventable
WHERE color = 'red' -- omit this line if you'd like to see the latest
date for each color
GROUP BY color;

OT hint: You might want to take a look at the list of PostgreSQL
Keywords in the documentation and avoid using them (such as date) to
help you avoid naming issues in the future.

Hope this helps.

Michael Glaesemann
grzm myrealbox com
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 23 '05 #2
SELECT "date" FROM "table" WHERE "color" = 'red' ORDER BY "date" DESC LIMIT
1;

Don't worry about names, just quote your identifiers. They will stand out
and you can use anything you want.

Jerry

"Michael Glaesemann" <gr**@myrealbox .com> wrote in message
news:89******** *************** ***********@myr ealbox.com...
Scott,

On Nov 12, 2004, at 10:00 AM, Scott Frankel wrote:
color | date
--------+------------
red | 2004-01-19
blue | 2004-05-24
red | 2004-04-12
blue | 2004-05-24
How do I select the most recent entry for 'red'?


SELECT color, MAX(date)
FROM giventable
WHERE color = 'red' -- omit this line if you'd like to see the latest date
for each color
GROUP BY color;

OT hint: You might want to take a look at the list of PostgreSQL Keywords
in the documentation and avoid using them (such as date) to help you avoid
naming issues in the future.

Hope this helps.

Michael Glaesemann
grzm myrealbox com
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 23 '05 #3
I interpreted the question slightly differently. I understood it to mean the
most recent instance of red which doesn't make much sense in this case but
let's say the table was

color | date | entered_by
--------+-----------------+---------------
red | 2004-01-19 | John
red | 2004-04-12 | Jane

and you wanted to pick up the row which Jane entered, then the statement
would be

SELECT g.color, g.date, g.entered_by
FROM giventable g
WHERE g.color = 'red'
AND g.date =
(SELECT MAX(g2.date)
FROM giventable g2
WHERE g2.color = g.color
)

or perhaps

SELECT g.color, g.date, g.entered_by
FROM giventable g
WHERE (g.color,g.date ) =
(SELECT g2.color, MAX(g2.date)
FROM giventable g2
WHERE g2.color = 'red'
GROUP BY g2.color
)

etc. etc.

----- Original Message -----
From: "Michael Glaesemann" <gr**@myrealbox .com>
To: "Scott Frankel" <le*****@pacbel l.net>
Cc: <pg***********@ postgresql.org>
Sent: Thursday, November 11, 2004 5:09 PM
Subject: Re: [GENERAL] simple query question: return latest

Scott,

On Nov 12, 2004, at 10:00 AM, Scott Frankel wrote:
color | date
--------+------------
red | 2004-01-19
blue | 2004-05-24
red | 2004-04-12
blue | 2004-05-24
How do I select the most recent entry for 'red'?


SELECT color, MAX(date)
FROM giventable
WHERE color = 'red' -- omit this line if you'd like to see the latest
date for each color
GROUP BY color;

OT hint: You might want to take a look at the list of PostgreSQL
Keywords in the documentation and avoid using them (such as date) to
help you avoid naming issues in the future.

Hope this helps.

Michael Glaesemann
grzm myrealbox com
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)


---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postg resql.org so that your
message can get through to the mailing list cleanly

Nov 23 '05 #4

On Nov 11, 2004, at 5:09 PM, Michael Glaesemann wrote:
Scott,

On Nov 12, 2004, at 10:00 AM, Scott Frankel wrote:
color | date
--------+------------
red | 2004-01-19
blue | 2004-05-24
red | 2004-04-12
blue | 2004-05-24
How do I select the most recent entry for 'red'?

SELECT color, MAX(date)
FROM giventable
WHERE color = 'red' -- omit this line if you'd like to see the latest
date for each color
GROUP BY color;


Unless I'm missing something, this returns every listing for color=red,
in max order.
So if I want the ONE most recent entry, is this something I have to
offload to my app
that parses the returned rows? Or is there a function in postgres that
can return THE
most recent entry?


OT hint: You might want to take a look at the list of PostgreSQL
Keywords in the documentation and avoid using them (such as date) to
help you avoid naming issues in the future.
Hmm. Good tip. Bad example terminology.

Thanks!
Scott


Hope this helps.

Michael Glaesemann
grzm myrealbox com
---------------------------(end of
broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 23 '05 #5
On Thu, 11 Nov 2004, Scott Frankel wrote:

On Nov 11, 2004, at 5:09 PM, Michael Glaesemann wrote:
Scott,

On Nov 12, 2004, at 10:00 AM, Scott Frankel wrote:
color | date
--------+------------
red | 2004-01-19
blue | 2004-05-24
red | 2004-04-12
blue | 2004-05-24
How do I select the most recent entry for 'red'?


SELECT color, MAX(date)
FROM giventable
WHERE color = 'red' -- omit this line if you'd like to see the latest
date for each color
GROUP BY color;


Unless I'm missing something, this returns every listing for color=red,
in max order.


No. This returns one row having the maximum date. The GROUP BY means
that you would get one row per color, but the where clause basically means
there is only the one.
However, it does not extend to getting other attributes of that row.

You can do something like the subselect already mentioned in another mail,
or use if you can use a PostgreSQL extension, you might want to look into
DISTINCT ON which will often be faster.

Something like:

select DISTINCT ON (color) * from giventable where color='red' order by
color, date desc;

should give the attributes of the one row with color='red' having the
highest date. With a bit of work (reverse opclasses), one can make an
index which can be used to provide the filtering and ordering for such
queries.

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 23 '05 #6
On Thu, Nov 11, 2004 at 05:00:46PM -0800, Scott Frankel wrote:
How does one return the latest row from a table, given multiple entries
of varying data?
i.e.: given a table that looks like this:

color | date
--------+------------
red | 2004-01-19
blue | 2004-05-24
red | 2004-04-12
blue | 2004-05-24

How do I select the most recent entry for 'red'?


One way would be to sort by date and use a LIMIT clause:

SELECT * FROM colortable WHERE color = 'red' ORDER BY date DESC LIMIT 1;

If you want the most recent entry for all colors then you could use
SELECT DISTINCT ON:

SELECT DISTINCT ON (color) * FROM colortable ORDER BY color, date DESC;

In either case, if multiple records have the same date and the ORDER BY
clause isn't specific enough to guarantee a certain order, then it's
indeterminate which record you'll get.

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 23 '05 #7

ORDER BY DESC LIMIT 1 is much simpler and more readable than a
sub-query.
Though the sub-query approach looks to be a good template for ensuring
more
accurate results by being more explicit.

Thanks to all who responded!
Scott

SELECT * FROM colortable WHERE color = 'red' ORDER BY date DESC LIMIT 1;

SELECT g.color, g.date, g.entered_by
FROM giventable g
WHERE g.color = 'red'
AND g.date =
(SELECT MAX(g2.date)
FROM giventable g2
WHERE g2.color = g.color
)

---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postg resql.org

Nov 23 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1819
by: Stijn Goris | last post by:
hi all, I have a table I want to interrogate tblcomment: CREATE TABLE `tblcomment` ( `ID` int(11) NOT NULL auto_increment, `IDSubonderdeel` int(11) NOT NULL default '0', `IDPoster` int(11) default NULL, `timestamp` int(11) default NULL, `inhoud` text NOT NULL,
3
3696
by: Patchwork | last post by:
Hi Everyone, Please take a look at the following (simple and fun) program: //////////////////////////////////////////////////////////////////////////// ///////////// // Monster Munch, example program #include <list>
2
18700
by: Dom | last post by:
I need to run a query based on a query in Access. The second query has a number of conditions which all work well, but there is one more contition I need to set to make it run properly. the first query returns a number of data items, consisting, among other fields, of a Company_ID and a Rating_Date. For most companies, the latest value of Rating_Date is equal to a value in a seperate table (tblVariables) which logs the last time a...
1
1675
by: Mike Cooper | last post by:
Hi everyone, This is a tough one. I have a database full of solicitations, identifying a customer and recording initial call, first followup, second followup, etc. My boss want to be able to generate a report showing a list of customer who were call between two different dates that he types into a form. That, I have done. My boss types in his two dates, the SQL statement searches through the follow-up call fields for a date
6
2299
by: Larry R Harrison Jr | last post by:
I have a database I'm designing in Access 97. I have a custom field in a query which looks in {Table of Documents} and shows them all. It then needs a "latest revision number," stored in another table named {Table of Revisions}. It naturally matches them up by linking the autoid in {Doc} with the related field in {Rev}. It then looks for a field in {Rev} called "revision number" and looks for the last one for the given Doc (linked by the...
51
8284
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct code? many thx!
1
1245
by: uspensky | last post by:
kind of a tough one i think but any help is appreciated. please try to stay away from T-SQL... I have a table with products and closing dates for each of 4 quarters and annual for several years back. (Earning_Dates) I have another table that has those products with dates and closing prices. (undPrices) i have a third table which has the id for all the products.
1
1621
by: acdevteam | last post by:
Hi All, I need some help with a query. Here is the structure for the table: ID, sDate, sComment, sRole Possible values in the table: 0101, 11/6/2006, Comment123, Role1 0101, 11/6/2006, Comment124, Role1 0101, 11/6/2006, Comment125, Role2
1
2280
by: ode | last post by:
I am an infrequent user and my version is Access 2000. I have a list of 122k lines which consits of 3 fields/data points;a product code, a date, and a price code. I want to run a query to select the latest date the product code was entered and return the price code associated with the date. There are entrys for many different dates, none of them are the same. I have pulled all the data into access but can not figure out how to get just the...
0
9001
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9396
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9342
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8263
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6808
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4716
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4888
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2807
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.