Skip to content
Advertisement

How to add PostGIS SQL SELECT query as layer to QGIS 3 project using Python console?

I want to add a PostGIS SELECT query as a new layer to a QGIS 3 project using the Python console.

It is a simple process to do this using the SQL Window in the DB Manager of QGIS. Here you can create a layer from any SQL query of a PostGIS enabled PostgreSQL database.

The following works for adding an entire PostGIS table and I’m aware a filter can be added by providing a fourth argument to uri.setDataSource(). However, this method, to my knowledge, does not allow you to do multi table queries and joins.

JavaScript

Ideally I would like to replace "my_table" with an SQL query like SELECT * FROM my_table. This would allow you to extend functionality to more complicated queries like:

JavaScript

The eventual goal is to then implement this code in a QGIS plugin.

Any help would be much appreciated!

Advertisement

Answer

I found the solution here:

https://gis.stackexchange.com/a/197800

Simply, you must leave the schema blank and include it in the SQL query instead.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement