I have a layer of points corresponding to the vertices extracted from a polygon, and from these I need to obtain the two maximum values and save them in a new layer of points.

Because I have more than 150 layers of points I would like to know if it is possible to do it without having to open the table of attributes of each of these and select the values that interest me.

I tried using the field calculator using the expression "maximum(expression[,group_by][,filter])" but that would not have the second maximum.

first two maximum values


  • 2
    Do u mean u're searching a way to achieve this programmatically for your 150 layers ? Are they opened ? Are they named using the same scheme ? Getting the two max. values is easy using a query on the table but is your question rather how to automate the whole process ?
    – Snaileater
    Commented Mar 29, 2019 at 6:50
  • 2
    Of course it isn't possible to find attribute values without opening the attribute table. But this is trivially simple to script. What have you tried?
    – Vince
    Commented Mar 29, 2019 at 7:52
  • Yes, I understand that it is essential to access the attribute table. I already tried the field calculator with the expression "maximun" but I would need the second highest value. How could I implement a query for this value?
    – John
    Commented Mar 29, 2019 at 15:54

1 Answer 1


This expression will give you the second-largest value:

array_last(array_sort(array_remove_all( array_agg( "fieldname"), maximum("fieldname"))))

It works by

  1. put all the "fieldname" values into an array (ie, a list)
  2. remove all instances of the maximum value from the array
  3. sort the array from smallest to largest
  4. extract the last value in the array

Note: This solution will work in QGIS 3.6 and later. The array_sort function doesn't exist in earlier versions.

  • Happy to help. You can mark this answer as accepted by clicking the checkmark next to the answer. That way others with the same question will know that this method works.
    – csk
    Commented Mar 29, 2019 at 19:42

Your Answer

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

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