{"record":{"id":"50e529ceb0b56c5d","repo":"pola-rs/polars","slug":"column-nm-r-appears-more-than-once-in-the-query","errorCode":null,"errorMessage":"column {nm!r} appears more than once in the query/result cursor","messagePattern":"column (.+?) appears more than once in the query/result cursor","errorType":"exception","errorClass":"DuplicateError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/io/database/_executor.py","lineNumber":363,"sourceCode":"        self,\n        description: list[tuple[str, Any]],\n        schema_overrides: SchemaDict,\n    ) -> SchemaDict:\n        \"\"\"\n        Attempt basic dtype inference from a cursor description.\n\n        Notes\n        -----\n        This is limited; the `type_code` description attr may contain almost anything,\n        from strings or python types to driver-specific codes, classes, enums, etc.\n        We currently only do the additional inference from string/python type values.\n        (Further refinement will require per-driver module knowledge and lookups).\n        \"\"\"\n        dupe_check = set()\n        for nm, desc in description:\n            if nm in dupe_check:\n                msg = f\"column {nm!r} appears more than once in the query/result cursor\"\n                raise DuplicateError(msg)\n            elif desc is not None and nm not in schema_overrides:\n                dtype = dtype_from_cursor_description(desc)\n                if dtype is not None:\n                    schema_overrides[nm] = dtype  # type: ignore[index]\n            dupe_check.add(nm)\n\n        return schema_overrides\n\n    @staticmethod\n    def _is_alchemy_async(conn: Any) -> bool:\n        \"\"\"Check if the given connection is SQLALchemy async.\"\"\"\n        try:\n            from sqlalchemy.ext.asyncio import (\n                AsyncConnection,\n                AsyncSession,\n                async_sessionmaker,\n            )\n","sourceCodeStart":345,"sourceCodeEnd":381,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/io/database/_executor.py#L345-L381","documentation":"polars.read_database raises DuplicateError when the cursor's description contains two or more columns with the same name. During result ingestion, _inject_type_overrides walks the cursor description to build schema overrides; a repeated column name would make override/dtype mapping ambiguous, so it fails fast. Fix your SQL to alias columns uniquely.","triggerScenarios":"Calling polars.read_database / pl.read_database with a query whose result set contains duplicate column names, e.g. SELECT a.id, b.id FROM a JOIN b ON ... with no aliases; also possible with SELECT * over tables/views having colliding column names.","commonSituations":"Joins where both sides expose an identically named column (id, name, created_at); SELECT * from a view combining tables; ORMs or legacy reports emitting duplicate labels.","solutions":["Alias duplicate columns in the query: SELECT a.id AS a_id, b.id AS b_id","Reduce the select list to unique columns instead of SELECT *","Use an explicit schema_overrides/parameter only after deduplicating names — overrides keyed by name cannot disambiguate duplicates","If the driver allows, fetch by column position and rename in pandas/arrow before conversion"],"exampleFix":"// before\npl.read_database(\"SELECT a.id, b.id FROM a JOIN b ON a.id = b.parent_id\", conn)\n// after\npl.read_database(\"SELECT a.id AS a_id, b.id AS parent_id FROM a JOIN b ON a.id = b.parent_id\", conn)","handlingStrategy":"validation","validationCode":"names = [c[0] for c in cur.description]\ndupes = {n for n in names if names.count(n) > 1}\nif dupes:\n    raise ValueError(f\"duplicate columns in result: {dupes}; alias them in the query\")","typeGuard":"def has_unique_columns(cur) -> bool:\n    names = [d[0] for d in (cur.description or [])]\n    return len(names) == len(set(names))","tryCatchPattern":"from polars.exceptions import DuplicateError\ntry:\n    df = pl.read_database(query, conn)\nexcept DuplicateError as e:\n    # rewrite query with unique aliases\n    ...","preventionTips":["Alias every joined column explicitly instead of SELECT *","Lint SQL for duplicate output labels before running","Test join queries against real schemas in CI"],"tags":["database","duplicate-columns","schema","polars"],"backgroundTag":"schema-validation-failed","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}