Search code examples
pythonsqlalchemyfastapi

SELECT query with multiple JOINs returns duplicate rows when ordered by descending, but not ascending


I'm using SQLAlchemy to construct a SELECT query that involves multiple JOINs between several tables. When I order the results by one of the columns in ascending order using the order_by method, the query returns data with no duplicate rows. However, when I order the results by the same column in descending order, the query returns duplicate rows for every row in the result.

Here's an example of the code that I'm using:

stmt = select([table1, table2, table3]).select_from(table1.join(table2).join(table3)).order_by(table1.c.column1.asc())

In this example, I'm selecting columns from three tables and joining them with two JOIN statements. When I order the results by column1 in ascending order, the query returns data with no duplicate rows. However, when I order the results by the same column in descending order, the query returns duplicate rows.

I've tried adding additional columns to the order_by clause to ensure that the ordering is unique, but this hasn't solved the issue. I'm not sure what else to try.

Can anyone help me figure out why I'm getting duplicate rows when I order the results by column1 in descending order, and how I can fix this issue?


Solution

  • This issues has been resolved, the problem does not come from the ORM but rather the database, the duplicates we were observing are the result of an anomaly on the part of our internal systems not the way the ORM is querying the data.