As per psycopg2 documentation the execute function takes variables as an extra parameter.

cursor.execute("""select * from table where type = %(value)s """, {"value": variable_value})

More examples in psycopg2 user manual..

Also please read carefully the section about SQL injection - the gist is, you should not quote parameters in your query, the execute function will take care of that to prevent the injection of harmful SQL.


Also to explain the error you are getting - the query you're sending is comparing two identifiers (type and variable_value). The table does not contain variable_value column, hence the error.

I believe, you intended to use string interpolation to construct the query, but you forgot the {}. It would work like this:

cursor.execute(f"""select * from table where type = '{variable_value}'""")

⚠️ but because of previously mentioned SQL injection, it is not a recommended way!.

Answer from botchniaque on Stack Overflow
🌐
PYnative
pynative.com › home › python › databases › python select from postgresql table using psycopg2
Python Select from PostgreSQL Table using psycopg2
March 9, 2021 - ... Next, prepare a SQL SELECT query to fetch rows from a table. You can select all or limited rows based on your need. If the where condition is used, then it decides the number of rows to fetch.
Discussions

python - Psycopg2 - Passing variable in the where clause - Stack Overflow
I am trying to run a SQL script in Python where I am passing a variable in the where clause as below: cursor.execute(f"""select * from table where type = variable_value""") In the above query, More on stackoverflow.com
🌐 stackoverflow.com
(Python psycopg) How do I add additional WHERE … AND … conditions to a SQL statement?
If I understand the use case, you’re having some user provided parameters passed in, but allowing them to be optional, which is why you want the AND statements to be pasted together. In that case, it’s best to add the AND statement in the original query, but structure it like this: AND (:var IS NULL OR columnname = :var) So, even if the parameter isn’t provided, your AND statement still works. Edit: that’s not verbatim, you’d replace :var with whatever formatting you’d need for a parameterized query. More on reddit.com
🌐 r/PostgreSQL
9
1
December 2, 2022
psycopg2 - Python/psycopg WHERE IN statement - Stack Overflow
What is the correct method to have the list (countryList) be available via %s in the SQL statement? # using psycopg2 countryList=['UK','France'] sql='SELECT * from countries WHERE country IN (%s)... More on stackoverflow.com
🌐 stackoverflow.com
postgresql - Python psycopg2 dynamic where clause with optional AND based on conditional - Stack Overflow
This probably isn't a new question but I have not been able to find a decent solution after googling and digging through SO for a while. I want to have a conditional AND added to my WHERE clause b... More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › python_data_access › python_postgresql_where_clause.htm
Python PostgreSQL - Where Clause
To fetch specific records from a table using the python program execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method. Following python example demonstrates the usage of WHERE command using python. ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-postgresql-where-clause
Python PostgreSQL - Where Clause - GeeksforGeeks
January 17, 2023 - In this article, we are going to see how to use the Where clause in PostgreSQL using Psycopg2 in Python. Where Clauses help us to easily deal with the databases. As we know we have a huge amount of data stored in our database, so extracting only useful and required information clauses is helpful.
🌐
Psycopg
psycopg.org › docs › usage.html
Basic module usage — Psycopg 2.9.12 documentation
The mapping is fairly customizable: see Adapting new Python types to SQL syntax and Type casting of SQL types into Python objects. You can also find a few other specialized adapters in the psycopg2.extras module.
🌐
Reddit
reddit.com › r/postgresql › (python psycopg) how do i add additional where … and … conditions to a sql statement?
r/PostgreSQL on Reddit: (Python psycopg) How do I add additional WHERE … AND … conditions to a SQL statement?
December 2, 2022 -

Using psycopg, I’d like to build a SQL statement according to certain conditions. There would be a base SELECT query, and then append WHERE. And then append AND. And then append another AND, etc.

I appreciate help on this!

