Showing posts with label Redshift. Show all posts
Showing posts with label Redshift. Show all posts

Thursday, December 18, 2025

SQL script to push the grants to a group in AWS Redshift DB for Read and write access

 1.select 'grant usage on schema ' ||nspname||' to <new_group_name>;' from pg_catalog.pg_namespace 

where nspname not in ('public','pg_catalog','catalog_history','information_schema','dbainfo') and nspname not like 'pg_%';  ---1



2.select 'grant select,insert,update,delete on all tables in schema ' ||nspname||' to <new_group_name>;' from pg_catalog.pg_namespace 

where nspname not in ('public','pg_catalog','catalog_history','information_schema','dbainfo') and nspname not like 'pg_%';     ---2



3.select 'ALTER DEFAULT PRIVILEGES IN SCHEMA ' ||nspname||' for user "<table_owner>" GRANT select,insert,update,delete ON tables to <new_group_name>;' from pg_catalog.pg_namespace 

where nspname not in ('public','pg_catalog','catalog_history','information_schema','dbainfo') and nspname not like 'pg_%';      ---3


SQL script to change the ownership of schema, table ,procedure in AWS Redshift Database

 

SQL script to change the ownership of schema, table ,procedure in AWS Redshift Database

1.change the ownership of schema


select 'alter schema ' ||nspname||' owner to "<new_schema_name>";' from pg_catalog.pg_namespace 

where nspname not in ('public','pg_catalog','catalog_history','information_schema','dbainfo') and nspname not like 'pg_%';


2.change the ownership of table


select 'alter table   klg_nga_kla.'||schemaname||'."'||tablename||'" owner to "<new_schema_name>";'

from pg_catalog.pg_tables where schemaname not in ('public','pg_catalog','catalog_history','information_schema','dbainfo') and schemaname not like 'pg_%';


3.change the ownership of procedure

SELECT 'alter  procedure '||n.nspname||'."'||p.proname||'" owner to "<new_schema_name>";'

    

FROM

    pg_catalog.pg_namespace n

JOIN pg_catalog.pg_proc p ON

    pronamespace = n.oid

join pg_catalog.pg_user b on

    b.usesysid = p.proowner

where

    nspname not in ('public','pg_catalog','catalog_history','information_schema','dbainfo') and nspname not like 'pg_%';


--add argument on the procedue while changing the ownership


AWS Redshift SQL scripts to find out session and Audit information

 What is the best way to assess tables that need to be vacuumed or analyzed?

This query returns tables where greater than 20% of rows are unsorted or statistics are 20% stale.


SELECT "database", "schema", "table", unsorted, stats_off

FROM svv_table_info

WHERE unsorted > 20

OR stats_off > 20


How can I troubleshoot loading errors?

Selecting from stl_load_errors provides information about errors during loading, and can be helpful for troubleshooting problematic loads.


SELECT *

FROM stl_load_errors

ORDER BY starttime DESC

LIMIT 100;




How to look specifically for failed logins?

SELECT *

FROM stl_connection_log

WHERE event='authentication failure'

ORDER BY recordtime;


Showing successfully authenticated users with the number of successful authentications:

SELECT username, event, COUNT(*)

FROM stl_connection_log

WHERE event = 'authenticated'

GROUP BY 1, 2

ORDER BY 3 DESC;


Showing successfully authenticated users by hourly buckets:

SELECT DATE_PART(YEAR, recordtime) || '-' ||

LPAD(DATE_PART(MONTH, recordtime),2,'0') || '-' ||

LPAD(DATE_PART(DAY, recordtime),2,'0') || ' ' ||

LPAD(DATE_PART(HOUR, recordtime),2,'0') AS hour_bucket, username, COUNT(*)

FROM stl_connection_log

WHERE event = 'authenticated'

GROUP BY 1, 2

ORDER BY 1, 2 DESC;



Showing a list of the connection drivers used by the redshift users:

SELECT username, application_name, COUNT(*) 

FROM stl_connection_log

