Select NULL Values in SQLAlchemy
In this article, we will see how to select NULL values into a PostgreSQL database using SQLAlchemy in Python.
For demonstration purposes first, let us create a sample table using SQLAlchemy in PostgreSQL as shown below
Creating a table using SQLAlchemy in PostgreSQL:
- Import necessary functions from SQLAlchemy package.
- Establish connection with the PostgreSQL database using create_engine() function as shown below
- Create a table called book_publisher with columns publisher_id, publisher_name, and publisher_estd
- Insert record into the tables using insert() and values() function as shown.
Syntax: engine = create_engine(dialect+driver://username:password@host:port/database_name)
- dialect – Name of the DBMS. The dialect is the system SQLAlchemy uses to communicate with various types of DBAPIs and databases like PostgreSQL, MySQL, MS SQL, etc.
- driver – Name of the DB API that moves information between SQLAlchemy and the database.
- Username – Name of the admin
- Password – Password of the admin
- host – Name of the host in which the database is hosted
- port – port number through which the database can be accessed
- database_name– Name of the database
Creating table for demonstration:
Selecting NULL values using SQLAlchemy in PostgreSQL
Using select() and where function, we can query data from our database. The NULL equivalent in python is None.
The other things remain the same, like conventional SQL querying. The query is passed to a execute() statement and output is stored in a result object and rows can be iterated to fetch all the rows
As we know from the output shown above, row 6 has None values and that is correctly returned in the below output
(6, None, None)