0

I have written an SQL script that should get X entries before a user id, ordered by registration_date desc on ordered db table based on registration date.

To be more concrete, lets say that these are some entries on the ordered db:

    id      | Name                  | Email                           | registration_data
    3939    | Barbara Hayes         | barbara.hayes@example.com       | 2019-09-15T23:39:26.910Z
    689     | Noémie Harris         | noemie.harris@example.com       | 2019-09-14T21:39:15.641Z
    2529    | Andrea Iglesias       | andrea.iglesias@example.com     | 2019-09-13T02:59:08.821Z
    3890    | Villads Andersen      | villads.andersen@example.com    | 2019-09-12T06:29:48.708Z
    3685    | Houssine Van Sabben   | houssine.vansabben@example.com  | 2019-09-12T02:27:08.396Z

I would like to get the users over id 3890. So the query should return

689     | Noémie Harris         | noemie.harris@example.com       | 2019-09-14T21:39:15.641Z
2529    | Andrea Iglesias       | andrea.iglesias@example.com     | 2019-09-13T02:59:08.821Z

The raw SQL that I wrote is this:

SELECT * from (
        SELECT id, name, email, registration_date FROM public.users
        WHERE users.registration_date > (SELECT registration_date FROM users WHERE id = 3890)
        order by registration_date
        limit 2 )
    as a
order by registration_date desc

See this dbfiddle.

I tried to implement the SqlAlchemy code with no luck. I believe that I am making a mistake on the subquery. This is what i have done so far.

registration_date_min = db.query(User.registration_date) \
    .order_by(User.registration_date) \
    .filter(User.id == ending_before).first()

users_list = db.query(User) \
    .filter(User.registration_date > registration_date_min) \
    .order_by('registration_date').limit(limit).subquery('users_list')

return users_list.order_by(desc('registration_date'))

P.s the ending_before represents a user_id. Like 3890 in the example. Any ideas on the SqlAlchemy part would be very helpful!

3
  • codeshare.io/5QwQEm real quick ?
    – Ioan Kats
    Nov 28, 2020 at 19:21
  • @MartijnPieters The example with the table is just ordered by date desc, that's why the specific dates. To tell you the truth, I was a bit buffled of what you meant with the samples dates, that's why I posted codeshare, to discuss it a bit faster there. On the bright side I tried your solution and it worked !
    – Ioan Kats
    Nov 28, 2020 at 19:29
  • On mobile right now. I put the query onto a dbfiddle and see I must have gotten the userids mixed up. :-/ Sorry about that!
    – Martijn Pieters
    Nov 28, 2020 at 20:07

1 Answer 1

2

First of all, your registration_date_min query has already been executed; you have a row with one column there. Remove the first() call; it executes the SELECT and returns the first row.

As you are selecting by the primary key, there is only ever going to be a single row and you don't need to order it. Just use:

registration_date_min = db.query(User.registration_date).filter(
    User.id == ending_before
)

That's now a query object and can be used directly in a comparison:

users_list = (
    db.query(User)
    .filter(User.registration_date > registration_date_min)
    .order_by(User.registration_date)
    .limit(limit)
)

You can then self-select with Query.from_self() from that query to apply the final ordering:

return user_list.from_self().order_by(User.registration_date.desc()))

This produces the following SQL (on SQLite, other dialects can differ):

SELECT anon_1.users_id AS anon_1_users_id, anon_1.users_name AS anon_1_users_name, anon_1.users_email AS anon_1_users_email, anon_1.users_registration_date AS anon_1_users_registration_date 
FROM (SELECT users.id AS users_id, users.name AS users_name, users.email AS users_email, users.registration_date AS users_registration_date 
FROM users 
WHERE users.registration_date > (SELECT users.registration_date AS users_registration_date 
FROM users 
WHERE users.id = ?) ORDER BY users.registration_date
 LIMIT ? OFFSET ?) AS anon_1 ORDER BY anon_1.users_registration_date DESC

If I use the following model with __repr__:

class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    email = db.Column(db.String)
    registration_date = db.Column(db.DateTime)

    def __repr__(self):
        return f"<User({self.id}, {self.name!r}, {self.email!r}, {self.registration_date!r}>"

and print the query result instances I get:

<User(689, 'Noémie Harris', 'noemie.harris@example.com', datetime.datetime(2019, 9, 14, 21, 39, 15, 641000)>
<User(2529, 'Andrea Iglesias', 'andrea.iglesias@example.com', datetime.datetime(2019, 9, 13, 2, 59, 8, 821000)>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.