RANK used in 'where' returns invalid column, but exists in results setUsing column alias in a WHERE clause doesn't workNon-integer primary key considerationsPostgreSQL DELETE FROM fails with `Error: attempted to delete invisible tuple`search_path set and seen but not used!Index not used with many WHERE LOWER(column) IN (…) conditions, works fine with just a fewMulti-Column index not used for index-only scan, but partial index ispostgresql random function returns duplicate results when order by random used in queryQuery returns results on pgAdmin running on remote client but not directly through psql on db serverPostgres, `where` condition, sort by first column, but I don't want that

RANK used in 'where' returns invalid column, but exists in results set

How can I finish my PhD?

When does order matter in probability?

How strong is aircraft-grade spruce?

What's the biggest difference between these two photos?

I multiply the source, you (probably) multiply the output!

Can multiple public keys lead to the same shared secret in x25519?

What is the difference between tl_to_str:V and tl_to_str:N?

Distinguishing between octahedral and tetrahedral holes

Is there a specific way to describe over-grown, old, tough vegetables?

Chandrayaan 2: Why is Vikram Lander's life limited to 14 Days?

Why does low tire pressure decrease fuel economy?

What makes an ending "happy"?

Is every sentence we write or utter either true or false?

Problem with listing a directory to grep

Friend is very nitpicky about side comments I don't intend to be taken too seriously

Features seen on the Space Shuttle's solid booster; what does "LOADED" mean exactly?

How is lower/no gravity simulated on a planet with gravity, without leaving the surface?

Is it unavoidable taking shortcuts in software development sometimes?

When calculating averages, why can we treat exploding die as if they're independent?

Are professors obligated to accept supervisory role? If not, how does it work?

How do we create our own symbolisms?

How to reference a custom counter that shows section number?

Supervisor wants me to support a diploma-thesis software tool after I graduated



RANK used in 'where' returns invalid column, but exists in results set


Using column alias in a WHERE clause doesn't workNon-integer primary key considerationsPostgreSQL DELETE FROM fails with `Error: attempted to delete invisible tuple`search_path set and seen but not used!Index not used with many WHERE LOWER(column) IN (…) conditions, works fine with just a fewMulti-Column index not used for index-only scan, but partial index ispostgresql random function returns duplicate results when order by random used in queryQuery returns results on pgAdmin running on remote client but not directly through psql on db serverPostgres, `where` condition, sort by first column, but I don't want that






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















been trying to get this query to work, it's almost perfect , but I just need to add the commented out 'where' condition and it'll do exactly what I want, but when I uncomment,I get an error 'column doesnt exist'. Been having trouble figuring out the syntax for this, would appreciate any help!



I basically have a table with date, timestamp, DID, coordinates



I want a query that will return rows with the last coordinate from day X, and the first coord from day X+1 , and the coordinates (so it will only return results where there are 2 consecutive dates)



This is what I came up with



SELECT a.timestamp_intersecting_date d1,b.timestamp_intersecting_date d2, 
a."DID",
a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
RANK () OVER (
PARTITION BY a.timestamp_intersecting_date
ORDER BY a.timestamp_intersecting_max DESC
) timestamp_d1_rank ,
RANK () OVER (
PARTITION BY b.timestamp_intersecting_date
ORDER BY b.timestamp_intersecting_max ASC
) timestamp_d2_rank,
a.coords_centroid, b.coords_centroid
FROM
signals a
INNER JOIN signals b ON (a."DID" = b."DID")
WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
AND a."DID" = b."DID"
--AND timestamp_d1_rank = 1
--AND timestamp_d2_rank = 1
ORDER BY a."DID", t1 desc, t2 asc


thanks!










share|improve this question


























  • Yes, you can’t refer to them in the where clause as window functions are evaluated after the where clause. You can put your query into a with clause, or wrap it as a subquery.

    – Colin 't Hart
    6 hours ago

















4















been trying to get this query to work, it's almost perfect , but I just need to add the commented out 'where' condition and it'll do exactly what I want, but when I uncomment,I get an error 'column doesnt exist'. Been having trouble figuring out the syntax for this, would appreciate any help!



I basically have a table with date, timestamp, DID, coordinates



I want a query that will return rows with the last coordinate from day X, and the first coord from day X+1 , and the coordinates (so it will only return results where there are 2 consecutive dates)



