0

Assumeing I have a table Foo

id | startDate | startTime | endTime | name

I am trying to find occurrences that "pass midnight"...start < 00:00:00 and end > 00:00:00

I can use the following to get the times

select extract (epoch from (endTime - startTime)) as time from Foo

but how can I add a constraint that allows me to filter the return values for only those < 0 (which should be those satisfying the "midnight" property)

I tried

select extract (epoch from (endTime - startTime)) as timeSpent from Foo where timeSpent < 0
ERROR:  column "timeSpent" does not exist
5
  • Do you mean an INSERT constraint? Such that only data that passes a certain test is allowed to be inserted into your table? Commented Sep 26, 2016 at 16:32
  • @CodyCaughlan I'll edit the question (including bad code) that I think will clarify Commented Sep 26, 2016 at 16:34
  • time is a reserved word in PG; so pick a different name Commented Sep 26, 2016 at 16:58
  • @CodyCaughlan, I've changed the question but the problem will remains. Commented Sep 26, 2016 at 17:07
  • What data type are the columns starttime and endtime? Commented Sep 26, 2016 at 17:23

2 Answers 2

1

You can't reference an alias on the same level where you define it. You need to wrap that in a derived table:

select * 
from (
  select extract (epoch from (endTime - startTime)) as timeSpent 
  from Foo 
) t 
where timespent < 0;
Sign up to request clarification or add additional context in comments.

Comments

0

What I would think about doing is creating a sub-query that isolates the part of the date that denotes the day, and writing a statement that roughly equates to:

WHERE [start day] != [end day]

This will enable you to extract a specific date from the table.

2 Comments

I would, but the time stamps are 24 hour. The table does however have a "start date"...
Note that [start day] is an invalid identifier in SQL. To use an identifier that contains a space you need to use double quotes: e.g. "start day"

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.