WHERE application_name != ''

GROUP BY 1,2

ORDER BY 1,2;



Privilege violation logging & monitoring in AWS Redshift

Prior to setting such access controls, you will be able to see queries pulling data from these resources by querying STL_QUERY, as seen below: Retrieving queries access to specific objects in Redshift:

SELECT * FROM STL_QUERY

WHERE userid!=1

AND querytxt LIKE '%customers%'

ORDER BY query DESC

LIMIT 100;


SELECT username,dbname,recordtime

FROM stl_connection_log

WHERE event='authentication failure'

ORDER BY recordtime > '2022-07-08';



 Get the disk based queries information for last 2 days

SELECT q.query, 

       q.endtime - q.starttime             AS duration, 

       SUM(( bytes ) / 1024 / 1024 / 1024) AS GigaBytes, 

       aborted, 

       q.querytxt 

FROM   stl_query q 

       join svl_query_summary qs 

         ON qs.query = q.query 

WHERE  qs.is_diskbased = 't' 

       AND q.starttime BETWEEN SYSDATE - 2 AND SYSDATE 

GROUP  BY q.query, 

          q.querytxt, 

          duration, 

          aborted 

ORDER  BY gigabytes DESC ;




/* Query showing information about sessions with currently running queries */

SELECT s.process AS pid

       ,date_Trunc ('second',s.starttime) AS S_START

       ,datediff(minutes,s.starttime,getdate ()) AS conn_mins

       ,trim(s.user_name) AS USER

       ,trim(s.db_name) AS DB

       ,date_trunc ('second',i.starttime) AS Q_START

       ,i.query

       ,trim(i.query) AS sql

FROM stv_sessions s

  LEFT JOIN stv_recents i

         ON s.process = i.pid

        AND i.status = 'Running'

WHERE s.user_name <> 'rdsdb'

ORDER BY 1;


/* Query shows EXPLAIN plans which flagged "missing statistics" on the underlying tables */

SELECT substring(trim(plannode),1,100) AS plannode

       ,COUNT(*)

FROM stl_explain

WHERE plannode LIKE '%missing statistics%'

AND plannode NOT LIKE '%redshift_auto_health_check_%'

GROUP BY plannode

ORDER BY 2 DESC;


/* query showing queries which are waiting on a WLM Query Slot */

SELECT w.query

       ,substring(q.querytxt,1,100) AS querytxt

       ,w.queue_start_time

       ,w.service_class AS class

       ,w.slot_count AS slots

       ,w.total_queue_time / 1000000 AS queue_seconds

       ,w.total_exec_time / 1000000 exec_seconds

       ,(w.total_queue_time + w.total_Exec_time) / 1000000 AS total_seconds

FROM stl_wlm_query w

  LEFT JOIN stl_query q

         ON q.query = w.query

        AND q.userid = w.userid

WHERE w.queue_start_Time >= dateadd(day,-7,CURRENT_DATE)

AND   w.total_queue_Time > 0

-- and q.starttime >= dateadd(day, -7, current_Date)    

-- and ( querytxt like 'select%' or querytxt like 'SELECT%' ) 

ORDER BY w.total_queue_time DESC

         ,w.queue_start_time DESC limit 35;


/* query showing queries which are waiting on a WLM Query Slot */

SELECT w.query

       ,substring(q.querytxt,1,100) AS querytxt

       ,w.queue_start_time

       ,w.service_class AS class

       ,w.slot_count AS slots

       ,w.total_queue_time / 1000000 AS queue_seconds

       ,w.total_exec_time / 1000000 exec_seconds

       ,(w.total_queue_time + w.total_Exec_time) / 1000000 AS total_seconds

FROM stl_wlm_query w

  LEFT JOIN stl_query q

         ON q.query = w.query

        AND q.userid = w.userid

WHERE w.queue_start_Time >= dateadd(day,-7,CURRENT_DATE)

AND   w.total_queue_Time > 0

