: SELECT p.ID, p.personID, lastname, lnprefix, firstname, p.living, p.branch, nickname, prefix, suffix, nameorder, title, birthplace, birthdate, deathplace, deathdate, LPAD(SUBSTRING_INDEX(birthdate, ' ', -1),4,'0') as birthyear, altbirthdate, LPAD(SUBSTRING_INDEX(altbirthdate, ' ', -1),4,'0') as altbirthyear, altbirthplace, p.gedcom, treename FROM tng_people AS p LEFT JOIN tng_trees on p.gedcom = tng_trees.gedcom WHERE ( p.lastname = "KUUTSA") AND p.gedcom="1" ORDER BY p.lastname, p.firstname, IF(p.birthdatetr, p.birthdatetr, p.altbirthdatetr) LIMIT 50