This is what I came up with



SELECT a.timestamp_intersecting_date d1,b.timestamp_intersecting_date d2, 
a."DID",
a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
RANK () OVER (
PARTITION BY a.timestamp_intersecting_date
ORDER BY a.timestamp_intersecting_max DESC
) timestamp_d1_rank ,
RANK () OVER (
PARTITION BY b.timestamp_intersecting_date
ORDER BY b.timestamp_intersecting_max ASC
) timestamp_d2_rank,
a.coords_centroid, b.coords_centroid
FROM
signals a
INNER JOIN signals b ON (a."DID" = b."DID")
WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
AND a."DID" = b."DID"
--AND timestamp_d1_rank = 1
--AND timestamp_d2_rank = 1
ORDER BY a."DID", t1 desc, t2 asc


thanks!










share|improve this question


























  • Yes, you can’t refer to them in the where clause as window functions are evaluated after the where clause. You can put your query into a with clause, or wrap it as a subquery.

    – Colin 't Hart
    6 hours ago













4












4








4








been trying to get this query to work, it's almost perfect , but I just need to add the commented out 'where' condition and it'll do exactly what I want, but when I uncomment,I get an error 'column doesnt exist'. Been having trouble figuring out the syntax for this, would appreciate any help!



I basically have a table with date, timestamp, DID, coordinates



I want a query that will return rows with the last coordinate from day X, and the first coord from day X+1 , and the coordinates (so it will only return results where there are 2 consecutive dates)



This is what I came up with



SELECT a.timestamp_intersecting_date d1,b.timestamp_intersecting_date d2, 
a."DID",
a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
RANK () OVER (
PARTITION BY a.timestamp_intersecting_date
ORDER BY a.timestamp_intersecting_max DESC
) timestamp_d1_rank ,
RANK () OVER (
PARTITION BY b.timestamp_intersecting_date
ORDER BY b.timestamp_intersecting_max ASC
) timestamp_d2_rank,
a.coords_centroid, b.coords_centroid
FROM
signals a
INNER JOIN signals b ON (a."DID" = b."DID")
WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
AND a."DID" = b."DID"
--AND timestamp_d1_rank = 1
--AND timestamp_d2_rank = 1
ORDER BY a."DID", t1 desc, t2 asc


thanks!










share|improve this question
















been trying to get this query to work, it's almost perfect , but I just need to add the commented out 'where' condition and it'll do exactly what I want, but when I uncomment,I get an error 'column doesnt exist'. Been having trouble figuring out the syntax for this, would appreciate any help!



I basically have a table with date, timestamp, DID, coordinates



I want a query that will return rows with the last coordinate from day X, and the first coord from day X+1 , and the coordinates (so it will only return results where there are 2 consecutive dates)



This is what I came up with



SELECT a.timestamp_intersecting_date d1,b.timestamp_intersecting_date d2, 
a."DID",
a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
RANK () OVER (
PARTITION BY a.timestamp_intersecting_date
ORDER BY a.timestamp_intersecting_max DESC
) timestamp_d1_rank ,
RANK () OVER (
PARTITION BY b.timestamp_intersecting_date
ORDER BY b.timestamp_intersecting_max ASC
) timestamp_d2_rank,
a.coords_centroid, b.coords_centroid
FROM
signals a
INNER JOIN signals b ON (a."DID" = b."DID")
WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
AND a."DID" = b."DID"
--AND timestamp_d1_rank = 1
--AND timestamp_d2_rank = 1
ORDER BY a."DID", t1 desc, t2 asc


thanks!







postgresql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 16 hours ago







roy naufal

















asked 17 hours ago









roy naufalroy naufal

1374 bronze badges




1374 bronze badges















  • Yes, you can’t refer to them in the where clause as window functions are evaluated after the where clause. You can put your query into a with clause, or wrap it as a subquery.

    – Colin 't Hart
    6 hours ago

















  • Yes, you can’t refer to them in the where clause as window functions are evaluated after the where clause. You can put your query into a with clause, or wrap it as a subquery.

    – Colin 't Hart
    6 hours ago
















Yes, you can’t refer to them in the where clause as window functions are evaluated after the where clause. You can put your query into a with clause, or wrap it as a subquery.

– Colin 't Hart
6 hours ago





