Skip to content

Instantly share code, notes, and snippets.

@han-wong
Last active April 1, 2021 13:20
Show Gist options
  • Save han-wong/64e106320da9b0b3ba2fb07e28fb99fb to your computer and use it in GitHub Desktop.
Save han-wong/64e106320da9b0b3ba2fb07e28fb99fb to your computer and use it in GitHub Desktop.
Average and median functions in MySQL
USE new_schema; #schema name
SELECT * FROM new_table ORDER BY new_column; #order by column
SELECT AVG(new_column) FROM new_table; #average
SET @median = (SELECT COUNT(*) FROM new_table) DIV 2; #variable to use as 'offset' in 'limit'
PREPARE median FROM 'SELECT * FROM new_table ORDER BY new_column LIMIT ?,1'; #? will be replaced by variable from 'using'
EXECUTE median USING @median; #execute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment