如何使用SQL在表中查找空列和空列

时间:2017-12-01 00:23:23

标签: sql oracle

我正在使用Oracle SQL开发人员,我们正在加载带有数据的表,我需要验证是否填充了所有表,以及是否有任何完全为null的列(该列的所有行都为null)。

对于表格,我点击每个表格并查看数据选项卡,查找表格是否已填充,然后使用过滤器查看每个列,以确定是否存在任何完全空列。我想知道是否有更快的方法来做到这一点。

谢谢, 苏雷什

5 个答案:

答案 0 :(得分:3)

当然可以。编写一个SQL脚本:

  • 枚举所有表格
  • 枚举表格中的列
  • 确定表格中的行数
  • 遍历每列并计算该列中有多少行为空。

如果列的行数为null,则等于表格中的行数,您就可以找到您要查找的内容。

答案 1 :(得分:3)

您很幸运 - 使用优化程序统计信息可以快速简便地获取此信息。

在大量数据加载后,无论如何都应该收集统计信息。统计NULL是统计收集已经完成的事情。使用自11g以来的默认设置,Oracle将准确计算100%的NULL数。 (但请记住,该数字仅反映一个时间点。如果您稍后添加数据,则必须重新收集统计数据以获得更新的结果。)

示例架构

create table test1(a number); --Has non-null values.
create table test2(b number); --Has NULL only.
create table test3(c number); --Has no rows.

insert into test1 values(1);
insert into test1 values(2);

insert into test2 values(null);

commit;

收集统计信息并运行查询

begin
    dbms_stats.gather_schema_stats(user);
end;
/

select table_name, column_name, num_distinct, num_nulls
from user_tab_columns
where table_name in ('TEST1', 'TEST2', 'TEST3');

使用NUM_DISTINCT和NUM_NULLS,您可以判断该列是否具有非NULL(num_distinct > 0),仅NULL(num_distinct = 0 and num_nulls > 0)或无行(num_distinct = 0 and num_nulls = 0)。

TABLE_NAME   COLUMN_NAME   NUM_DISTINCT   NUM_NULLS
----------   -----------   ------------   ---------
TEST1        A             2              0
TEST2        B             0              1
TEST3        C             0              0

答案 2 :(得分:1)

如果COUNT返回任何高于0的值,那么如何只在一个表中执行一个列 - 这意味着其中有数据。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

  <LinearLayout
      android:id="@+id/row_content"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintWidth_max="650dp"/>
</android.support.constraint.ConstraintLayout>

答案 3 :(得分:0)

此查询返回您想要的内容

 select table_name,column_name,nullable,num_distinct,num_nulls from all_tab_columns
        where owner='SCHEMA_NAME' 
        and num_distinct is null
        order by column_id;

答案 4 :(得分:0)

下面的脚本可用于获取表中的空列

    SELECT column_name 
      FROM all_tab_cols
     where table_name in (<table>)
       and avg_col_len = 0;