May 11 2013

Mysql better way to select random records

Tagged Under : ,

MySQL
The easiest way to generate random records in Mysql is to use the ORDER BY RAND().
SELECT col1 FROM tbl ORDER BY RAND() LIMIT 1;
This can work fine for small tables. However, for big table, it will have a serious performance problem as in order to generate the list of random rows, because Mysql need to assign random number to each row and then sort them.

Even if you only want random 1 records from 200k+ rows, Mysql need to sort all the records and then extract it.

January 12 2013

Mysql replace() function

Tagged Under : ,

MySQL
Because I found that record save inside the database have typo problem.

How to solve it? Normally I will use PHP str_replace to solve the issue. But now requires use SQL to print out all the record and replace the typo.

January 12 2013

Mysql regexp and rlike function

Tagged Under : ,

MySQL
Mysql regexp or rlike function it same as PHP preg_match() function.

It save the time write code and filter the data.

January 12 2013

Mysql lpad() function

Tagged Under : ,

MySQL
Using Mysql function add asterisk (*) in front of the string.

Example Output:
********MyTestString
*******MyTestString2
**********TestString

January 10 2013

Mysql instr() Function

Tagged Under : ,

MySQL
Find the string position. I think most of the Software Engineer will use server side script to do it. I also is the one. For PHP, I will use strpos to get the position.

January 10 2013

Mysql find_in_set() Function

Tagged Under : ,

MySQL
Generally, we stores various values of choices in 1 column of database. For example, we store user’s preferred categories in user table’s. value stored in this field will be like this 1,2,12,22,4