Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to query once, then organize objects based on returned column value, or query twice with different conditions?

Tags:

java

sql

database

I have a table which I need to query, then organize the returned objects into two different lists based on a column value. I can either query the table once, retrieving the column by which I would differentiate the objects and arrange them by looping through the result set, or I can query twice with two different conditions and avoid the sorting process. Which method is generally better practice?

MY_TABLE

NAME    AGE    TYPE
John    25     A
Sarah   30     B
Rick    22     A
Susan   43     B

Either SELECT * FROM MY_TABLE, then sort in code based on returned types, or

SELECT NAME, AGE FROM MY_TABLE WHERE TYPE = 'A' followed by

SELECT NAME, AGE FROM MY_TABLE WHERE TYPE = 'B'

like image 554
Drazen Bjelovuk Avatar asked Jun 25 '14 14:06

Drazen Bjelovuk


People also ask

Does order matter in query?

Answer. No, the order of query parameters should not matter.

Do Joins slow down query?

Joins: If your query joins two tables in a way that substantially increases the row count of the result set, your query is likely to be slow. There's an example of this in the subqueries lesson. Aggregations: Combining multiple rows to produce a result requires more computation than simply retrieving those rows.


1 Answers

Logically, a DB query from a Java code will be more expensive than a loop within the code because querying the DB involves several steps such as connecting to DB, creating the SQL query, firing the query and getting the results back.

Besides, something can go wrong between firing the first and second query.

With an optimized single query and looping with the code, you can save a lot of time than firing two queries.

In your case, you can sort in the query itself if it helps:

SELECT * FROM MY_TABLE ORDER BY TYPE

In future if there are more types added to your table, you need not fire an additional query to retrieve it.

like image 177
Nikhil Talreja Avatar answered Sep 22 '22 05:09

Nikhil Talreja