tags:

views:

354

answers:

5

I want to determine if a column exists in a table for any jdbc driver.

In order to know the columns in a table, I have to make a query to the table and then get the ResultSetMetaData for the info, but this is pretty expensive in like 99% of times.

In mysql I have:

SELECT * FROM tablename LIMIT 0,0

In Intersystems caché I have:

SELECT TOP 0 * FROM tablename

But, for example, in JavaDB I cannot apply any limit at all.

Is there any generic query that would give me the same result and still be fair with the DB performance?

Thanks in advance.

+7  A: 

SELECT * FROM table_name WHERE 1 = 2;

Autocracy
+3  A: 
select * from tablename where 1 != 1
davetron5000
On some databases, 1 would refer to the *first column*. Even so, this will work: not even NULL is not equal to NULL.
Andomar
won't work on many databases. SHould be 1 <> 1
AlexKuznetsov
<> and != are fairly mutually exclusive across DBMS platforms, so I'd avoind inequality altogether.
Mike Woodhouse
+3  A: 

Unrelated, but if you just need the columns in MySQL, you can run SHOW FIELDS FROM tablename. This returns columns and the associated info.

Ben Hughes
+17  A: 
SELECT * FROM tableName WHERE 'You' = 'Smart'
Slim
I would have said WHERE "Paula Bean" = "Brillant", but this works, too.
Eric
this one made my day... thanks
Oso
i use 1<>!, but hey, this works amazingly well.
Raj More
isn't it better to do: 'You' = 'Smart' ?
Carlos Heuberger
Doing a select is unnecessary as you can query the database table metainfo without it.
Thorbjørn Ravn Andersen
+16  A: 

...or you could just use the DatabaseMetaData route.

There's a "getColumns" method that does what you need without creating a resultset.

Jeremy Smyth