Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Select columns with NULL values only

Tags:

sql-server

How do I select all the columns in a table that only contain NULL values for all the rows? I'm using MS SQL Server 2005. I'm trying to find out which columns are not used in the table so I can delete them.

like image 363
Bryan Roth Avatar asked Sep 15 '08 14:09

Bryan Roth


People also ask

How can we find columns with NULL values in a table in mysql?

select column_name from user_tab_columns where table_name='Table_name' and num_nulls>=1; Just by simple query you will get those two columns.

How do you exclude columns with NULL values in SQL?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.

How do I compare two columns with NULL values in SQL?

Use <=> (null-safe equality operator) negated comparison which returns FALSE in case one of the operands is null but TRUE when both are null and both operands have equal non-null values.


1 Answers

Here is the sql 2005 or later version: Replace ADDR_Address with your tablename.

declare @col varchar(255), @cmd varchar(max)  DECLARE getinfo cursor for SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID WHERE t.Name = 'ADDR_Address'  OPEN getinfo  FETCH NEXT FROM getinfo into @col  WHILE @@FETCH_STATUS = 0 BEGIN     SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ADDR_Address WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end'     EXEC(@cmd)      FETCH NEXT FROM getinfo into @col END  CLOSE getinfo DEALLOCATE getinfo 
like image 200
Charles Graham Avatar answered Sep 22 '22 15:09

Charles Graham