-- and q.starttime >= dateadd(day, -7, current_Date)    

-- and ( querytxt like 'select%' or querytxt like 'SELECT%' ) 

ORDER BY w.total_queue_time DESC

         ,w.queue_start_time DESC limit 35;


Tuesday, December 16, 2025

Shell script to check and record the database size in Redshift Database

Here is the custom script used to check the Redshift DB size and record it every month .This  will  be useful to get the know the DB growth.


1.create the table on DB  to store the DB size

CREATE TABLE admin.rs_db_size_dev (

    db_name    VARCHAR(256) ENCODE zstd,

    db_size_gb NUMERIC(    db_size_gb NUMERIC(37,2) ENCODE az64,

    date       DATE ENCODE az64

)

DISTSTYLE AUTO

2.schedule the job on cron

2 0 12 * *  /redshiftadmin/aws/scripts/dev_db_size_chk.sh DB1_DW1_India >> /redshiftadmin/aws/audit/log/db_size_dev_india.log 2>&1

3.load the script to  the server.

##################################################################################################

## purpose     :script used to collect Redshift dev DB size details                              #

## Author      : Bala P                                                                          #

## Developed   :10-july-2023 V1                                                                  #

##################################################################################################

#

##!/usr/bin/bash

#

export PGHOST=XXXXXXXXXXX.redshift.amazonaws.com

export PGPORT='5439'

export PGDATABASE=$1

export PGUSER=rsdbadmin


export PGPASSWORD='XXXXXXXXXXXX'

export wdir=/redshiftadmin/aws/audit/scripts/

export logdir=/redshiftadmin/aws/audit/log



query_result=$(psql -tA -c  "INSERT INTO admin.rs_db_size_dev (db_name, db_size_GB, date)

SELECT     dbase_name, total_GB AS db_size, CURRENT_DATE   FROM ( SELECT   dbase_name,  SUM(megabytes/1024) AS total_GB

FROM  admin.v_space_used_per_tbl   GROUP BY   dbase_name ) AS aggregated_data;")

#

#

if [[ -n "$query_result" ]]; then

##   if [[ -n "$query_result" && $(echo "$query_result" | grep -c 'exec_time_hours > 0.001') -gt 0 ]]; then

#       

recipient="BALAS@abc.com"


       subject="DB size  @ $PGDATABASE in Dev"

       body="DB size in dev cluster\n$query_result"


       echo -e "$body" | mailx -s "$subject" "$recipient"

      fi


4.output of the script


=# select * from admin.rs_db_size_dev;

 db_name    | db_size_gb |    date

---------------+------------+------------

DB1_DW1_India |    1654.00 | 2024-10-12

DB1_DW1_India |    1671.00 | 2024-11-12

DB1_DW1_India |    1515.00 | 2024-12-12

DB1_DW1_India |    1528.00 | 2025-01-12

DB1_DW1_India |    1573.00 | 2025-02-12

DB1_DW1_India |    1579.00 | 2025-03-12

DB1_DW1_India |    1666.00 | 2025-04-12

DB1_DW1_India |    1787.00 | 2025-05-12

DB1_DW1_India |    1788.00 | 2025-06-12

DB1_DW1_India |    1791.00 | 2025-07-12

DB1_DW1_India |    1788.00 | 2025-08-12

DB1_DW1_India |    1796.00 | 2025-09-12

DB1_DW1_India |    1801.00 | 2025-10-12

DB1_DW1_India |    1801.00 | 2025-11-12

DB1_DW1_India |    1801.00 | 2025-12-12

DB1_DW1_India |     249.00 | 2023-11-10

DB1_DW1_India |     249.00 | 2023-11-10

DB1_DW1_India |     249.00 | 2023-11-12

DB1_DW1_India |     246.00 | 2023-12-12

DB1_DW1_India |     166.00 | 2024-01-12

DB1_DW1_India |     318.00 | 2024-02-12

DB1_DW1_India |     236.00 | 2024-03-12

DB1_DW1_India |     334.00 | 2024-04-12

DB1_DW1_India |     772.00 | 2024-05-12

DB1_DW1_India |     965.00 | 2024-06-12

DB1_DW1_India |    1082.00 | 2024-07-12

DB1_DW1_India |    1528.00 | 2024-08-12

DB1_DW1_India |    1606.00 | 2024-09-12

(28 rows)




Tuesday, December 2, 2025

Shell script to find out super user list in AWS Redshift

 ################################################################################################

# purpose     :script used to collect PROD  Redshift super user list for audit

# Author      : Bala P

# Developed   :19-sep-2022 V1

################################################################################################


#!/usr/bin/bash


export PGHOST=XXXX.redshift.amazonaws.com

export PGPORT='5454'

export PGDATABASE=RS_DB1

export PGUSER=rsdbadmin


DBA=balamani@abc.com

export DBA


export PGPASSWORD='XXXXXXXXXX'

export wdir=/redshiftadmin/aws/audit/scripts/

export logdir=/redshiftadmin/aws/audit/log


psql  -f $wdir/super_user_list.sql -o $logdir/super_user_list.sql_output.log




mailx -s "Super user list from Redshift PROD cluster " $DBA  < $logdir/super_user_list.sql_output.log


************************************


 super_user_list.sql

\qecho

select usename,usesuper FROM pg_catalog.pg_user_info where usesuper='true';



check_tbl_ownr_compl.sql

select  schemaname,tablename ,tableowner from pg_catalog.pg_tables where schemaname not in ('public','pg_catalog','catalog_history','information_schema','dbainfo') and tableowner not in ('rsdbadmin') and schemaname not like 'pg_%';


 chk_tbl_owner_public.sql

select schemaname,tablename,tableowner  from pg_catalog.pg_tables  where schemaname='public';



************************************


shell script to find out long running session details in AWS Redshift database

 Here is the shell script to monitor the Long running session details in AWS redshift, we can schedule it .


##################################################################################################

### purpose     :script used to collect Redshift long running session details                     #

### Author      : Bala P                                                                          #

### Developed   :10-july-2023 V1                                                                  #

###################################################################################################

##

##!/usr/bin/bash

##


export PGDATABASE=$1

export PGUSER=rsdbadmin

export PGHOST=XXXXXXXXXX.redshift.amazonaws.com

export PGPORT='5439'


export PGPASSWORD='XXXXXXXXXXXXXXX'

export wdir=/redshiftadmin/aws/audit/scripts/

export logdir=/redshiftadmin/aws/audit/log



 query_result=$(psql -tA -c "select SPLIT_PART(SUBSTRING(user_name, 5), '@', 1) as user_name, DATE_TRUNC('second',starttime) as start_time,status,pid,duration/ (1000000.0 * 60 * 60) AS exec_time_hoursi,query  from stv_recents where user_name not in ('rdsdb') and duration/(1000000.0 * 60 * 60) > 3;")


#

 if [[ -n "$query_result" ]]; then


recipient="balamani@abc.com"

       subject="Queries with Execution Time > 3 hours @ $PGDATABASE in PROD"

       body="user_name|starttime |state|pid|exec_time_hours, queries  execution time greater than 3 hours PROD:\n\n$query_result"


     echo -e "$body" | mailx -s "$subject" "$recipient"

            fi




Tuesday, July 15, 2025

Script to find out user query running which priority in AWS Redshift Database

 

Script to find out user  query running  which priority in AWS Redshift Database:

 SELECT w.query, i.userid, w.service_class, w.state,w.query_priority

 FROM stv_wlm_query_state w

 JOIN stv_inflight i ON w.query = i.query

WHERE w.state = 'Running' and i.userid in ('219','384','105');



Redshift_TEST_DB=# SELECT w.query, i.userid, w.service_class, w.state,w.query_priority

Redshift_TEST_DB-#  FROM stv_wlm_query_state w

Redshift_TEST_DB-#  JOIN stv_inflight i ON w.query = i.query

Redshift_TEST_DB-# WHERE w.state = 'Running' and i.userid in ('219','384','105');

   query   | userid | service_class |      state       |    query_priority

-----------+--------+---------------+------------------+----------------------

 129306353 |    105 |           100 | Running          | High

 129302344 |    105 |           100 | Running          | High

(2 rows)

script to find out assumerole granted to user in AWS redshift Database.

 

script to find out assumerole granted to user in AWS redshift.

select username, iam_role, cmd FROM pg_get_iam_role_by_user('TESTUSER@abc.domain.com') res_iam_role(username text, iam_role text, cmd text);

Thursday, March 27, 2025

script to check if the schema part of the data share or not in aws Redshift database

 script to check if the schema  part of the data share or not in aws Redshift database:

 SELECT * FROM SVV_DATASHARE_OBJECTS where object_type='schema' and object_name='<schema_name>';



share_type|share_name       |object_type|object_name|producer_account|producer_namespace  

----------+-----------------+-----------+-----------+----------------+--------------------

outbound |abcprod_k1222_ds|schema     |schema_name|122234555555    |1234567890


script to check select access for entire schema in AWS Redshift database.

 

script to check  select access for entire schema in AWS Redshift database.

SELECT 

    tablename,

    usename

FROM

    pg_catalog.pg_tables AS tables,

    pg_catalog.pg_user AS users

WHERE 

    tables.schemaname = '<schema_name>'

    AND users.usename = 'username@abc.com'

    AND tables.schemaname not  like 'pg_%'

    AND NOT HAS_TABLE_PRIVILEGE(users.usename, tables.tablename, 'select');

script to check user has select,insert,update,delete access on specific schema in AWS Redshift Database

 script to check user has select,insert,update,delete  access on specific schema in AWS Redshift Database:


SELECT 

     tablename

     ,usename

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'select') AS sel

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'insert') AS ins

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'update') AS upd

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'delete') AS del

