0

The given query works perfectly fine when executed with DataGrip, but returns the following error when it's submitted by lib/pq:

pq: a negative number raised to a non-integer power yields a complex result

The error is happening within postgres as it shows up in the logs

SELECT upvotes / (EXTRACT(EPOCH FROM current_timestamp-created_at)/3600)^1.8 as score, title,
FROM ideas
ORDER BY score desc

simplified schema

create table ideas
(
   title text not null,
   created_at timestamp not null,
   upvotes integer default 0 not null
)

I'm running postgres v9.2

I'd be very happy about a little hint in where to look into, as I'm out of ideas.

2
  • 2
    Check which created_at values are in the future. Commented Jun 2, 2018 at 5:35
  • yeah, just resolved it, was indeed the issue, thanks man! Commented Jun 2, 2018 at 5:37

1 Answer 1

1

So, you've got some timestamps in the future somehow. you can protect the query to ensure that there's no negative results using GREATEST

SELECT upvotes / (GREATEST(EXTRACT(EPOCH FROM current_timestamp-created_at)/3600),0)^1.8 as score, title,
FROM ideas
ORDER BY score desc

Alternatively you can exclude the bad data using a WHERE clause.

SELECT upvotes / (EXTRACT(EPOCH FROM current_timestamp-created_at)/3600)^1.8 as score, title,
FROM ideas
WHERE current_timestampn >= created_at
ORDER BY score desc
Sign up to request clarification or add additional context in comments.

1 Comment

cheers! there was indeed a future timestamp in one of the rows

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.