Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9069243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T17:22:41+00:00 2026-06-16T17:22:41+00:00

I would like to create a scope which sort data from the closest date

  • 0

I would like to create a scope which sort data from the closest date to the farthest.

For example I have 3 values:

<Value id: 1, date: '2012-12-20'>
<Value id: 2, date: '2012-12-28'>
<Value id: 3, date: '2012-12-31'>

Then I would like to sort the date closest to a given date: 2012-12-29.
I should have as result this order: 2, 3, 1.
If I choose 2012-12-30 the result must be: 3, 2, 1.

I tried something like this:

scope :order_by_closest_date, lambda{|time| 
  select("*, (date - DATE('#{time}')) AS time").order("time ASC")
}

But it doesn’t work.
For information: Rails 3.2.9 Ruby 1.9.3 Postgresql 9.1.4.
Any ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T17:22:43+00:00Added an answer on June 16, 2026 at 5:22 pm

    Simple query

    First example works with a date column according to initial question.

    Not sure about Ruby syntax, but a proper SQL statement would be:

    SELECT * 
    FROM   tbl
    ORDER  BY @(date_col - '2012-12-29'::date)
    

    @ being the "absolute value" operator.

    Never use date or time as identifiers. While being allowed (with some restrictions) in PostgreSQL, these are reserved words in the SQL standard and it leads to confusing error messages and possibly unexpected errors.

    Superior performance

    The rest works with a timestamp column according to the update in the comment.

    For small tables or ad-hoc queries, the above solution is just fine. For medium or big tables, if performance matters, I suggest a more sophisticated approach.

    Condicio sine qua non is an index on the date or timestamp column. Like this:

    CREATE INDEX tbl_my_timestamp_idx ON tbl(my_timestamp);
    

    With the index in place the following query which will nuke the performance of the simple one for bigger tables:

    SELECT *
    FROM  (
        (
        SELECT *
        FROM   tbl
        WHERE  my_timestamp >= '2012-12-30 11:32'::timestamp
        ORDER  BY my_timestamp
        LIMIT  3
        )
    
        UNION ALL
        (
        SELECT *
        FROM   tbl
        WHERE  my_timestamp < '2012-12-30 11:32'::timestamp
        ORDER  BY my_timestamp DESC
        LIMIT  3
        )
        ) x
    ORDER  BY @extract('epoch' FROM (my_timestamp - '2012-12-28 11:32'::timestamp))
    LIMIT  3;
    
    • Parenthesis around the two legs of the UNION ALL – SELECT are not optional. Needed to apply LIMIT to each leg.

    • If you order by additional columns, reflect that in your index – use a multi-column index in that case.

    How so?

    The first query uses an expression as condition. Postgres has to compute a value for every single row, then order by the result and pick the first few. No problem for a small table, but very expensive for big tables. O(n); n being the number of rows in the table. It can’t use a plain index. Plus some non-trivial cost to sort and pick the winners among all rows.
    You could create an index on an expression, which would be fastest, but that only works for a constant timestamp to compare to – hardly a realistic use case.

    The second query finds the position according to your timestamp in the index, reads tuple pointers for next couple of rows sequentially and fetches them straight from the table (or even directly from the index with an index-only scan in 9.2). Twice, once up, once down, since we don’t know how the peers compare. But that’s just 2 x O(log(n)) (typical b-tree look-up cost) Computation is only done for the few pre-selected rows. Picking the winners from the small sample carries a trivial constant cost.

    Just test with EXPLAIN ANALYZE. In a quick test on a real-life table I got a factor 1000 with a table of 50k rows. And it keeps scaling up for bigger tables.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i would like create a array of structure which have a dynamic array :
I have this form on which I would like to create a dynamic number
In my model I would like to create a scope that takes advantage of
I would like to be able to create a bean whose scope is limited
I would like to create an ASP.NET MVC web application which has extensible logic
I would like to create an advancedmodule with a cmdlet function which performs some
I would like to create a Spring's bean producer method which is aware who
I would like to create a list or map of references in C++ which
I have a client who would like a system developed which handles sending out
I would like to create this shape using just css. I am pretty sure

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.