Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Virtual Column—column does not exist?

Using PostgreSQL 8.4, I'm trying to put together the following query:

SELECT (field_a + field_b + field_c) AS virtual_field, *
FROM "entities" 
WHERE ("entities".thing_id = 9999 AND (virtual_field > 0)) 
AND (boolean_field = 't') 
ORDER BY virtual_field DESC

Unfortunately, I keep getting the following error:

PGError: ERROR:  column "virtual_field" does not exist
LINE 1: ...ies" ("entities".thing_id = 9999 AND (virtual_fiel...
                                                 ^

The error message is quite obvious, but I'll be damned if I can figure out the correct syntax for what I'm trying to do. field_a, field_b and field_c are all real columns in my entities table.

For reference, I'm using Rails (2.3.11) to compose the query. Here's the (anonymised) code I'm using:

Thing.entities.boolean_scope.find(:all, 
  :select     => "(field_a + field_b + field_c) AS virtual_field, *",
  :conditions => ['virtual_field > ?', value],
  :order      => 'virtual_field DESC'
)

My brain has failed me—can anyone help me figure it out?

like image 841
dnch Avatar asked Jul 07 '11 09:07

dnch


People also ask

How do I create a virtual column in PostgreSQL?

To create a generated column, use the GENERATED ALWAYS AS clause in CREATE TABLE , for example: CREATE TABLE people ( ..., height_cm numeric, height_in numeric GENERATED ALWAYS AS (height_cm / 2.54) STORED ); The keyword STORED must be specified to choose the stored kind of generated column.

How do you add column if not exists PostgreSQL?

The Postgres IF NOT EXISTS syntaxFirst, we specify the name of the table to which we want to add a column. We supply the IF NOT EXISTS option after the ADD COLUMN clause, and then we specify the name of the column and its data type.

Is an identity column defined as generated always?

SQL Reference Guide The above UPDATE statement will raise an exception saying that a user cannot set a value for an IDENTITY column that is defined as GENERATED ALWAYS. An IDENTITY column that is defined as GENERATED ALWAYS cannot be updated.

How do I add a column in PostgreSQL?

Syntax. The syntax to add a column in a table in PostgreSQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition; table_name.


1 Answers

If you put the "main" statement into a derived table, you can use the alias:

    SELECT *
    FROM 
    (
        SELECT (field_a + field_b + field_c) AS virtual_field,
               entities.*
        FROM entities 
    ) t
    WHERE thing_id = 9999 
      AND virtual_field > 0
      AND boolean_field = 't'
    ORDER BY virtual_field DESC

Btw: you don't need the expressioni boolean_field = 't' (if that is really a column of type boolean). AND boolean_field is enough as that is a valid boolean expression.

like image 189
a_horse_with_no_name Avatar answered Nov 15 '22 16:11

a_horse_with_no_name