Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum not used value in mysql table

Tags:

mysql

I have a MySQL table like this:

+--------+-------+
| Server | Port  |
+--------+-------+
| 1      | 27001 |
| 2      | 27002 |
| 4      | 27004 |
+--------+-------+

How you can see - here was 27003 port - but it was deleted some time ago (just for example).

Is there some way to know the minimum value that is not used (higher than 27000 for example) in mysql table? Or there is no way and I need to make an separate table with all ports and column with "used" or "not used" ?

Situation explanation: I am creating game hosting website, and I can use auto-increment for ports, but I will have a lot of deleted/unused ports after some time, and I want to use all of them before increasing port range.

like image 312
splattru Avatar asked Jun 24 '11 07:06

splattru


People also ask

How do I find the smallest value in MySQL?

MySQL MIN() Function. The MIN() function in MySQL is used to return the minimum value in a set of values from the table. It is an aggregate function that is useful when we need to find the smallest number, selecting the least expensive product, etc.

How do you find the minimum value in a table in SQL?

To find the minimum value of a column, use the MIN() aggregate function; it takes as its argument the name of the column for which you want to find the minimum value. If you have not specified any other columns in the SELECT clause, the minimum will be calculated for all records in the table.

Can I use min in where clause?

You can use the MIN() function is a variety of ways. One of the ways, is using it inside a WHERE clause.

What is the use of <> in MySQL?

The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0.


1 Answers

A quick search on Google for "first missing number from sequence mysql" gives this page of common MySQL queries.

It shows you how to find the first missing number from a sequence:

You have a table tbl(id int) with values (1,2,4,18,19,20,21), and you wish to find the first missing number in its sequence of id values:

SELECT t1.id+1 AS Missing 
FROM tbl AS t1 
LEFT JOIN tbl AS t2 ON t1.id+1 = t2.id 
WHERE t2.id IS NULL 
ORDER BY t1.id LIMIT 1; 

+---------+ 
| Missing | 
+---------+ 
|       3 | 
+---------+ 
like image 74
Caspar Avatar answered Oct 26 '22 07:10

Caspar