PostgreSQL相关查询SQL

PostgreSQL相关查询SQL

  • 一、查看表的索引名,索引定义,索引对应的字段序列
  • 二、根据字段列号获取字段名
  • 三、获取索引定义
  • 四、检索没有使用过的索引
  • 五、查看表上索引的大小
  • 六、获得当前模式下的建立索引的定义语句


一、查看表的索引名,索引定义,索引对应的字段序列

SELECT
	indrelid::regclass as table_name,
	pc1.relname as index_name,
	pi1.indisprimary as primary_key,
	pi1.indisunique as unique_key,
	pi1.indisvalid as valid,
	pi1.indkey as index_column_seq,
	pg_get_indexdef(pi1.indexrelid,0,TRUE) as create_index_sql
FROM
	pg_class pc1
	join pg_index pi1
	 on(pc1.oid = pi1.indexrelid )
	join pg_class pc2
	 on(pc2.oid = pi1.indrelid)
	 join pg_namespace pn
	 on(pc1.relnamespace=pn.oid)
where  1=1
	and pn.nspname=CURRENT_SCHEMA
    --and pc2.relname ~~* 't%'
order by table_name,index_column_seq ;

二、根据字段列号获取字段名

SELECT
	pa.attrelid :: regclass AS TABLE_NAME,
	pa.attname AS COLUMN_NAME,
	pa.attnum 
FROM
	pg_attribute pa
	JOIN pg_class pc ON ( pa.attrelid = pc.oid ) 
WHERE
	pc.relname = 'test' 
	AND pa.attnum IN ( 3, 2 )

--原语句
SELECT
	relname,
	indkey 
FROM
	pg_class,
	pg_index 
WHERE
	pg_class.oid = pg_index.indexrelid 
	AND pg_class.oid IN (
	SELECT
		indexrelid 
	FROM
		pg_index,
		pg_class 
	WHERE
		pg_class.relname = 'tmc_deals_t' 
		AND pg_class.oid = pg_index.indrelid
		--AND indisunique != 't' 
		--AND indisprimary != 't' 
	);

三、获取索引定义

SELECT * FROM pg_get_indexdef('idx_tpl_excel_import_errors_t'::regclass);

四、检索没有使用过的索引

SELECT
	relid :: regclass AS table_name,
	indexrelid :: regclass AS index_name
FROM
	pg_stat_user_indexes
	JOIN pg_index USING ( indexrelid ) 
WHERE
	idx_scan = 0 
	AND indisunique IS FALSE;

五、查看表上索引的大小

select pg_size_pretty(pg_total_relation_size('tmc_deals_t'))  --表总大小;
select pg_size_pretty(pg_relation_size('tmc_deals_t'));  --表的大小
select pg_size_pretty(pg_indexes_size('idx1_tmc_deals_t'));   --索引大小

六、获得当前模式下的建立索引的定义语句

SELECT
tablename,
indexname,
indexdef 
FROM
	pg_indexes 
WHERE
	schemaname = 'tmc' 
ORDER BY
	tablename,
	indexname;

你可能感兴趣的:(PostgreSQL,postgresql)