Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a column exists in a table using an SQL statement

Is there a simple alternative in PostgreSQL to this statement produced in Oracle?

select table_name from user_tab_columns where table_name = myTable and column_name = myColumn; 

I am then testing whether the query returns anything so as to prove the column exists.

I am aware that using psql I can find these out individually but this is required to produce a result in a program I am writing to validate that a requested attribute field exists in my database table.

like image 204
CSharpened Avatar asked Apr 03 '12 10:04

CSharpened


People also ask

How do you check if a column exists or not?

For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.

How do you check if data exists in a table SQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How can check column in table in SQL Server?

To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'


1 Answers

Try this :

SELECT column_name  FROM information_schema.columns  WHERE table_name='your_table' and column_name='your_column'; 
like image 58
Ramandeep Singh Avatar answered Sep 19 '22 23:09

Ramandeep Singh