Search code examples
mysqlsqlselectsql-order-byquery-optimization

optimise simple mysql query with order by on two columns


I've only just began to run explain on my queries and see that the type is All and I'm using filesort.

I'm not sure how to optimise even the simplest of queries, if anyone could provide guidance on the following query which just retrieves users and orders by their first name primarily and second name secondarily:

SELECT UserID, TRIM(FName) AS FName, TRIM(SName) as SName, pic
FROM users WHERE Blocked <> 1
ORDER BY FName, SName 
LIMIT  ?, 10

Table is created as follows:

CREATE TABLE IF NOT EXISTS `users` (
`UserID` int(11) NOT NULL,
  `FName` varchar(25) NOT NULL,
  `SName` varchar(25) NOT NULL,
  `Pword` varchar(50) NOT NULL,
  `Longitude` double NOT NULL,
  `Latitude` double NOT NULL,
  `DateJoined` bigint(20) NOT NULL,
  `Email` varchar(254) NOT NULL,
  `NotificationID` varchar(256) NOT NULL,
  `Pic` varchar(500) DEFAULT NULL,
  `Radius` int(11) NOT NULL,
  `ads` tinyint(1) NOT NULL,
  `Type` varchar(5) NOT NULL,
  `Blocked` tinyint(4) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=1469 DEFAULT CHARSET=latin1;

Explain gives the following:

id : 1
select_type : SIMPLE
table : users 
type : ALL
possible_keys : NULL
key  : NULL
key_len : NULL
ref : NULL
rows : 1141
Extra : Using where; Using filesort

Solution

  • Add index (Blocked, FName, SName)
    And change where to Blocked = 0, if it is possible