8/8/2023 0 Comments Postgres insert with selectWhile many answers here are suggesting using a CTE, that's not preferable. Which yields: key |val |color |lookup_key |įirst always use the standardized CREATE TABLE AS, SELECT INTO as suggested in other answers has been a deprecated syntax for over a decade. Or JOIN the values with another relationship (which again can be a regular table, view, etc.), e.g.: SELECT * Then you can get a Cartesian product with a CROSS JOIN (where the other relationship can be, of course, a regular table, view, etc.). You can inline them: SELECT *įROM (VALUES(0::INT, -99999::NUMERIC), (1, 100)) AS lookup(key, val) You really don't need to create a table nor use a CTE, if all you need is to use a few values in your queries. There are, however, many instances where the optimization fence can actually enhance performance, so this is something to be aware of, not to blindly avoid. There are many good reasons for using CTEs, but there can be quite a significant performance hit, if not used carefully. Note, also from the comments by a_horse_with_no_name, and in the OP's original question, this includes a cast to the correct datatypes inside the values list and uses a CTE (WITH) statement.Īlso, as pointed out in Evan Carrol's answer, in Postgres prior to version 12 a CTE query is always an optimization fence, ie, the CTE is always materialized. Therefore, while the above examples are valid for plain SQL, the CREATE TABLE form should be preferred. , but that the former is a superset of the latter and that SELECT INTO is used in plpgslq for assigning a value to a temporary variable - so it would fail in that case. SELECT * INTO temporary table temp_table FROM vals ĮDIT: As pointed out by a_horse_with_no_name, in the docs it states that CREATE TABLE AS. To actually create a temporary table in a similar fashion, use: WITH vals (k,v) AS (VALUES (0,-9999), (1, 100)) If you just want to select from some values, rather than just creating a table and inserting into it, you can do something like: WITH vals (k,v) AS (VALUES (0,-9999), (1, 100)) EDIT: I am leaving the original accepted answer as it is, but please note that the edit below, as suggested by a_horse_with_no_name, is the preferred method for creating a temporary table using VALUES.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |