Find lowest date (custom) in mysql
Please, do yourself a favour and use a date
field instead.. you'll save yourself a lot of troubles.
ALTER TABLE `TableName` ADD `date` DATE NOT NULL;
UPDATE `TableName` SET `date` = CONCAT( `Y` , '-', `M` , '-', `D` );
then you'll be able to do:
SELECT MIN(`date`) FROM `TableName`
SELECT min(concat(Y,M,D)) FROM TableName
Edit: This just looks nice and clean but it is kind of very bad answer, so please use this answer
Just use the ORDER BY
clauses:
SELECT * FROM TableName
ORDER BY Y ASC, M ASC, D ASC
More info here : http://www.tizag.com/mysqlTutorial/mysqlorderby.php
bugwheels94's answer will give you the correct result:
SELECT min(concat(Y,M,D))
FROM `TableName`
but this will be unable to use any index you have on any of the date's constituent fields, so will have to visit every row in the table to determine the minimum value.
Combining m4t1t0 and koopajah's answers gives you:
SELECT *
FROM `TableName`
ORDER BY Y, M, D
LIMIT 1
This will be able to use an available index on Y, and maybe even a combined index on (Y,M,D) which can perform much faster on larger tables.
All this being said; It's almost criminal to put an answer to this question that doesn't suggest using a date field instead of your three column setup. The only reason I can think of to separate a date column would be for performance on niche queries that require separate indexes on day or month, but the choice of accepted answer suggests to me that this isn't the case.
As pointed out by Lucius.. If it's a date, store it as a date and run:
SELECT MIN(`DateColumnName`) FROM `TableName`
As a bonus this will give you access to all the MySQL Temporal functions on the column, including the ability to extract day and month, format it how you like and a single field to index and order by.