Yes, you can’t refer to them in the where clause as window functions are evaluated after the where clause. You can put your query into a with clause, or wrap it as a subquery.

– Colin 't Hart
6 hours ago










2 Answers
2






active

oldest

votes


















2
















You cannot use window/ranking functions or their aliases in the WHERE clause because they are evaluated in SELECT, after the WHERE has been evaluated.



You can use a subquery (derived table or CTE) to process a second WHERE clause, after the window functions have been evaluated:



SELECT d1, d2,
"DID",
t1, t2,
coords_centroid_a,
coords_centroid_b
FROM
(
SELECT a.timestamp_intersecting_date d1, b.timestamp_intersecting_date d2,
a."DID",
a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
RANK () OVER (
PARTITION BY a.timestamp_intersecting_date
ORDER BY a.timestamp_intersecting_max DESC
) timestamp_d1_rank ,
RANK () OVER (
PARTITION BY b.timestamp_intersecting_date
ORDER BY b.timestamp_intersecting_max ASC
) timestamp_d2_rank,
a.coords_centroid AS coords_centroid_a,
b.coords_centroid AS coords_centroid_b
FROM
signals a
INNER JOIN signals b ON (a."DID" = b."DID")
WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
AND a."DID" = b."DID"
) AS t
WHERE t.timestamp_d1_rank = 1
AND t.timestamp_d2_rank = 1
ORDER BY "DID", t1 DESC, t2 ASC ;





share|improve this answer

























  • thanks, that worked...i tried something similar but using WITH t AS ( slect ..., what you put in th from statement) select t.*, from t then joins where ranks=1/2, it was forcing me to add the columsn to group by or use aggregates, it ended up looking like this, mind telling me my mess up ? thanks pastebin.com/5aN3E29k

    – roy naufal
    4 hours ago











  • Ah, you have both GROUP BY a."DID" to get MAX/MIN and window functions there. There are ways that that's valid but it's usually complicated.

    – ypercubeᵀᴹ
    3 hours ago











  • If my query above solved the issue, use it. You cab use a CTE of course but that may result in different performance, as Postgres materializes CTE results (at least in versions less than 12).

    – ypercubeᵀᴹ
    3 hours ago


















3
















You cannot use aliases in WHERE clauses!



To demonstrate, consider this example (fiddle).



CREATE TABLE foo (bar INT);


Populate it:



INSERT INTO foo VALUES (1), (2), (3);


Then



SELECT bar AS baz
FROM foo
WHERE baz = 2;


Causes the error:



ERROR: column "baz" does not exist
LINE 2: where baz = 2;
^
HINT: Perhaps you meant to reference the column "foo.bar".


You didn't post your error message or PostgreSQL version, but your problem is that timestamp_d1_rank and timestamp_d2_rank are aliases.



Maybe the PostgreSQL hint isn't obvious in your case because of the Window function? I'm afraid you're going to have to put the entire expression into your WHERE clause! Or, you could consider using a CTE (i.e. WITH clause) as outlined here.



For a good explanation of this issue, see here.






share|improve this answer





























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "182"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f247275%2frank-used-in-where-returns-invalid-column-but-exists-in-results-set%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2
















    You cannot use window/ranking functions or their aliases in the WHERE clause because they are evaluated in SELECT, after the WHERE has been evaluated.



    You can use a subquery (derived table or CTE) to process a second WHERE clause, after the window functions have been evaluated:



    SELECT d1, d2,
    "DID",
    t1, t2,
    coords_centroid_a,
    coords_centroid_b
    FROM
    (
    SELECT a.timestamp_intersecting_date d1, b.timestamp_intersecting_date d2,
    a."DID",
    a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
    RANK () OVER (
    PARTITION BY a.timestamp_intersecting_date
    ORDER BY a.timestamp_intersecting_max DESC
    ) timestamp_d1_rank ,
    RANK () OVER (
    PARTITION BY b.timestamp_intersecting_date
    ORDER BY b.timestamp_intersecting_max ASC
    ) timestamp_d2_rank,
    a.coords_centroid AS coords_centroid_a,
    b.coords_centroid AS coords_centroid_b
    FROM
    signals a
    INNER JOIN signals b ON (a."DID" = b."DID")
    WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
    AND a."DID" = b."DID"
    ) AS t
    WHERE t.timestamp_d1_rank = 1
    AND t.timestamp_d2_rank = 1
    ORDER BY "DID", t1 DESC, t2 ASC ;





    share|improve this answer

























    • thanks, that worked...i tried something similar but using WITH t AS ( slect ..., what you put in th from statement) select t.*, from t then joins where ranks=1/2, it was forcing me to add the columsn to group by or use aggregates, it ended up looking like this, mind telling me my mess up ? thanks pastebin.com/5aN3E29k

      – roy naufal
      4 hours ago











    • Ah, you have both GROUP BY a."DID" to get MAX/MIN and window functions there. There are ways that that's valid but it's usually complicated.

      – ypercubeᵀᴹ
      3 hours ago











    • If my query above solved the issue, use it. You cab use a CTE of course but that may result in different performance, as Postgres materializes CTE results (at least in versions less than 12).

      – ypercubeᵀᴹ
      3 hours ago















    2
















    You cannot use window/ranking functions or their aliases in the WHERE clause because they are evaluated in SELECT, after the WHERE has been evaluated.



    You can use a subquery (derived table or CTE) to process a second WHERE clause, after the window functions have been evaluated:



    SELECT d1, d2,
    "DID",
    t1, t2,
    coords_centroid_a,
    coords_centroid_b
    FROM
    (
    SELECT a.timestamp_intersecting_date d1, b.timestamp_intersecting_date d2,
    a."DID",
    a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
    RANK () OVER (
    PARTITION BY a.timestamp_intersecting_date
    ORDER BY a.timestamp_intersecting_max DESC
    ) timestamp_d1_rank ,
    RANK () OVER (
    PARTITION BY b.timestamp_intersecting_date
    ORDER BY b.timestamp_intersecting_max ASC
    ) timestamp_d2_rank,
    a.coords_centroid AS coords_centroid_a,
    b.coords_centroid AS coords_centroid_b
    FROM
    signals a
    INNER JOIN signals b ON (a."DID" = b."DID")
    WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
    AND a."DID" = b."DID"
    ) AS t
    WHERE t.timestamp_d1_rank = 1
    AND t.timestamp_d2_rank = 1
    ORDER BY "DID", t1 DESC, t2 ASC ;





    share|improve this answer

























    • thanks, that worked...i tried something similar but using WITH t AS ( slect ..., what you put in th from statement) select t.*, from t then joins where ranks=1/2, it was forcing me to add the columsn to group by or use aggregates, it ended up looking like this, mind telling me my mess up ? thanks pastebin.com/5aN3E29k

      – roy naufal
      4 hours ago











    • Ah, you have both GROUP BY a."DID" to get MAX/MIN and window functions there. There are ways that that's valid but it's usually complicated.

      – ypercubeᵀᴹ
      3 hours ago











    • If my query above solved the issue, use it. You cab use a CTE of course but that may result in different performance, as Postgres materializes CTE results (at least in versions less than 12).

      – ypercubeᵀᴹ
      3 hours ago













    2














    2










    2









    You cannot use window/ranking functions or their aliases in the WHERE clause because they are evaluated in SELECT, after the WHERE has been evaluated.



    You can use a subquery (derived table or CTE) to process a second WHERE clause, after the window functions have been evaluated:



    SELECT d1, d2,
    "DID",
    t1, t2,
    coords_centroid_a,
    coords_centroid_b
    FROM
    (
    SELECT a.timestamp_intersecting_date d1, b.timestamp_intersecting_date d2,
    a."DID",
    a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
    RANK () OVER (
    PARTITION BY a.timestamp_intersecting_date
    ORDER BY a.timestamp_intersecting_max DESC
    ) timestamp_d1_rank ,
    RANK () OVER (
    PARTITION BY b.timestamp_intersecting_date
    ORDER BY b.timestamp_intersecting_max ASC
    ) timestamp_d2_rank,
    a.coords_centroid AS coords_centroid_a,
    b.coords_centroid AS coords_centroid_b
    FROM
    signals a
    INNER JOIN signals b ON (a."DID" = b."DID")
    WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
    AND a."DID" = b."DID"
    ) AS t
    WHERE t.timestamp_d1_rank = 1
    AND t.timestamp_d2_rank = 1
    ORDER BY "DID", t1 DESC, t2 ASC ;





    share|improve this answer













    You cannot use window/ranking functions or their aliases in the WHERE clause because they are evaluated in SELECT, after the WHERE has been evaluated.



    You can use a subquery (derived table or CTE) to process a second WHERE clause, after the window functions have been evaluated:



    SELECT d1, d2,
    "DID",
    t1, t2,
    coords_centroid_a,
    coords_centroid_b
    FROM
    (
    SELECT a.timestamp_intersecting_date d1, b.timestamp_intersecting_date d2,
    a."DID",
    a.timestamp_intersecting_max t1, b.timestamp_intersecting_min t2,
    RANK () OVER (
    PARTITION BY a.timestamp_intersecting_date
    ORDER BY a.timestamp_intersecting_max DESC
    ) timestamp_d1_rank ,
    RANK () OVER (
    PARTITION BY b.timestamp_intersecting_date
    ORDER BY b.timestamp_intersecting_max ASC
    ) timestamp_d2_rank,
    a.coords_centroid AS coords_centroid_a,
    b.coords_centroid AS coords_centroid_b
    FROM
    signals a
    INNER JOIN signals b ON (a."DID" = b."DID")
    WHERE (b.timestamp_intersecting_date = a.timestamp_intersecting_date + INTERVAL '1 DAY')
    AND a."DID" = b."DID"
    ) AS t
    WHERE t.timestamp_d1_rank = 1
    AND t.timestamp_d2_rank = 1
    ORDER BY "DID", t1 DESC, t2 ASC ;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 7 hours ago









    ypercubeᵀᴹypercubeᵀᴹ

    81k11 gold badges140 silver badges230 bronze badges




    81k11 gold badges140 silver badges230 bronze badges















    • thanks, that worked...i tried something similar but using WITH t AS ( slect ..., what you put in th from statement) select t.*, from t then joins where ranks=1/2, it was forcing me to add the columsn to group by or use aggregates, it ended up looking like this, mind telling me my mess up ? thanks pastebin.com/5aN3E29k

      – roy naufal
      4 hours ago











    • Ah, you have both GROUP BY a."DID" to get MAX/MIN and window functions there. There are ways that that's valid but it's usually complicated.

      – ypercubeᵀᴹ
      3 hours ago











    • If my query above solved the issue, use it. You cab use a CTE of course but that may result in different performance, as Postgres materializes CTE results (at least in versions less than 12).

      – ypercubeᵀᴹ
      3 hours ago

















    • thanks, that worked...i tried something similar but using WITH t AS ( slect ..., what you put in th from statement) select t.*, from t then joins where ranks=1/2, it was forcing me to add the columsn to group by or use aggregates, it ended up looking like this, mind telling me my mess up ? thanks pastebin.com/5aN3E29k

      – roy naufal
      4 hours ago











    • Ah, you have both GROUP BY a."DID" to get MAX/MIN and window functions there. There are ways that that's valid but it's usually complicated.

      – ypercubeᵀᴹ
      3 hours ago











    • If my query above solved the issue, use it. You cab use a CTE of course but that may result in different performance, as Postgres materializes CTE results (at least in versions less than 12).

      – ypercubeᵀᴹ
      3 hours ago
















    thanks, that worked...i tried something similar but using WITH t AS ( slect ..., what you put in th from statement) select t.*, from t then joins where ranks=1/2, it was forcing me to add the columsn to group by or use aggregates, it ended up looking like this, mind telling me my mess up ? thanks pastebin.com/5aN3E29k

    – roy naufal
    4 hours ago





    thanks, that worked...i tried something similar but using WITH t AS ( slect ..., what you put in th from statement) select t.*, from t then joins where ranks=1/2, it was forcing me to add the columsn to group by or use aggregates, it ended up looking like this, mind telling me my mess up ? thanks pastebin.com/5aN3E29k

    – roy naufal
    4 hours ago













    Ah, you have both GROUP BY a."DID" to get MAX/MIN and window functions there. There are ways that that's valid but it's usually complicated.

    – ypercubeᵀᴹ
    3 hours ago





    Ah, you have both GROUP BY a."DID" to get MAX/MIN and window functions there. There are ways that that's valid but it's usually complicated.

    – ypercubeᵀᴹ
    3 hours ago













    If my query above solved the issue, use it. You cab use a CTE of course but that may result in different performance, as Postgres materializes CTE results (at least in versions less than 12).

    – ypercubeᵀᴹ
    3 hours ago





    If my query above solved the issue, use it. You cab use a CTE of course but that may result in different performance, as Postgres materializes CTE results (at least in versions less than 12).

    – ypercubeᵀᴹ
    3 hours ago













    3
















    You cannot use aliases in WHERE clauses!



    To demonstrate, consider this example (fiddle).



    CREATE TABLE foo (bar INT);


    Populate it:



    INSERT INTO foo VALUES (1), (2), (3);


    Then



    SELECT bar AS baz
    FROM foo
    WHERE baz = 2;


    Causes the error:



    ERROR: column "baz" does not exist
    LINE 2: where baz = 2;
    ^
    HINT: Perhaps you meant to reference the column "foo.bar".


    You didn't post your error message or PostgreSQL version, but your problem is that timestamp_d1_rank and timestamp_d2_rank are aliases.



    Maybe the PostgreSQL hint isn't obvious in your case because of the Window function? I'm afraid you're going to have to put the entire expression into your WHERE clause! Or, you could consider using a CTE (i.e. WITH clause) as outlined here.



    For a good explanation of this issue, see here.






    share|improve this answer































      3
















      You cannot use aliases in WHERE clauses!



      To demonstrate, consider this example (fiddle).



      CREATE TABLE foo (bar INT);


      Populate it:



      INSERT INTO foo VALUES (1), (2), (3);


      Then



      SELECT bar AS baz
      FROM foo
      WHERE baz = 2;


      Causes the error:



      ERROR: column "baz" does not exist
      LINE 2: where baz = 2;
      ^
      HINT: Perhaps you meant to reference the column "foo.bar".


      You didn't post your error message or PostgreSQL version, but your problem is that timestamp_d1_rank and timestamp_d2_rank are aliases.



      Maybe the PostgreSQL hint isn't obvious in your case because of the Window function? I'm afraid you're going to have to put the entire expression into your WHERE clause! Or, you could consider using a CTE (i.e. WITH clause) as outlined here.



      For a good explanation of this issue, see here.






      share|improve this answer





























        3














        3










        3









        You cannot use aliases in WHERE clauses!



        To demonstrate, consider this example (fiddle).



        CREATE TABLE foo (bar INT);


        Populate it:



        INSERT INTO foo VALUES (1), (2), (3);


        Then



        SELECT bar AS baz
        FROM foo
        WHERE baz = 2;


        Causes the error:



        ERROR: column "baz" does not exist
        LINE 2: where baz = 2;
        ^
        HINT: Perhaps you meant to reference the column "foo.bar".


        You didn't post your error message or PostgreSQL version, but your problem is that timestamp_d1_rank and timestamp_d2_rank are aliases.



        Maybe the PostgreSQL hint isn't obvious in your case because of the Window function? I'm afraid you're going to have to put the entire expression into your WHERE clause! Or, you could consider using a CTE (i.e. WITH clause) as outlined here.



        For a good explanation of this issue, see here.






        share|improve this answer















        You cannot use aliases in WHERE clauses!



        To demonstrate, consider this example (fiddle).



        CREATE TABLE foo (bar INT);


        Populate it:



        INSERT INTO foo VALUES (1), (2), (3);


        Then



        SELECT bar AS baz
        FROM foo
        WHERE baz = 2;


        Causes the error:



        ERROR: column "baz" does not exist
        LINE 2: where baz = 2;
        ^
        HINT: Perhaps you meant to reference the column "foo.bar".


        You didn't post your error message or PostgreSQL version, but your problem is that timestamp_d1_rank and timestamp_d2_rank are aliases.



        Maybe the PostgreSQL hint isn't obvious in your case because of the Window function? I'm afraid you're going to have to put the entire expression into your WHERE clause! Or, you could consider using a CTE (i.e. WITH clause) as outlined here.



        For a good explanation of this issue, see here.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 7 hours ago

























        answered 12 hours ago









        VéraceVérace

        17.4k3 gold badges37 silver badges55 bronze badges




        17.4k3 gold badges37 silver badges55 bronze badges































            draft saved

            draft discarded















































            Thanks for contributing an answer to Database Administrators Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f247275%2frank-used-in-where-returns-invalid-column-but-exists-in-results-set%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її