FROM

(SELECT * from FROM pg_catalog.pg_tables

WHERE schemaname = '<schema_name>' ) as tables

,(SELECT * FROM pg_catalog.pg_user where usename='username@abc.com') AS users;

script to check user has select,insert,update,delete access on specific table in schema in AWS Redshift Database

 script to check user has select,insert,update,delete  access on specific table in schema in AWS Redshift Database

SELECT 

     tablename

     ,usename

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'select') AS sel

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'insert') AS ins

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'update') AS upd

     ,HAS_TABLE_PRIVILEGE(users.usename, tablename, 'delete') AS del

FROM

(SELECT * from FROM pg_catalog.pg_tables

WHERE schemaname = '<schema_name>' and tablename in ('dm_sales_rptg_ecomm_new')) as tables

,(SELECT * FROM pg_catalog.pg_user where usename='username@abc.com') AS users;


Tuesday, October 8, 2024

script to find out table part of the datashare in AWS redshift

 script to find out table part of the datashare in AWS redshift:

SELECT share_type,

    btrim(share_name)::varchar(16) AS share_name,

    object_type,

    object_name

FROM svv_datashare_objects

WHERE share_name='<share_name>'

AND object_name LIKE  '%<table_name>%'

ORDER BY object_name;

Friday, June 7, 2024

