Course SQL Scripts
Course SQL Scripts
--create schema
create schema ext_file_demo
--create user
CREATE USER test_user_1 WITH PASSWORD 'test_USER_1' VALID UNTIL
'2022-01-01';
--create schema
create schema loading_data_demo
-- Add some new rows so we have sample insert data. The query creates a
duplicate of every fourth seller id
-- Insert all the rows from the staging table into the target table
insert into sales
select * from stagesales;
-- validating results
-- unload
unload ('select * from sales')
to 's3://test-redshift-demo/demo-4/unload/sales_'
iam_role 'arn:aws:iam::$account_id:role/test-redshift-role-s3';
Demo: Materialized View
-- create schema
create schema mat_view_demo
-- auto refresh
CREATE MATERIALIZED VIEW tickets_mv_2 AUTO REFRESH YES
AS (SELECT e.eventname eventname,
sum(s.pricepaid) total_sales
FROM event e, sales s
WHERE e.eventid = s.eventid
GROUP BY e.eventname)
Demo: Table Design - Distribution Style
-- create schema
create schema table_design_demo
-- all example
create table usersall diststyle all as
select * from users;
-- auto example
create table usersauto as
select * from users;
-- check sortkey
select "column", type, sortkey
from pg_table_def where tablename = 'usersauto';
-- check sortkey
select "column", type, sortkey
from pg_table_def where tablename = 'users_custom_sort';
-- explain functions
explain SELECT firstname, lastname, total_quantity
FROM (SELECT buyerid, sum(qtysold) total_quantity
FROM sales
GROUP BY buyerid
ORDER BY total_quantity desc limit 10) Q,
table_design_demo.users_custom_sort U
WHERE Q.buyerid = U.userid
ORDER BY Q.total_quantity desc;
Demo: Table Design - Compression
-- compression
select "column", type, encoding
from pg_table_def where tablename = 'usersauto' and
schemaname='table_design_demo';
-- Analyse Command
ANALYSE COMPRESSION usersauto;
-- analyse command
ANALYSE COMPRESSION users_custom_compression;
Demo: Redshift ML
-- create schema
create schema redshift_ml_demo
-- load data
COPY customer_activity
FROM 's3://test-redshift-demo/demo-15/input/customer_activity.csv'
REGION 'us-west-2' IAM_ROLE 'arn:aws:iam::$account:role/test-redshift-ml'
DELIMITER ','
IGNOREHEADER 1;
-- create ML model
CREATE MODEL customer_churn_auto_model FROM (SELECT state,
account_length,
area_code,
total_charge/account_length AS average_daily_spend,
cust_serv_calls/account_length AS average_daily_cases,
churn
FROM customer_activity
WHERE record_date < '2020-01-01'
)
TARGET churn FUNCTION ml_fn_customer_churn_auto
IAM_ROLE 'arn:aws:iam::480935361548:role/test-redshift-ml'SETTINGS (
S3_BUCKET 'test-redshift-demo'
);