有一种情况我需要清理雪花中的数据库。 我们有大约 40 个数据库,每个数据库有 100 多个表。有些每天都会加载,有些则不会,但每天都会使用。 然而,已经添加了很多用于测试和其他目的的表(由很多开发人员和用户)。
现在我们正在清理未使用的桌子。
我们有query_history表,它为我们提供了过去运行的查询的信息,但是它有数据库、仓库、用户等字段,但没有表。
我想知道是否有任何方法可以编写一个查询,为我们提供过去 10 天内未使用的表名(DDL 和 DML b0th)。
select obj.value:objectName::string objName
, max(query_start_time) as QUERY_DATE_TIME
from snowflake.account_usage.access_history
, table(flatten(direct_objects_accessed)) obj
group by 1
order by QUERY_DATE_TIME desc;
信息模式有一个表视图,并且您有最后更改的列,这对您有用吗?它不会为您提供最后访问的表,但会提供最后更改的表。除此之外,目前没有简单的方法可以从雪花中获取此信息。我也需要这个功能,我认为我们应该请求这个功能。
select table_schema,
table_name,
last_altered
from information_schema.tables
where table_type = 'BASE TABLE'
and last_altered < dateadd( 'DAY', -10, current_timestamp() )
order by table_schema,
table_name;
您可以从
information_schema.tables
获取表格列表,从snowflake.account_usage.access_history
获取访问历史记录。查找前者存在表但后者不存在的情况(在过去 20 天内)应该可以满足您的需求。
with table_list as (
select
table_catalog as table_database,
table_schema,
table_name
from information_schema.tables
),
access_history AS (
SELECT
query_start_time,
split(base.value:objectName, '.')[0]::string as table_database,
split(base.value:objectName, '.')[1]::string as table_schema,
split(base.value:objectName, '.')[2]::string as table_name
from snowflake.account_usage.access_history
, lateral flatten (base_objects_accessed) base
, lateral flatten (base.value, path => 'columns') cols
where query_start_time > current_date - interval '20 days'
),
tables_with_access as (
select distinct
table_database,
table_schema,
table_name
from access_history
)
select *
from table_list
left join tables_with_access twa
using (table_database,table_schema, table_name)
where twa.table_name is null
;