script to find out user part of which group in AWS Redshift

 script to find out user part of which group in AWS Redshift:

you just need to feed the username and script will provide associated group name


SELECT 

         pg_group.groname

      ,pg_group.grosysid

                        ,pg_user.*

                    FROM pg_group, pg_user  

                    WHERE pg_user.usesysid = ANY(pg_group.grolist) 

                    AND pg_user.usename='<user_name>'

                    ORDER BY 1,2 ;

script to find what are the users associated with group in AWS Redshift

 

script to find  what are the users associated with group in AWS Redshift:


select usename 

from pg_user , pg_group

where pg_user.usesysid = ANY(pg_group.grolist) and 

      pg_group.groname='<group_name>';

Tuesday, July 18, 2023

script to find what are the users having CREATE privilege's on AWS Redshift database

 script to find what are the users having CREATE privilege's on AWS Redshift database:


SELECT u.usename AS username,

       nsp.nspname AS schema_name,

       has_schema_privilege(u.usename, nsp.nspname, 'CREATE') AS has_create_privilege

FROM pg_user u

CROSS JOIN pg_namespace nsp

WHERE nsp.nspname NOT LIKE 'pg_%' AND nsp.nspname not in ('information_schema','public') and u.usename not in('admin')

  AND has_schema_privilege(u.usename, nsp.nspname, 'CREATE') = true

ORDER BY u.usename, nsp.nspname;

Tuesday, January 3, 2023

How to migrate the data between AWS Redshift clusters ? or steps to configure the datashare in aws Redshift cluster?

 pre-request:

******************


get the cluster_name_space of source & Target cluster.



[source_cluster_name_space]==>source_DB


[target_cluster_name_space]==>Target_DB


source_cluster (Producer)

**********************


 create datashare Data_share_copy_source_2_target publicaccessible=false; --create Datashare


 alter datashare Data_share_copy_source_2_target add schema  schema_name; --- add schema to migrate the tables


 alter datashare Data_share_copy_source_2_target set includenew=true for schema schema_name;--add future object


 alter datashare Data_share_copy_source_2_target add all tables  in  schema schema_name;--current objects



 grant usage on datashare Data_share_copy_source_2_target to namespace '[target_cluster_name_space]';




Target_cluster (consumer)

********************


--create new datashare  to import the data to current/target cluster


create database import_DS_target from datashare Data_share_copy_source_2_target of  namespace '[source_cluster_name_space]';


--copy the data from imported Datashare  to  target DB tables


Move data  from source to Target:

***************************

create the empty table1 with same structure on target DB and insert the data.

insert into schema_name.table1 select * from  Data_share_copy_source_2_target.schema_name.table1

Monday, November 7, 2022

script to copy data from S3 bucket to Redshift?

 

script to copy data from S3 bucket to Redshift:

script to copy data from S3 bucket to Redshift using keys:

copy db_name.schema_name.tabl2 FROM 's3://s3_bucket/tabl2.csv' 

credentials 'aws_access_key_id=123456789; aws_secret_access_key=987654321;token=12345678898' CSV IGNOREHEADER 1 REGION 'us-east-1';


script to copy data from S3 bucket to Redshift using ARN:

copy  db_name.schema_name.table8 from  's3://s3_bucket/table8.csv

iam_role 'arn:aws:iam::123456789:role/S3_to_Redshift_copy_role'

 CSV IGNOREHEADER ;

How to make the session and user priority to increase in Redshift Database?

 user priority change:


The new priority to be assigned to all queries issued by user_name. 

This argument must be a string with the value CRITICAL, HIGHEST, HIGH, NORMAL, LOW, LOWEST, or RESET. 

Only superusers can change the priority to CRITICAL.


 Changing the priority to RESET removes the priority setting for user_name.


select change_user_priority('<username>','<Priority>');


select change_user_priority('user@abc.com','HIGHEST');



session priorty change:


CHANGE_SESSION_PRIORITY enables superusers to immediately change the priority of any session in the system. 

Only one session, user, or query can run with the priority CRITICAL.



returns the process identifier of the server process handling the current session.

select pg_backend_pid();

select change_session_priority(30311, 'Lowest');

               

 change_session_priority

---------------------------------------------------------

Succeeded to change session priority. Changed session (pid:30311) priority to lowest.

(1 row)

setup DDL Group in Redshift database

 setup DDL  Group in Redshift database


1.create group   <group_name>

2.load the DDL Privilege's to group

3.add the users to DDL  group


create schema <schema_name>;

create group  group_<schema>_DDL;

GRANT CREATE ON  database <DB name>  to group group_<schema>_DDL;

GRANT all ON  schema <schema_name>    to group group_<schema>_DDL;