PHP Mysql tips
Published: Mon, 23 Jul 2007 09:38:05 GMT
Updated: Sat, 22 Mar 2025 15:38:02 GMT
Continuing from my earlier post on PHP performance, I thought I'd share a few Mysql tips that I've learnt over the years. Hope it helps someone and please leave a comment with your own tips or provide any corrections to the ones mentioned.
Word searching
- <pre lang="sql">SELECT * FROM table WHERE MATCH (`field`) AGAINST ('Keyword')</pre>
(Fastest)
2.<pre lang="sql">SELECT * FROM table WHERE MATCH (field
) AGAINST ('+Keyword' IN BOOLEAN MODE)</pre>
(Fast)
3.<pre lang="sql">SELECT * FROM table WHERE RLIKE '(^| +)Keyword($| +)'</pre> OR
<pre lang="sql">SELECT * FROM table WHERE RLIKE '([[:space:]]|[[:<:]])Keyword([[:space:]]|[[:>:]])'</pre>(Slow)
Contains searching
- <pre lang="sql">SELECT * FROM table WHERE MATCH (`field`) AGAINST ('Keyword*' IN BOOLEAN MODE)</pre>
(Fastest)
- <pre lang="sql">SELECT * FROM table WHERE field LIKE 'Keyword%'</pre>
(Fast)
- <pre lang="sql">SELECT * FROM table WHERE MATCH (`field`) AGAINST ('*Keyword*' IN BOOLEAN MODE)</pre>
(Slow)
- <pre lang="sql">SELECT * FROM table WHERE field LIKE '%Keyword%'</pre>
(Slow)
Recordsets
- <pre lang="sql">
SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE Condition LIMIT 0, 10 SELECT FOUND_ROWS() </pre>
(Fastest)
2.<pre lang="sql"> SELECT * FROM table WHERE Condition LIMIT 0, 10 SELECT COUNT(PrimaryKey) FROM table WHERE Condition </pre>
(Fast)
- <pre lang="php">
$result = mysql_query("SELECT * FROM table", $link); $num_rows = mysql_num_rows($result); </pre> (Very slow)
Joins
Use an INNER JOIN when you want the joining table to only have matching records that you specify in the join. Use LEFT JOIN when it doesn't matter if the records contain matching records or not.
<pre lang="sql"> SELECT * FROM products INNER JOIN suppliers ON suppliers.SupplierID = products.SupplierID </pre>Returns all products with a matching supplier.
<pre lang="sql"> SELECT * FROM products LEFT JOIN suppliers ON suppliers.SupplierID = products.SupplierID WHERE suppliers.SupplierID IS NULL </pre>Returns all products without a matching supplier.
Best practice
- Always use lowercase for table names. (If you use different OS's this is a must)
- Always prepend the table name to the field. E.g. ProductName, SupplierPostCode. This makes multiple joins very easy.
- Always create a primary id field with the name of the table followed by the id. e.g. ProductID
- Index fields used for joins.
- Use a separate logging table or transactions for logs of table updates, deletes etc.