Newest Drupal path alias per node: NOT EXISTS instead of GROUP BY
To get one path alias per node in a custom Drupal query, join path_alias on the node's system path and language, and add a NOT EXISTS condition that rules out any newer published alias for the same path and language. That returns the row with the highest id, which is the one Drupal's alias manager treats as current, and core's index on (path, langcode, id, status) can answer the check one row at a time. The common alternative, joining a MAX(id) … GROUP BY path, langcode derived table, gives the same answer but aggregates the whole alias table before the join.
Why a plain join returns one row per old URL
The query in question fed a custom sitemap endpoint on a decoupled Drupal site: list published nodes with their URL. The first version was the obvious one, a LEFT JOIN from node_field_data to path_alias on path = CONCAT('/node/', nid).
That works until an editor renames a page. Drupal keeps the old alias row unless something deletes it, and Pathauto's "create a new alias, keep the old one" setting does exactly that on purpose, so old links keep resolving. A node that has been renamed twice has three published rows in path_alias, all pointing at the same /node/123. The plain join multiplies the node by three, and the sitemap lists three URLs for one page, two of them retired.
Drupal itself is not confused by this. When it turns /node/123 into a URL, the alias repository looks up published aliases for that path and language and takes the one with the highest id. So "the current alias" has a precise definition you can reproduce in SQL: for each path and langcode, the published row with the largest id. This is the classic greatest-n-per-group problem.
The GROUP BY version and what it costs
The first fix reached for the textbook answer: compute the maximum id per group in a derived table, then join through it.
SELECT n.nid, n.langcode, pa.alias
FROM node_field_data n
LEFT JOIN (
SELECT path, langcode, MAX(id) AS id
FROM path_alias
WHERE status = 1
GROUP BY path, langcode
) latest
ON latest.path = CONCAT('/node/', n.nid)
AND latest.langcode = n.langcode
LEFT JOIN path_alias pa ON pa.id = latest.id
WHERE n.status = 1;
It's correct, and on a small site you'd never notice the difference. The problem is the shape of the work. The derived table has to group every published alias on the site, including aliases for taxonomy terms, users and anything else, before MySQL can join a single node to it. The grouped result is a temporary table with no index of its own, and the join into it depends on how well the optimiser handles derived tables in your MySQL or MariaDB version. You've turned a set of cheap per-row lookups into one large aggregation.
The rewrite came during a period when the CMS was slow under heavy load. I can't say this query was the cause; it was one of several things tidied up at the time. But a sitemap endpoint is exactly the kind of request crawlers hit repeatedly, so it was worth making the query's cost proportional to the rows it returns.
How the NOT EXISTS join works
The rewrite keeps the plain join and adds one more condition to it: join this alias row only if no newer published alias exists for the same path and language.
SELECT n.nid, n.langcode, pa.alias
FROM node_field_data n
LEFT JOIN path_alias pa
ON pa.path = CONCAT('/node/', n.nid)
AND pa.langcode = n.langcode
AND pa.status = 1
AND NOT EXISTS (
SELECT 1
FROM path_alias newer
WHERE newer.path = pa.path
AND newer.langcode = pa.langcode
AND newer.status = 1
AND newer.id > pa.id
)
WHERE n.status = 1;
For each candidate alias row, the subquery asks a narrow question: is there a row with the same path and langcode, published, with a larger id? Core's path_alias table has an index on (path, langcode, id, status), which matches that question almost exactly: equality on the first two columns and a range on the third. The database can seek straight to the group and check whether anything sits above the current id, without touching the rest of the table.
Two details matter here.
- Keep every alias filter in the
ONclause. Movepa.status = 1intoWHEREand the left join quietly becomes an inner join: a node with no alias hasNULLthere and drops out. TheNOT EXISTScheck happens to survive inWHERE, because a subquery comparing againstNULLfinds nothing, but keeping all of the alias conditions together in the join makes the intent obvious. A node without an alias then comes back with aNULLalias, which a sitemap can fall back to/node/123for. - Match the language the way your site does. This joins on the node's own langcode. If your site stores aliases with the "not specified" language code, or relies on Drupal's fallback from a translation to a language-neutral alias, you need to reproduce that fallback too, or those nodes will come back without an alias.
Writing it with Drupal's database API
Drupal's dynamic query builder accepts a raw join condition string, and curly-brace table names inside it are prefixed like everywhere else, so the subquery can live in the condition:
$query = $this->database->select('node_field_data', 'n');
$query->fields('n', ['nid', 'langcode', 'changed']);
$query->leftJoin('path_alias', 'pa', implode(' AND ', [
"pa.path = CONCAT('/node/', n.nid)",
'pa.langcode = n.langcode',
'pa.status = 1',
'NOT EXISTS (SELECT 1 FROM {path_alias} newer'
. ' WHERE newer.path = pa.path'
. ' AND newer.langcode = pa.langcode'
. ' AND newer.status = 1'
. ' AND newer.id > pa.id)',
]));
$query->addField('pa', 'alias');
$query->condition('n.status', 1);
$rows = $query->execute()->fetchAll();
Nothing in the condition comes from user input, so a literal string is fine. If you ever need a parameter in there, pass it through the $arguments array of leftJoin() rather than concatenating it.
A window function, ROW_NUMBER() OVER (PARTITION BY path, langcode ORDER BY id DESC), is the other modern answer to greatest-n-per-group, and it works on MySQL 8 and MariaDB 10.2 or later. I prefer NOT EXISTS for this case because it stays a plain join that the query builder expresses easily, and it uses the existing index without a derived table. Whichever you pick, run EXPLAIN against your own data before trusting either one; the optimiser's choices vary by version and table size.
Excluding trashed nodes only when the module is there
The same change fixed a second miscount. The site uses the contributed Trash module, which keeps "deleted" content in the database so it can be restored. A query that reads node_field_data directly bypasses the entity query layer that would normally hide those rows, so trashed pages turned up in the sitemap and in its counts.
The fix was a small helper that adds the trash condition to a query only when the module is installed, checked with \Drupal::moduleHandler()->moduleExists('trash') or the injected module handler. That keeps the endpoint working on an environment without the module, and keeps the condition in one place for every query that needs it. The general lesson is that any raw query over entity tables is responsible for the filtering an entity query would have done for you: published status, access and, here, soft deletion.
Key takeaways
- A node can have several published rows in path_alias after renames, so a plain join to it returns one row per old URL.
- Drupal treats the published alias with the highest id for a path and language as current, so reproduce that rule exactly in custom SQL.
- A NOT EXISTS check for a newer row inside the join condition picks that alias per row and can use core's path, langcode, id, status index.
- Keep every alias condition inside the LEFT JOIN's ON clause so nodes without an alias still come back.
- Raw queries over entity tables skip what entity queries filter for you, so add soft-deletion and status conditions yourself.