{"record":{"id":"a4e89cd4d0af6314","repo":"prestodb/presto","slug":"duplicate-relation","errorCode":"DUPLICATE_RELATION","errorMessage":"WITH query name '%s' specified more than once","messagePattern":"WITH query name '(.+?)' specified more than once","errorType":"validation","errorClass":"SemanticException","httpStatus":null,"severity":"error","filePath":"presto-main-base/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java","lineNumber":5469,"sourceCode":"        private Scope analyzeWith(Query node, Optional<Scope> scope)\n        {\n            // analyze WITH clause\n            if (!node.getWith().isPresent()) {\n                return createScope(scope);\n            }\n            With with = node.getWith().get();\n            if (with.isRecursive()) {\n                throw new SemanticException(NOT_SUPPORTED, with, \"Recursive WITH queries are not supported\");\n            }\n\n            Scope.Builder withScopeBuilder = scopeBuilder(scope);\n            for (WithQuery withQuery : with.getQueries()) {\n                Query query = withQuery.getQuery();\n                process(query, withScopeBuilder.build());\n\n                String name = withQuery.getName().getValueLowerCase();\n                if (withScopeBuilder.containsNamedQuery(name)) {\n                    throw new SemanticException(DUPLICATE_RELATION, withQuery, \"WITH query name '%s' specified more than once\", name);\n                }\n\n                // check if all or none of the columns are explicitly alias\n                if (withQuery.getColumnNames().isPresent()) {\n                    List<Identifier> columnNames = withQuery.getColumnNames().get();\n                    RelationType queryDescriptor = analysis.getOutputDescriptor(query);\n                    if (columnNames.size() != queryDescriptor.getVisibleFieldCount()) {\n                        throw new SemanticException(MISMATCHED_COLUMN_ALIASES, withQuery, \"WITH column alias list has %s entries but WITH query(%s) has %s columns\", columnNames.size(), name, queryDescriptor.getVisibleFieldCount());\n                    }\n                }\n\n                withScopeBuilder.withNamedQuery(name, withQuery);\n            }\n\n            Scope withScope = withScopeBuilder.build();\n            analysis.setScope(with, withScope);\n            return withScope;\n        }","sourceCodeStart":5451,"sourceCodeEnd":5487,"githubUrl":"https://github.com/prestodb/presto/blob/55bb57d202de3b926896fa966c2c4a44c779634e/presto-main-base/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java#L5451-L5487","documentation":"Semantic check in StatementAnalyzer while processing a WITH clause: two CTEs in the same WITH list declare the same query name. Since each name must bind to exactly one subquery for scope resolution, the analyzer rejects the query, formatting the duplicated name into the message.","triggerScenarios":"WITH a AS (...), a AS (...) SELECT ... — any duplicate CTE name within a single WITH clause.","commonSituations":"Copy-pasting CTEs and forgetting to rename; programmatic SQL generation emitting the same alias twice; merging queries by concatenating WITH lists.","solutions":["Rename one of the duplicate WITH queries","Merge the two CTE definitions if they compute the same thing","Check generated SQL builders for alias collisions"],"exampleFix":"// before\nWITH sales AS (...), sales AS (...) SELECT ...\n// after\nWITH sales_2023 AS (...), sales_2024 AS (...) SELECT ...","handlingStrategy":"validation","validationCode":"List<String> names = withQueries.stream().map(q -> q.getName().getValueLowerCase()).collect(toList());\nSet<String> dupes = names.stream().filter(n -> Collections.frequency(names, n) > 1).collect(toSet());\nif (!dupes.isEmpty()) throw new IllegalArgumentException(\"Duplicate CTE names: \" + dupes);","typeGuard":null,"tryCatchPattern":"try { runQuery(); } catch (SemanticException e) { if (e.getCode() == DUPLICATE_RELATION.toErrorCode()) { renameCteAndRetry(); } throw e; }","preventionTips":["Generate CTE names with unique prefixes in SQL builders","Search for duplicate names when concatenating query fragments","Lowercase-normalize names before comparison"],"tags":["cte","duplicate-name","sql"],"backgroundTag":"duplicate-identifier","analyzedSha":"55bb57d202de3b926896fa966c2c4a44c779634e","analyzedAt":"2026-09-04T12:50:26.162Z","contentChangedAt":"2026-09-04T12:50:26.162Z","schemaVersion":2},"datasetVersion":"2026-09-11T21:17:09.523Z"}