/******************************************************************************
  Display the median row of a table
  If count of record is odd, display 1 row. If count is even, display 2 rows
  Procedure takes a table name, and a column name to sort by
******************************************************************************/
DROP PROCEDURE median; 
/
CREATE PROCEDURE median(p_tablename varchar(10), p_column varchar(20))
BEGIN                                             
   SET @s1 =CONCAT("SELECT COUNT(*)/2 INTO @offset FROM ", p_tablename); 

   PREPARE statement FROM @s1; 
   EXECUTE statement; 
   DEALLOCATE PREPARE statement;

-- select @offset;                          -- debug

   IF (MOD(@offset,2) = .5)                 -- if fraction, therefore count is odd
       THEN SET @limit = 1;
       ELSE SET @limit = 2;
   END IF;
   SET @offset = @offset-1;                 -- backtrack starting point by 1 

--  select @limit;                          -- debug

   SET @s2 =CONCAT("SELECT * FROM ",p_tablename," ORDER BY ",p_column," LIMIT ?,?");

   PREPARE statement FROM  @s2; 
   EXECUTE statement USING @offset, @limit; 
   DEALLOCATE PREPARE statement; 
END; 
/
CALL median("payment", "amount");