Teradata - Useful SQLs

1. How to create a copy of table using an existing table including data in one line?

create multiset table <NewTableDB>.<NewTableName> as <ExistingTableDB>.<ExistingTableName> with data;


2. Some times we may need to review the table level stats like who, when table has been created, when was it last accessed etc for various reasons. In such scenarios you can use the following sql

-- Table space in GB along with last access time in a specific database
SELECT
  a.databasename,
  a.tablename,
  t.creatorname, t.CreateTimestamp, t.LastAccessTimestamp,
SUM (a.currentperm)/1024**3 (FORMAT 'zz9.99%') AS current_GB
FROM dbc.allspace a
join dbc.tablesv t
on a.databasename = t.databasename
and a.tablename = t.tablename
WHERE -- tablename =  '<tblname' AND 
a.databasename = '<dbname>'
GROUP BY 1,2,3,4,5
ORDER BY current_GB desc
;


3. When you need to find specific SQL queries executed by anyone  in the past, for backtracking purposes or even usage stats, you can use the following query in Teradata.
-- Usage based on the query string
SELECT
    username,MAX(ACCTSTRINGDATE) , COUNT(1)
FROM
    DW_MONITOR_VIEWSX.QryLog_Hist   Q
WHERE
  logdate >= current_date -180 -- lst 1 year
  and  querytext  like any ('%search key word%'                                      
)
and username not like all ('%dw_stats%','%DBA%')
GROUP BY username
ORDER BY Username, 2 desc
;


-- Database Free space check in GB
SELECT
DatabaseName
,SUM(CurrentPerm)/1024**3 AS USEDSPACE_IN_GB
,SUM(MaxPerm)/1024**3 AS MAXSPACE_IN_GB
,SUM(CurrentPerm) * 1.0/ NULLIFZERO (SUM(MaxPerm)) *100 (FORMAT 'zz9.99%') AS Percentage_Used
,MAXSPACE_IN_GB - USEDSPACE_IN_GB AS REMAININGSPACE_IN_GB
FROM DBC.DiskSpace
WHERE DatabaseName = 'dqrc'
GROUP BY DatabaseName;


4. SQL to check any user and its access rights

-- SQL to check particular user and corresponding access rights
SELECT
"DBC".RoleMembers.Grantee
,DBC.RoleMembers.RoleName AS RoleName
,DatabaseName
,"DBC".AllRoleRights.AccessRight
FROM
"DBC".RoleMembers
INNER JOIN "DBC".AllRoleRights
ON "DBC".RoleMembers.RoleName = "DBC".AllRoleRights.RoleName
WHERE
databasename = '<user_name>'
ORDER BY 1,3,4

Comments

Popular posts from this blog

Parsing a long text and fetching desired pattern strings using SPARK SQL

SQL to pivot rows to columns

Spark SQL - Performance Tuning tips