In the GUI there is the Query Builder, but that does not seem to be easily available in Python. The processing (SEXTANTE) module has the qgis:selectbyattribute algorithm, but that only supports selecting by a single attribute. There is also QgsFeatureRequest.setFilterExpression, but apparently that is not available in current stable version (2.0.1 Dufour).

Do I have to write my own?

1 Answer 1


This is listed in the pyqgis cookbook.

PyQGIS Developer Cookbook 2.18

PyQGIS Developer Cookbook 3

You need to make use of the optional where clause.

uri = QgsDataSourceURI()
# set host name, port, database name, username and password
uri.setConnection("localhost", "5432", "dbname", "johny", "xxx")
# set database schema, table name, geometry column and optionaly
# subset (WHERE clause)
uri.setDataSource("public", "roads", "the_geom", "cityid = 2643")
vlayer = QgsVectorLayer(uri.uri(), "layer_name_you_like", "postgres")

Or if you want to filter an existing layer, you can use setSubsetString from QgsVectorLayer


  • Thanks, that'll work nicely! Only for vector layers, I guess, but that's all I need.
    – user23603
    Commented Oct 31, 2013 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.