I am relatively new to postgres and am using version 9.4 . I have a simple function in Java that I been told would be more efficient if I let postgres do it. My function takes an Integer and a String data that comes from the database and transforms them .This is my function: Notice it takes an Integer and a String
private static String difference(Integer i,String created_on) {
String id = "";
if (i < 60) {
...
}
else if (i >= 60 && i < 1440) {
....
}
else if (i >= 1440 && i < 10080) {
....
}
else {
....
}
return id;
}
This is my query now the Created_on is the String and last_reply is the Integer
"SELECT created_on as created_on,
last_reply as last_reply;
Once the data comes from the database I put it in a loop and transform it by doing this:
for(i=0;i<10;i++)
{
jo = new JSONObject();
jo.put("last_reply", difference(rs.getInt("last_reply",
rs.getString("created_on"))));
}
As you can see the data transformation happens here
difference(rs.getInt("last_reply", rs.getString("created_on")
My question now is how can I replicate that function and save it in postgres so that I can do a query like this
**
**"SELECT difference(last_reply,created_on) as newvalue, created_on as created_on,
last_reply as last_reply;**
** As I know that from a performance standpoint it is better to have the database do that rather than loop through the data using Java. Any suggestions would be great ...
Update
The function is used for a social app that measures the time something is posted in terms of Minutes. If it is less than 60 minutes then it will return something like "6 mins ago etc", if it is between 60-1440 then it will return " 4 hrs ago etc." . I have already worked out the calculations inside the If-else statements but did not include it so that the code looks more presentable.
Here is the full Method
private static String difference(Integer i,String created_on) {
String id = "";
if (i < 60) {
if(i<1)
id = "Now";
else
id = i + " min";
}
else if (i >= 60 && i < 1440) {
i=(i/60);
if(i==0)
{i=1;}
id = i + " hrs";
} else if (i >= 1440 && i < 10080) {
i=(i/1440);
id = i + " day(s)";
}
else {
// Posted longer than 7 days so Created_On will show date created
// Passed down to the id String
id = created_on;
}
return id;
}
difference()method? You're just showing a lot of nonsensicalifclauses and theStringparameter isn't used anywhere.String created_ondo? Why do you pass it as a parameter if you're not using it anywhere? You have a lot of text in your question, but very little information.if(i < 60)then you recheckif(i < 1)(i.e. if i == 0). You're also doing a redundant check fori==0in the second else, it can never happen sinceiis at least60. Then instead of creating a stored procedure I'd just go with aCASE -THEN.