Skip to content

Instantly share code, notes, and snippets.

@hrach
Last active December 13, 2015 23:19
Show Gist options
  • Save hrach/4990603 to your computer and use it in GitHub Desktop.
Save hrach/4990603 to your computer and use it in GitHub Desktop.
PostgreSQL subselect
CREATE TABLE book (
id serial NOT NULL,
author_id int NOT NULL,
translator_id int,
title varchar(50) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE book_tag (
book_id int NOT NULL,
tag_id int NOT NULL,
PRIMARY KEY (book_id, tag_id),
CONSTRAINT book_tag_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
);
SELECT * FROM "book" WHERE ("id" IN (SELECT "id" FROM "book_tag" WHERE ("tag_id" = ?)))
-- pass and return invalid result
-- how is it possible to select not existing column "id" from table "book_tag" without error?
-- correct query would be SELECT * FROM "book" WHERE ("id" IN (SELECT "book_id" FROM "book_tag" WHERE ("tag_id" = ?)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment