To get random number in sql we use rand() function. But rand() funcition returns decimally random between 0 and 1. If we want to get between 1 and 100 we must multiply the number with top value. Then we must round the number. To round a number we can use 3 different methods. The first one floor method rounds the number to the integer floor value. The second one ceiling value, roundes to ceiling and the third one round method.
Example 1 : Show random number between 0 and 100;
1 |
Select floor(rand()*101)--If we want the 100 number to be selectable we must write 101 |
Example 2 : Show random number between 1 and 100;
1 |
Select ceiling(rand()*100)--0 is never selected because we use "ceiling" function |
Example 3 : Show random number between 50 and 100;
1 |
Select floor(rand()*50) + 50 |
Example 4 : Show random number between 20 and 80;
1 |
Select floor(rand()*60) + 20 -- 80 - 20 = 60 so we multiply with 60, then we add 20 |
best answer
best of the best