3

I usually use SELECT 1 as my preferred validation-query from tomcat jdbc pools, because it returns only one row with the result 1 that is very faster, but today I've found one terrible mistake:

My database only has one table with its primary key and is not nullable. This table sometimes is dropped, and then appears again by application circumstances. And that's the problem, SELECT 1 validate connection to database because it's already up but the table is missing so I get a terrible exception.

So, the solutions passes by finding one validation-query against the only table that exists in the database. And also, I need the query to be as fast as possible, because the performance in the application is one of the main objetives.

You can answer than an obvius query may be SELECT 1 FROM THE_TABLE but this query returns 1 for each row that the table has, and that's not very quick.

So, what could be the faster validation-query to this table??

EDIT

If I need to return at least one result, How should be the validation-query?
I ask this because some pool implementations, like commons-dbcp doesn't accept a query without results as a validated query.

1 Answer 1

4

How about this, which should validate the table exists without actually loading any data by pulling 0 rows and no actual columns.

SELECT TOP 0 1 FROM THE_TABLE

Demo: http://www.sqlfiddle.com/#!3/c670b/3


There are also built-in ways to check for the existance of objects in SQL SERVER. Here are two examples that do effectively the same thing.

select count(1) from information_schema.tables where table_name = 'THE_TABLE'
select OBJECT_ID('THE_TABLE') is not null
4
  • 1
    If you look at the execution plan which is attached in the demo, it shows a constant scan, which effectively costs nothing.
    – mellamokb
    May 22, 2012 at 19:23
  • Do you know how to return one result in the validation-query? May 22, 2012 at 21:06
  • The two examples I provided in the addendum would return one result. First one would return 1 = exists, 0 = not exists. Second one would return TRUE = exists, FALSE = not exists (actually I think that would be 1/0 as well in SQL Server)
    – mellamokb
    May 22, 2012 at 21:10
  • I will test them tomorrow. Thanks again May 22, 2012 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.