Search code examples
sqlpostgresqlnode-postgres

Cannot run simple WHERE query in node-postgres


This is my table:

-- Table Definition ----------------------------------------------

CREATE TABLE "Friendships" (
    id integer DEFAULT nextval('"Friendships_id_seq"'::regclass) PRIMARY KEY,
    "createdAt" timestamp with time zone NOT NULL,
    "updatedAt" timestamp with time zone NOT NULL,
    "fromUserId" integer NOT NULL REFERENCES "Users"(id),
    "toUserId" integer NOT NULL REFERENCES "Users"(id)
);

-- Indices -------------------------------------------------------

CREATE UNIQUE INDEX "Friendships_pkey" ON "Friendships"(id int4_ops);

This is my query:

const { Client } = require('pg')
const pgClient = new Client({ user: PG_USERNAME, host: PG_HOST, database: PG_DB, password: PG_PASSWORD, port: 5432 })
pgClient.connect()

pgClient.query({
            name: 'fetch-friendships',
            text: 'SELECT * FROM Friendships WHERE fromUserId = $1',
            values: [1]
        }, (err, res) => {
            console.log(err)
            console.log(res)
        })

Error: relation "friendships" does not exist

cosmos=> \dt;
            List of relations
 Schema |      Name       | Type  | Owner 
--------+-----------------+-------+-------
 public | AuthCodes       | table | pangu
 public | BirthRecords    | table | pangu
 public | Births          | table | pangu
 public | Friendships     | table | pangu
 public | InvitationCodes | table | pangu
 public | SequelizeMeta   | table | pangu
 public | Users           | table | pangu
(7 rows)

cosmos=> SELECT * FROM Friendships;
ERROR:  relation "friendships" does not exist
LINE 1: SELECT * FROM Friendships;

Solution

  • In postgres you need use double quotes if create the table with upper cases.

    Without double quotes

    Friendships -> friendships
    

    As you can see for the error:

    ERROR: relation "friendships" does not exist

    but you create

    CREATE TABLE "Friendships" (
    

    So you need use "Friendships"

    Same goes for Tables, Field names or Function names.