Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - conditionally select a column if exists

Tags:

sql

postgresql

I need to select a column only if it exists in table, else it can be set to null.

Sample table below, lets say the marks col is not necessary be there, so need to be checked if it exists

Table1:

name marks
joe  10
john 11
mary 13

Query:

select
    name,
    marks if it exists else null as marks1 -- pseudo code
from 
    table1

What should go in line to select marks ?

like image 787
user3206440 Avatar asked Dec 07 '16 05:12

user3206440


People also ask

How do I SELECT a column based on a condition in SQL?

Syntax. SELECT (optional: any desired columns), CASE WHEN (condition) THEN (desired output) WHEN (other condition) THEN (desired output) ELSE (desired output) END AS (descriptive header for the output column) FROM (appropriate table);

How do you check if a column exists in SQL?

Checking Existence of the Column: 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 I SELECT multiple columns based on condition in SQL?

When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.


2 Answers

SQL Doesn't permit that. Your result set has two options:

  1. Static inclusion
  2. All from table or subquery through column-expansion with * and tbl.*

Perhaps this will suit your needs, SELECT * FROM table1; You'll always get that column, if it exists.

like image 164
NO WAR WITH RUSSIA Avatar answered Oct 06 '22 01:10

NO WAR WITH RUSSIA


try this

IF COL_LENGTH('your_table_name','column_name_you_want_to_select') IS NULL BEGIN 
 --This means columns does not exist or permission is denied
 END
 else 
 --Do whatever you want
like image 42
Muhammad Usman Avatar answered Oct 05 '22 23:10

Muhammad Usman