Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Select lowest value that doesn't already exist

In TableA I have an int column.

Is it possible using only a select statement to select the minimum value in the column that DOES NOT EXIST and is greater then 0?

For example, if the col has the values 1,2,9 the select statement will return 3. If the col has 9,10,11 it will return 1.

I can achieve this using a temp table or using a loop, but I'm wondering if I can do it using just a select statement?

like image 277
Bob Avatar asked Oct 06 '10 11:10

Bob


People also ask

How do you select the least value 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.

How do you find min excluding 0 in SQL?

In MySQL you can use the NULLIF function. NULLIF will compare the price value with 0 and if it's true, it will return null.

How do I find the second lowest value in SQL?

select min(price) from table where itemid not in (select itemid from table where price= (select min(price) from table));

Can we use MIN function in WHERE clause?

You can get the lowest or minimum value using this function from any column, even you can filter the lowest or minimum value between specified expressions using the WHERE clause.


1 Answers

select
min(nt.id)
from numbertable nt
left outer join originaldata od
on nt.id=od.id
where od.id is null

have a number table that goes from 1 to your max value (or higher)

like image 81
DForck42 Avatar answered Oct 14 '22 03:10

DForck42