Search code examples
javamysqlsqlderby

SQL statement returns a resultset on an empty table


        String sql = "Select MAX(ORDERLINEID) From ORDERLINESTABLE";
        ResultSet rst;
        rst = stmt.executeQuery(sql);

        if(rst.next())
        {
            next = rst.getInt("ORDERLINEID");
            next++;
        }

I have a table called ORDERLINESTABLE in my database which is currently empty. I have run the above code with the aim is to get the highest integer stored in the ORDERLINEID column allowing me to increment it when adding items to the database.

I expected this query to return nothing as the table is empty but when debugging I noticed that the search is returning true for the rst.next() method.

Does anyone have any idea why this would be? I have looked at the resultset.next() documentation and as far as I can see it should return false.


Solution

  • When in doubt, look at your data. Here is a sample query from any db engine.

    select max(field) maxValue
    from table
    where 1=3
    

    It will yield

    maxValue
    Null
    

    In other words, your query is returning one record with a value of null.