r/mysql • u/deWereldReiziger • Apr 17 '25
solved Query Help: Select * WHERE only bring back new records from current year
Trying to make a query so that it brings back only new instances from the current year where there were no instances of the same name in previous years; I thought about trying a WHERE NOT EXISTS but I'm not sure I'm doing it right. My results come back NULL
SELECT DISTINCT tbed1.common_name, tbed1.scientific_name, year(tbed1.date) FROM tbl_bird_ebird_data tbed1
WHERE NOT EXISTS (
SELECT tbed2.common_name, tbed2.scientific_name, year(tbed2.date)
FROM tbl_bird_ebird_data tbed2
WHERE tbed1.common_name = tbed2.common_name AND year(tbed2.date) < NOW() )
ORDER BY common_name ASCThe sample data would be
id common_name date
1 Wood Duck 2020-01-01
2 Mallard 2020-01-01
3 Eastern Screech Owl 2025-04-17
4 Wood Duck 2025-04-17
5 Mallard 2025-04-17The results would be:
id common_name date
3 Eastern Screech Owl 2025-04-17
2
Upvotes
1
u/Aggressive_Ad_5454 Apr 17 '25
Your example shows
That isn't right. You need this instead:
It compares the year of the
datecolumn in your table with the year of the present datestamp. That means "current year".But it's an inefficient way to do that. What you really want is this:
That
DATE_FORMAT(NOW(), "%Y-01-01")expression turns, I dunno,2025-04-17 09:41into2025-01-01, the first day of the current year. Then the>=chooses all thedatevalues on or after that day. And that approach can use an index to search, which can be important when you have a lot of data in the table.1
u/[deleted] Apr 17 '25 edited Apr 17 '25
This achieves your desired outcome:
SELECT `tbed1`.`id`, `tbed1`.`common_name`,`tbed1`.`date`
FROM `tbl_bird_ebird_data` as `tbed1`
LEFT JOIN (SELECT * from `tbl_bird_ebird_data` WHERE YEAR(`date`)<YEAR(NOW())) AS `tbed2`
ON `tbed1`.`common_name`=`tbed2`.`common_name`
WHERE YEAR(`tbed1`.`date`)=YEAR(NOW())
AND `tbed2`.`ID` IS null
2
u/[deleted] Apr 17 '25
[removed] — view removed comment