Oct 15th

MySQL Select the first and last ID from a table in a single select statement

Just a very quick little snippet that will allow you to SELECT the lowest and highest value from a single field in a database. For example, in a recent project I had to ensure that I was not deleting the first or last record status history record for a given project in a database table. To do this I came up with the following:

SELECT
	MIN(status_history_id) as first_id,
	MAX(status_history_id) as last_id
FROM table_status_history
WHERE ( project_id = "some_unique_id" )
GROUP BY project_id;

Essentially, this selects all status history records from the table for a specific project, then we group them all together and select only the max and min from the ID field and return those as (2) ad-hoc fields.

Leave a Reply