Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to Get features by their attributes (similar to Iqueryfilter in arcobjects) in Qgis using python? Instead of getting all features and filter it manually, is there any option to use whereclause to filter it out?

For Example: I have a field name called 'Counties'. It has more than fifty thousand of features.i.e not possible to fetch all features and filter it because of time consuming. So i can query it by using iqueryfilter.whereclause = 'Counties = Norwich' in arcobjects. Similar thing i need in PyQgis. kindly let me know whether its doable. If so, please give me an example

share|improve this question
up vote 5 down vote accepted

Update Please read this answer for a safer method of achieving the same

In case you experience performance issues you may still resort to original method described below.

The only way of forwarding a WHERE clause to the data provider (backend) at the moment is to use the setSubsetString method of QgsDataProvider

If you have a QgsVectorLayer assigned to a variable vl :

vl.setSubsetString( 'Counties = "Norwich"' )

This causes heavy side-effects, because the filter will then apply to the whole layer and not only to your query, so you have to carefully consider if this is really an option for your use case!

Any other option will require a seperate connection to the database or adding a new layer with a subsetString as outlined above.

share|improve this answer
Its working fine. just like definition query in Arcgis. Thanks a lot – venkat Apr 22 '13 at 12:29
I have 4 lakhs features in a shape file..its taking long time to execute this query 'Counties = "Norwich"'. is there any solutions to speedup the execution? – venkat Jun 10 '13 at 12:59
You can probably create an index on the column (untested) – Matthias Kuhn Jun 10 '13 at 13:02
Yes I created an index by using ArcCatalog. but no effect – venkat Jun 11 '13 at 5:22
This is a gdal issue. You can read up on it here . QGis 1.9 (master) provides vl.dataProvider().createAttributeIndex( fieldIndex ) as frontend to index creation. – Matthias Kuhn Jun 11 '13 at 6:04

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.