Hi I'm doing a homework on psql databases for my software engineering class and one of the questions I had to do was "Find all the books that contain Python in them" so I tried using the WHERE syntax but it would give me 0 rows no books that have the word Python in the title but there clearly are in the books table can anyone help me out with this?
booktown=# SELECT books.title FROM books WHERE title NOT IN ('Python');
title
-----------------------------
The Shining
Dune
2001: A Space Odyssey
The Cat in the Hat
Bartholomew and the Oobleck
Franklin in the Dark
Goodnight Moon
Little Women
The Velveteen Rabbit
Dynamic Anatomy
The Tell-Tale Heart
Programming Python
Learning Python
Perl Cookbook
Practical PostgreSQL
(15 rows)
booktown=# SELECT books.title FROM books WHERE title IN ('Python');
title
-------
(0 rows)
booktown=# SELECT books.title FROM books WHERE title LIKE 'Python';
title
-------
(0 rows)
booktown=# SELECT books.title FROM books WHERE title LIKE 'Python';
CodePudding user response:
You should use the LIKE operator of Postgresql for pattern matching. The way you have queried will do exact matching. See examples at https://www.postgresqltutorial.com/postgresql-like/
CodePudding user response:
title IN ('Python') looks for all books the title of which is in the list. The list only consists of one entry 'Python'. There is no book with the title 'Python'.
title LIKE 'Python' looks for all books where the title matches the pattern 'Python'. As there is no wildcard character in the pattern (i.e. %, _), this looks for exact matches. Again, there is no book named 'Python'.
You want all titles that match the pattern "zero or more characters we don't care about, then the word Python, then again zero or more characters we are not interested in".
That is title LIKE '%Python%'.
