Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best and most efficient method of fetching the maximum value from an Int column?

Tags:

realm

swift2

What is the best and most efficient method of fetching the maximum value from an Int column?

Idea A

let maxId = realm.objects(Books).sorted("id").last

Idea B

let maxId = realm.objects(Books).sorted("id", ascending: false).first

Or another idea?

(Yes my code snippets will only return the object with the highest ID, not the actual value)

like image 946
Ian Bradbury Avatar asked Oct 23 '15 07:10

Ian Bradbury


2 Answers

I believe it should work in the following way

 if let maxValue =  realm.objects(Books).max("id") as Int?{

 // Do some stuff 
 }

Or just

let maxValue =  realm.objects(Books).max("id") as Int?

To make my answer complete I decided to add the code to fetch the min value: realm.objects(Books).min("id") as Int?

like image 138
ProblemSlover Avatar answered Dec 06 '22 18:12

ProblemSlover


Following on from @ProblemSlover's answer. I created a small app that throws 10000 records into a realm class - calling a function to fetch the max value and using that to set the ID column. I wanted to see some metrics (I ran the test 3 times to get an average). As you can see the MAX function is 2.3 times quicker than sorted/last and nearly 8 times quicker than ascending/first. Sometimes it's just good to know. :)

enter image description here

like image 37
Ian Bradbury Avatar answered Dec 06 '22 18:12

Ian Bradbury