Find elsewhere
🌐
Aklaver
aklaver.org › wordpress › 2018 › 04 › 21 › building-dynamic-sql-using-psycopg2
Building dynamic SQL using psycopg2 | This and That
April 21, 2018 - In the above %s is created as the placeholder for the first_name field value in the WHERE clause using the Placeholder class.
🌐
Stack Overflow
stackoverflow.com › questions › 44199167 › multiple-parameters-psycopg2-where-clause-syntax-error
python - Multiple parameters psycopg2 where clause - Syntax error - Stack Overflow
May 26, 2017 - python-2.7 · psycopg2 · Share ... Date modified (newest first) Date created (oldest first) 0 · You cannot put a WHERE clause into an INSERT statement - insert inserts new rows....
🌐
Dataquest Community
community.dataquest.io › q&a › non-dq courses
SQL : pass a list as a parameter using psycopg2 - Non-DQ Courses - Dataquest Community
November 21, 2020 - Hi, Despite Postgres course, I am still unable to pass a list as parameter with WHERE statement. Let say we want 10 item_id so that: list_id = [0,1,2,3,4,5,6,7,8,9] conn = psycopg2.connect... query = "SELECT * FROM table WHERE item_id = list_id;" pd.read_sql(query, con=conn) Obviously it doesn’t work, but someone knows how to pass a list as parameter ?
🌐
Psycopg
psycopg.org › docs › sql.html
psycopg2.sql – SQL string composition — Psycopg 2.9.12 documentation
class psycopg2.sql.Literal(wrapped)¶ · A Composable representing an SQL value to include in a query. Usually you will want to include placeholders in the query and pass values as execute() arguments. If however you really really need to include a literal value in the query you can use this object. The string returned by as_string() follows the normal adaptation rules for Python objects.
🌐
Tecladocode
pysql.tecladocode.com › section08 › lectures › 08_sql_string_composition
SQL String Composition | The Complete Python/PostgreSQL Course 2.0
from psycopg2 import sql table_name = input("Enter table you want to search in: ") column_name = input("Enter column you want to search by: ") search_value = input("Enter what value you're looking for: ") query = sql.SQL("SELECT * FROM {table} WHERE {column} = %s;") query = query.format( ...
🌐
pg_tileserv
access.crunchydata.com › documentation › psycopg2 › 2.7.6 › sql.html
psycopg - PostgreSQL database adapter for Python
from psycopg2 import sql cur.execute( sql.SQL("insert into {} values (%s, %s)") .format(sql.Identifier('my_table')), [10, 20]) The objects exposed by the sql module can be used to compose a query as a Python string (using the as_string() method) or passed directly to cursor methods such as execute() , executemany() , copy_expert() .
🌐
Stack Overflow
stackoverflow.com › questions › 78081432 › handling-a-dynamic-sql-query-in-psycopg2-with-multiple-where-condition
python - Handling a dynamic sql query in Psycopg2 with multiple WHERE condition - Stack Overflow
I want to execute a sql query dynamically with multiple WHERE conditions. the query is as below query = """SELECT * FROM UBO_EXCEPTION WHERE reg_nb = %s AND return_date = %s::date ...
🌐
GitHub
gist.github.com › jayu108 › bebd10b5b1648aab0531
psycopg2 -- with statement ; http://initd.org/psycopg/docs/usage.html#with-statement · GitHub
February 27, 2020 - psycopg2 -- with statement ; http://initd.org/psycopg/docs/usage.html#with-statement - psycopg2_with.py
🌐
ZetCode
zetcode.com › python › psycopg2
Python PostgreSQL proramming with psycopg2 module
January 29, 2024 - PostgreSQL Python tutorial with psycopg2 shows how to program PostgreSQL databases in Python with psycopg2 module.
🌐
Stack Overflow
stackoverflow.com › questions › 66232884 › psycopg2-not-empty-result-unless-where-clause-hard-coded
python - Psycopg2 not empty result unless WHERE clause hard coded - Stack Overflow
import psycopg2 db_conn = psycopg2.connect(dbname="pi", user="pi", password="raspberry") def lol(): cursor = db_conn.cursor() cursor.execute('SELECT * FROM trades_1_min LIMIT 1') res = cursor.fetchall() print(res) def get_latest(symbol): query = """SELECT TRIM(TRAILING FROM symbol) as symbol, timestamp, open, close, high, low, volume FROM trades_1_min WHERE symbol=%(symbol)s ORDER BY id DESC LIMIT 1""" with db_conn.cursor() as cursor: cursor.execute(query, {'symbol': symbol}) res = cursor.fetchall() cursor.close() return res return None def main(): lol() #print(get_latest("amd")) main()