Skip to content

Instantly share code, notes, and snippets.

@genakim
Forked from hackimov/GROUP_MAXIMUM.SQL
Created September 13, 2019 10:06
Show Gist options
  • Save genakim/d7b3ff8f6b83b5cb8a969a0c4763898d to your computer and use it in GitHub Desktop.
Save genakim/d7b3ff8f6b83b5cb8a969a0c4763898d to your computer and use it in GitHub Desktop.
#SQL #MAXIMUM #WITHOUT_GROUP_BY #SPEED #QUERY
SELECT maintable.*
FROM TABLE_NAME maintable
LEFT OUTER JOIN TABLE_NAME temporarytable
ON maintable.GROUPING_BY_COLUMN = temporarytable.GROUPING_BY_COLUMN
AND maintable.COLUMN_WHERE_THE_MAXIMUM_IS_NEEDED < temporarytable.COLUMN_WHERE_THE_MAXIMUM_IS_NEEDED
WHERE temporarytable.COLUMN_WHERE_THE_MAXIMUM_IS_NEEDED IS NULL
ORDER BY PRIMARY_KEY_COLUMN DESC
LIMIT 50;
@genakim
Copy link
Author

genakim commented Sep 13, 2019

An alternative way to get the maximum value from a group. This query does not require aggregation, as is the case with “GROUP BY”.

In addition, when grouping using “GROUP BY”, each of the groups is sorted by primary key, which also takes a lot of time.

My query compares the values of one table with another. Until he can find nothing more. If nothing else is found, then this is the maximum.

This query can help you save time getting the maximum value from the group.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment