Course Presentation
Course Presentation
Controlled access
Data Manipulation
Large Amount of
Data
Business Insights
Who uses SQL
Database
Data Metadata
Tables
Attributes
Cells
Records
Start-Tech Academy
Why PostgreSQL
➢ Completely Open source
➢ Complete ACID Compliance
➢ Comprehensive documentation and active discussion forums
PostgreSQL ➢ PostgreSQL is best suited for Data Warehousing and data analysis
applications that require fast read/write speeds
➢ Supported by all major cloud service providers, including Amazon,
Google, & Microsoft
Start-Tech Academy
Create
Creating a basic table involves naming the table and defining its columns and each column's data type.
Start-Tech Academy
Create
Creating a basic table involves naming the table and defining its columns and each column's data type.
➢ NOT NULL Constraint: Ensures that a column cannot have NULL value.
➢ DEFAULT Constraint: Provides a default value for a column when none is
specified.
➢ UNIQUE Constraint: Ensures that all values in a column are different.
Constraints ➢ CHECK Constraint: Makes sure that all values in a column satisfy certain
criteria.
➢ Primary Key Constraint: Used to uniquely identify a row in the table.
➢ Foreign Key Constraint: Used to ensure referential integrity of the data.
Start-Tech Academy
Create
Creating a basic table involves naming the table and defining its columns and each column's data type.
Start-Tech Academy
Create
Creating a basic table involves naming the table and defining its columns and each column's data type.
Start-Tech Academy
Create
Creating a basic table involves naming the table and defining its columns and each column's data type.
➢ Numeric - This type of data stores numerical values. Following Data types fall
in this category: Integer, Float, Real, Numeric, or Decimal.
➢ Character String - This type of data stores character values. The two common
Data Types types are CHAR(n) and VARCHAR(n).
➢ Date/Datetime - This type of data allows us to store date or datetime in a
database table.
Start-Tech Academy
Data Types
Numeric - This type of data stores numerical values.
Storage
Name Description Range
Size
Stores whole numbers,
smallint 2 bytes -32768 to +32767
small range.
Stores whole numbers.Use
-2147483648 to
integer this when you want to store 4 bytes
Numeric typical integers.
+2147483647
Start-Tech Academy
Data Types
Character String - This type of data stores character values. The two common types are CHAR(n) and VARCHAR(n).
Name Description
character varying(n), varchar(n) variable-length with limit
Character character(n), char(n) fixed-length, blank padded
text variable unlimited length
Start-Tech Academy
Data Types
Date/Datetime - This type of data allows us to store binary objects in a database table.
Start-Tech Academy
CREATE TYPE
Users can define data types as per requirements also
Start-Tech Academy
INSERT
The INSERT INTO statement is used to add new records into a database table
Start-Tech Academy
INSERT
The INSERT INTO statement is used to add new records into a database table
Start-Tech Academy
COPY
The basic syntax to import data from CSV file into a table using COPY statement is as below
Start-Tech Academy
SELECT
The SELECT statement is used to fetch the data from a database table which returns this data in the form of a result
table. These result tables are called result-sets.
Start-Tech Academy
SELECT
The SELECT statement is used to fetch the data from a database table
Start-Tech Academy
SELECT DISTINCT
The DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and
fetching only unique records.
Start-Tech Academy
SELECT DISTINCT
The DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and
fetching only unique records.
Start-Tech Academy
WHERE
The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with
multiple tables. If the given condition is satisfied, then only it returns a specific value from the table.
SELECT "column_name"
FROM "table_name"
Syntax WHERE "condition";
Start-Tech Academy
WHERE
The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with
multiple tables. If the given condition is satisfied, then only it returns a specific value from the table.
➢ Equals to condition
SELECT first_name FROM customer_table WHERE age = 25;
Start-Tech Academy
AND & OR
The SQL AND & OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two
operators are called as the conjunctive operators.
SELECT "column_name"
FROM "table_name"
Syntax WHERE "simple condition"
{ [AND|OR] "simple condition"}+;
Start-Tech Academy
AND & OR
The SQL AND & OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two
operators are called as the conjunctive operators.
Start-Tech Academy
NOT
NOT condition is used to negate a condition in a SELECT, INSERT, UPDATE, or DELETE statement.
SELECT "column_name"
Syntax FROM "table_name"
WHERE NOT "simple condition"
Start-Tech Academy
NOT
NOT condition is used to negate a condition in a SELECT, INSERT, UPDATE, or DELETE statement.
Start-Tech Academy
UPDATE
The SQL UPDATE Query is used to modify the existing records in a table.
UPDATE "table_name"
Syntax SET column_1 = [value1], column_2 = [value2], ...
WHERE "condition";
Start-Tech Academy
UPDATE
The SQL UPDATE Query is used to modify the existing records in a table.
Start-Tech Academy
DELETE
The DELETE Query is used to delete the existing records from a table.
Start-Tech Academy
DELETE
The DELETE Query is used to delete the existing records from a table.
➢ Single row
DELETE FROM CUSTOMERS
WHERE ID = 6;
➢ Multiple rows
Example DELETE FROM CUSTOMERS
WHERE age>25;
➢ All rows
DELETE FROM CUSTOMERS;
Start-Tech Academy
ALTER
The ALTER TABLE statement is used to change the definition or structure of an existing table
Start-Tech Academy
COLUMN – ADD & DROP
The basic syntax of an ALTER TABLE command to add/drop a Column in an existing table is as follows.
Start-Tech Academy
COLUMN – MODIFY & RENAME
The basic syntax of an ALTER TABLE command to Modify/Rename a Column in an existing table is as follows.
Syntax
ALTER TABLE "table_name"
RENAME COLUMN "column 1" TO "column 2";
Start-Tech Academy
CONSTRAINT – ADD & DROP
The basic syntax of an ALTER TABLE command to add/drop a Constraint on a existing table is as follows.
Syntax (“column_name”>=100);
Start-Tech Academy
Issues while restoration
Possible solution:
Locate the file on your PC and update this address in pgAdmin
Issues while restoration
1. Create a new DB for restoring the data and avoid using old Database for
restoring.
4. Refresh DB once and check if tables are created even if it shows failure
Examples
Filtering
Examples
Filtering
Examples
Sorting
Customer Name Age Customer Name Age Customer Name Age
Brosina Hoffman 20 Alejandro Grove 18 Zuschuss Donatelli 66
Andrew Allen 50 Andrew Allen 50 Sandra Flanagan 41
Irene Maddox 66 Brosina Hoffman 20 Pete Kriz 46
Harold Pawlan 20 Emily Burns 34 Ken Black 67
Pete Kriz 46 Harold Pawlan 20 Irene Maddox 66
Alejandro Grove 18 Irene Maddox 66 Harold Pawlan 20
Zuschuss Donatelli 66 Ken Black 67 Emily Burns 34
Ken Black 67 Pete Kriz 46 Brosina Hoffman 20
Sandra Flanagan 41 Sandra Flanagan 41 Andrew Allen 50
Examples
Aggregation
Order Line Order ID Customer ID Product ID Sales Quantity
1 CA-2016-152156 CG-12520 FUR-BO-10001798 261.96 2
2 CA-2016-152156 CG-12520 FUR-CH-10000454 731.94 3
3 CA-2016-138688 DV-13045 OFF-LA-10000240 14.62 2
4 US-2015-108966 SO-20335 FUR-TA-10000577 957.5775 5
5 US-2015-108966 SO-20335 OFF-ST-10000760 22.368 2
6 CA-2014-115812 BH-11710 FUR-FU-10001487 48.86 7
7 CA-2014-115812 BH-11710 OFF-AR-10002833 7.28 4
8 CA-2014-115812 BH-11710 TEC-PH-10002275 907.152 6
9 CA-2014-115812 BH-11710 OFF-BI-10003910 18.504 3
10 CA-2014-115812 BH-11710 OFF-AP-10002892 114.9 5
Raw Data
Customer ID Customer Name Segment Age Country City State Postal Code Region
CG-12520 Claire Gute Consumer 67 United States Henderson Kentucky 42420 South
DV-13045 Darrin Van Huff Corporate 31 United States Los Angeles California 90036 West
SO-20335 Sean O'Donnell Consumer 65 United States Fort Lauderdale Florida 33311 South
BH-11710 Brosina Hoffman Consumer 20 United States Los Angeles California 90032 West
AA-10480 Andrew Allen Consumer 50 United States Concord North Carolina 28027 South
IM-15070 Irene Maddox Consumer 66 United States Seattle Washington 98103 West
HP-14815 Harold Pawlan Home Office 20 United States Fort Worth Texas 76106 Central
PK-19075 Pete Kriz Consumer 46 United States Madison Wisconsin 53711 Central
AG-10270 Alejandro Grove Consumer 18 United States West Jordan Utah 84084 West
ZD-21925 Zuschuss Donatelli Consumer 66 United States San Francisco California 94109 West
Aggregation
SELECT "column_name"
Syntax FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...);
Start-Tech Academy
IN
IN condition is used to help reduce the need to use multiple OR conditions in a SELECT, INSERT, UPDATE, or DELETE
statement.
SELECT *
FROM customer
WHERE city IN (‘Philadelphia’, ‘Seattle’)
Example
SELECT *
FROM customer
WHERE city = ‘Philadelphia’ OR city = ’Seattle’;
Start-Tech Academy
BETWEEN
The BETWEEN condition is used to retrieve values within a range in a SELECT, INSERT, UPDATE, or DELETE statement.
SELECT "column_name"
Syntax FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2';
Start-Tech Academy
BETWEEN
The BETWEEN condition is used to retrieve values within a range in a SELECT, INSERT, UPDATE, or DELETE statement.
Which is same as
SELECT * FROM customer
WHERE age>= 20 AND age<= 30;
Example
SELECT * FROM customer
WHERE age NOT BETWEEN 20 and 30;
Start-Tech Academy
LIKE
The PostgreSQL LIKE condition allows you to perform pattern matching using Wildcards.
SELECT "column_name"
Syntax FROM "table_name"
WHERE "column_name" LIKE {PATTERN};
Start-Tech Academy
WILDCARDS
The PostgreSQL LIKE condition allows you to perform pattern matching using Wildcards.
Wildcard Explanation
% Allows you to match any string of any length (including zero length)
_ Allows you to match on a single character
AB_C means string starts with AB, then there is one character, then there is C
Start-Tech Academy
LIKE
The PostgreSQL LIKE condition allows you to perform pattern matching using Wildcards.
Start-Tech Academy
ORDER BY
The ORDER BY clause is used to sort the records in result set. It can only be used in SELECT statements.
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC];
Syntax It is possible to order by more than one column.
Start-Tech Academy
ORDER BY
The ORDER BY clause is used to sort the records in result set. It can only be used in SELECT statements.
Same as
SELECT * FROM customer
WHERE state = 'California’ ORDER BY Customer_name ASC;
Start-Tech Academy
LIMIT
LIMIT statement is used to limit the number of records returned based on a limit value.
SELECT “column_names”
FROM “table_name”
Syntax [WHERE conditions]
[ORDER BY expression [ ASC | DESC ]]
LIMIT row_count;
Start-Tech Academy
LIMIT
LIMIT statement is used to limit the number of records returned based on a limit value.
Start-Tech Academy
AS
The keyword AS is used to assign an alias to the column or a table. It is inserted between the column name and the
column alias or between the table name and the table alias.
Start-Tech Academy
AS
The keyword AS is used to assign an alias to the column or a table. It is inserted between the column name and the
column alias or between the table name and the table alias.
Start-Tech Academy
COUNT
Count function returns the count of an expression
Start-Tech Academy
COUNT
Count function returns the count of an expression
Start-Tech Academy
SUM
Sum function returns the summed value of an expression
SELECT sum(aggregate_expression)
FROM tables
Syntax [WHERE conditions];
Start-Tech Academy
SUM
Sum function returns the summed value of an expression
Start-Tech Academy
AVERAGE
AVG function returns the average value of an expression.
SELECT avg(aggregate_expression)
FROM tables
Syntax [WHERE conditions];
Start-Tech Academy
AVERAGE
AVG function returns the average value of an expression.
Start-Tech Academy
MIN/MAX
MIN/MAX function returns the minimum/maximum value of an expression.
SELECT min(aggregate_expression)
FROM tables
[WHERE conditions];
Syntax
SELECT max(aggregate_expression)
FROM tables
[WHERE conditions];
Start-Tech Academy
MIN/MAX
MIN/MAX function returns the minimum/maximum value of an expression.
Start-Tech Academy
GROUP BY
GROUP BY clause is used in a SELECT statement to group the results by one or more columns.
Start-Tech Academy
GROUP BY
GROUP BY clause is used in a SELECT statement to group the results by one or more columns.
SELECT customer_id,
Example MIN(sales) AS min_sales,
MAX(sales) AS max_sales,
AVG(sales) AS Average_sales,
SUM(sales) AS Total_sales
FROM sales
GROUP BY customer_id
ORDER BY total_sales DESC
LIMIT 5;
Start-Tech Academy
HAVING
HAVING clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those
whose the condition is TRUE
Start-Tech Academy
HAVING
HAVING clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those
whose the condition is TRUE
Start-Tech Academy
CASE
The CASE expression is a conditional expression, similar to if/else statements
Start-Tech Academy
CASE
The CASE expression is a conditional expression, similar to if/else statements
SELECT *,
CASE WHEN age<30 THEN ‘Young'
WHEN age>60 THEN ‘Senior Citizen'
Example ELSE ‘Middle aged'
END AS Age_category
FROM customer;
Start-Tech Academy
Module – Joining Data
Furniture 8028
Office Supplies 22906
We should give
Technology 6939
Agenda offer on
Technology
products
Subqueries
Query A
Agenda
Query B
Joins
Why
Marketing Head
Joins
Order Line Order ID Order Date Ship Date Ship Mode Customer ID Product ID Sales Quantity Discount Profit
Why 1
2
CA-2016-152156
CA-2016-152156
08-11-2016
08-11-2016
11-11-2016
11-11-2016
Second Class
Second Class
CG-12520
CG-12520
FUR-BO-10001798
FUR-CH-10000454
261.96
731.94
2
3
0
0
41.9136
219.582
3 CA-2016-138688 12-06-2016 16-06-2016 Second Class DV-13045 OFF-LA-10000240 14.62 2 0 6.8714
4 US-2015-108966 11-10-2015 18-10-2015 Standard Class SO-20335 FUR-TA-10000577 957.5775 5 0.45 -383.031
5 US-2015-108966 11-10-2015 18-10-2015 Standard Class SO-20335 OFF-ST-10000760 22.368 2 0.2 2.5164
Customer ID Customer Name Segment Age Country City State Postal Code Region
CG-12520 Claire Gute Consumer 67 United States Henderson Kentucky 42420 South
DV-13045 Darrin Van Huff Corporate 31 United States Los Angeles California 90036 West
SO-20335 Sean O'Donnell Consumer 65 United States Fort Lauderdale Florida 33311 South
BH-11710 Brosina Hoffman Consumer 20 United States Los Angeles California 90032 West
Joins
To join tables we must know:
Order Line Order ID Order Date Ship Date Ship Mode Customer ID Product ID Sales Quantity Discount Profit
What’s needed 1
2
CA-2016-152156
CA-2016-152156
08-11-2016
08-11-2016
11-11-2016
11-11-2016
Second Class
Second Class
CG-12520
CG-12520
FUR-BO-10001798
FUR-CH-10000454
261.96
731.94
2
3
0
0
41.9136
219.582
3 CA-2016-138688 12-06-2016 16-06-2016 Second Class DV-13045 OFF-LA-10000240 14.62 2 0 6.8714
4 US-2015-108966 11-10-2015 18-10-2015 Standard Class SO-20335 FUR-TA-10000577 957.5775 5 0.45 -383.031
5 US-2015-108966 11-10-2015 18-10-2015 Standard Class SO-20335 OFF-ST-10000760 22.368 2 0.2 2.5164
Customer ID Customer Name Segment Age Country City State Postal Code Region
CG-12520 Claire Gute Consumer 67 United States Henderson Kentucky 42420 South
DV-13045 Darrin Van Huff Corporate 31 United States Los Angeles California 90036 West
SO-20335 Sean O'Donnell Consumer 65 United States Fort Lauderdale Florida 33311 South
BH-11710 Brosina Hoffman Consumer 20 United States Los Angeles California 90032 West
Joins
Order Line Order ID Order Date Customer ID Product ID Sales
Order Line Order ID Order Date Customer ID Product ID Sales Customer Name State Region
1 CA-2016-152156 08-11-2016 CG-12520 FUR-BO-10001798 261.96 Claire Gute Kentucky South
3 CA-2016-138688 12-06-2016 DV-13045 OFF-LA-10000240 14.62 Darrin Van Huff California West
5 US-2015-108966 11-10-2015 SO-20335 OFF-ST-10000760 22.368 Sean O'Donnell Florida South
Joins
Observations
Order Line Order ID Order Date Customer ID Product ID Sales Customer Name State Region
1 CA-2016-152156 08-11-2016 CG-12520 FUR-BO-10001798 261.96 Claire Gute Kentucky South
88 CA-2017-155558 26-10-2017 PG-18895 OFF-LA-10000134 6.16 Null Null Null
3 CA-2016-138688 12-06-2016 DV-13045 OFF-LA-10000240 14.62 Darrin Van Huff California West
5 US-2015-108966 11-10-2015 SO-20335 OFF-ST-10000760 22.368 Sean O'Donnell Florida South
Joins
Observations
Order Line Order ID Order Date Customer ID Product ID Sales Customer Name State Region
1 CA-2016-152156 08-11-2016 CG-12520 FUR-BO-10001798 261.96 Claire Gute Kentucky South
3 CA-2016-138688 12-06-2016 DV-13045 OFF-LA-10000240 14.62 Darrin Van Huff California West
5 US-2015-108966 11-10-2015 SO-20335 OFF-ST-10000760 22.368 Sean O'Donnell Florida South
Null Null Null BH-11710 Null Null Brosina Hoffman California West
Joins
Observations
Order Line Order ID Order Date Customer ID Product ID Sales Customer Name State Region
1 CA-2016-152156 08-11-2016 CG-12520 FUR-BO-10001798 261.96 Claire Gute Kentucky South
88 CA-2017-155558 26-10-2017 PG-18895 OFF-LA-10000134 6.16 Null Null Null
3 CA-2016-138688 12-06-2016 DV-13045 OFF-LA-10000240 14.62 Darrin Van Huff California West
5 US-2015-108966 11-10-2015 SO-20335 OFF-ST-10000760 22.368 Sean O'Donnell Florida South
Null Null Null BH-11710 Null Null Brosina Hoffman California West
Joins
Customer ID Customer Name Segment Age Country City State Postal Code Region
Customer ID Customer Name Segment Age Country City State Postal Code Region
EB-13870 Emily Burns Consumer 34 United States Orem Utah 84057 West
EH-13945 Eric Hoffmann Consumer 21 United States Los Angeles California 90049 West
TB-21520 Tracy Blumstein Consumer 48 United States Philadelphia Pennsylvania 19140 East
MA-17560 Matt Abelman Home Office 19 United States Houston Texas 77095 Central
ON-18715 Odella Nelson Corporate 27 United States Eagan Minnesota 55122 Central
PO-18865 Patrick O'Donnell Consumer 64 United States Westland Michigan 48185 Central
LH-16900 Lena Hernandez Consumer 66 United States Dover Delaware 19901 East
JOINS
JOINS are used to retrieve data from multiple tables. It is performed whenever two or more tables are joined in a SQL
statement.
Start-Tech Academy
JOINS
/*Creating sales table of year 2015*/
Create table sales_2015 as select * from sales where ship_date between '2015-
01-01' and '2015-12-31';
select count(*) from sales_2015; --2131
creating dataset
/* Customers with age between 20 and 60 */
create table customer_20_60 as select * from customer where age between 20
and 60;
select count (*) from customer_20_60;--597
Start-Tech Academy
INNER JOIN
INNER JOIN compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-
predicate. When satisfied, column values for each matched pair of rows of A and B are combined into a result row.
SELECT columns
FROM table1
Syntax INNER JOIN table2
ON table1.column = table2.column;
Start-Tech Academy
INNER JOIN
INNER JOIN compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-
predicate. When satisfied, column values for each matched pair of rows of A and B are combined into a result row.
SELECT
a.order_line ,
a.product_id,
a.customer_id,
a.sales,
Example b.customer_name,
b.age
FROM sales_2015 AS a
INNER JOIN customer_20_60 AS b
ON a.customer_id = b.customer_id
ORDER BY customer_id;
Start-Tech Academy
JOINS
JOINS are used to retrieve data from multiple tables. It is performed whenever two or more tables are joined in a SQL
statement.
Start-Tech Academy
LEFT JOIN
The LEFT JOIN returns all rows from the left table, even if there are no matches in the right table.
Start-Tech Academy
LEFT JOIN
The LEFT JOIN returns all rows from the left table, even if there are no matches in the right table.
SELECT
a.order_line ,
a.product_id,
a.customer_id,
a.sales,
Example b.customer_name,
b.age
FROM sales_2015 AS a
LEFT JOIN customer_20_60 AS b
ON a.customer_id = b.customer_id
ORDER BY customer_id;
Start-Tech Academy
RIGHT JOIN
The RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table.
Start-Tech Academy
RIGHT JOIN
The RIGHT JOIN returns all rows from the right table, even if there are no matches in the left table.
SELECT
a.order_line ,
a.product_id,
a.customer_id,
a.sales,
Example b.customer_name,
b.age
FROM sales_2015 AS a
RIGHT JOIN customer_20_60 AS b
ON a.customer_id = b.customer_id
ORDER BY customer_id;
Start-Tech Academy
FULL OUTER JOIN
The FULL JOIN combines the results of both left and right outer joins
Start-Tech Academy
FULL OUTER JOIN
The FULL JOIN combines the results of both left and right outer joins
SELECT
a.order_line ,
a.product_id,
a.customer_id,
a.sales,
b.customer_name,
Example b.age,
b.customer_id
FROM sales_2015 AS a
FULL JOIN customer_20_60 AS b
ON a.customer_id = b.customer_id
ORDER BY a.customer_id , b.customer_id;
Start-Tech Academy
CROSS JOIN
The Cross Join creates a cartesian product between two sets of data.
Start-Tech Academy
CROSS JOIN
The Cross Join creates a cartesian product between two sets of data.
Start-Tech Academy
Combining queries
Combining similar data using operators like Union, Intersect and Except
Customer ID Customer Name Segment Age Country City State Postal Code Region
EB-13870 Emily Burns Consumer 34 United States Orem Utah 84057 West
EH-13945 Eric Hoffmann Consumer 21 United States Los Angeles California 90049 West
TB-21520 Tracy Blumstein Consumer 48 United States Philadelphia Pennsylvania 19140 East
MA-17560 Matt Abelman Home Office 19 United States Houston Texas 77095 Central
Customer ID Customer Name Segment Age Country City State Postal Code Region
Customer ID Customer Name Segment Age Country City State Postal Code Region
EB-13870 Emily Burns Consumer 34 United States Orem Utah 84057 West
EH-13945 Eric Hoffmann Consumer 21 United States Los Angeles California 90049 West
TB-21520 Tracy Blumstein Consumer 48 United States Philadelphia Pennsylvania 19140 East
MA-17560 Matt Abelman Home Office 19 United States Houston Texas 77095 Central
ON-18715 Odella Nelson Corporate 27 United States Eagan Minnesota 55122 Central
PO-18865 Patrick O'Donnell Consumer 64 United States Westland Michigan 48185 Central
LH-16900 Lena Hernandez Consumer 66 United States Dover Delaware 19901 East
Combining Queries
Combining queries are used to combine the results of two SELECT queries
Note: Structure of the output from the two queries should be same
Combining Queries
Combining queries are used to combine the results of two SELECT queries
Syntax INTERSECT
Example INTERSECT
Start-Tech Academy
EXCEPT
EXCEPT operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT
statement.
SELECT customer_id
FROM sales_2015
EXCEPT
Example SELECT customer_id
FROM customer_20_60
ORDER BY customer_id;
Start-Tech Academy
UNION
UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between
the various SELECT statements.
Each SELECT statement within the UNION operator must have the same number
of fields in the result sets with similar data types
Start-Tech Academy
UNION
UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between
the various SELECT statements.
SELECT customer_id
FROM sales_2015
UNION
Example SELECT customer_id
FROM customer_20_60
ORDER BY customer_id;
Start-Tech Academy
SUBQUERY
Subquery is a query within a query. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT
clause.
SELECT "column_name1"
Syntax FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");
Start-Tech Academy
SUBQUERY
Subquery is a query within a query. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT
clause.
Subquery in WHERE
Start-Tech Academy
SUBQUERY
Subquery is a query within a query. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT
clause.
Subquery in FROM
SELECT
a.product_id ,
a.product_name ,
a.category,
Example b.quantity
FROM product AS a
LEFT JOIN (SELECT product_id,
SUM(quantity) AS quantity
FROM sales GROUP BY product_id) AS b
ON a.product_id = b.product_id
ORDER BY b.quantity desc;
Start-Tech Academy
SUBQUERY
Subquery is a query within a query. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT
clause.
SELECT customer_id,
order_line,
(SELECT customer_name
Example FROM customer
WHERE sales.customer_id = customer.customer_id)
FROM sales
ORDER BY customer_id;
Start-Tech Academy
SUBQUERY
Subquery is a query within a query. These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT
clause.
There are a few rules that subqueries must follow −
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected
columns.
• An ORDER BY command cannot be used in a subquery, although the main
query can use an ORDER BY. The GROUP BY command can be used to
RULES perform the same function as the ORDER BY in a subquery.
• Subqueries that return more than one row can only be used with multiple
value operators such as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a
BLOB, ARRAY, CLOB, or NCLOB.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery. However, the
BETWEEN operator can be used within the subquery.
Start-Tech Academy
VIEW
VIEW is not a physical table, it is a virtual table created by a query joining one or more tables.
Start-Tech Academy
CREATE VIEW
VIEW is not a physical table, it is a virtual table created by a query joining one or more tables.
Start-Tech Academy
DROP or UPDATE VIEW
VIEW is not a physical table, it is a virtual table created by a query joining one or more tables.
Start-Tech Academy
VIEW
A view is a virtual table. A view consists of rows and columns just like a table. The
difference between a view and a table is that views are definitions built on top of
other tables (or views), and do not hold data themselves. If data is changing in the
underlying table, the same change is reflected in the view. A view can be built on top
of a single table or multiple tables. It can also be built on top of another view. In the
SQL Create View page, we will see how a view can be built.
Views offer the following advantages:
1. Ease of use: A view hides the complexity of the database tables from end users.
Essentially we can think of views as a layer of abstraction on top of the database
NOTES tables.
2. Space savings: Views takes very little space to store, since they do not store actual
data.
3. Additional data security: Views can include only certain columns in the table so
that only the non-sensitive columns are included and exposed to the end user. In
addition, some databases allow views to have different security settings, thus hiding
sensitive data from prying eyes.
Start-Tech Academy
VIEW
VIEW can be updated under certain conditions which are given below −
Start-Tech Academy
INDEX
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each
value that appears in the indexed columns.
Start-Tech Academy
CREATE INDEX
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each
value that appears in the indexed columns.
Start-Tech Academy
DROP or RENAME INDEX
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each
value that appears in the indexed columns.
Start-Tech Academy
DROP INDEX
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each
value that appears in the indexed columns.
Start-Tech Academy
INDEX
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each
value that appears in the indexed columns.
PRACTICES 4. Make sure the column you are building an index for is declared NOT NULL
Start-Tech Academy
INDEX
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each
value that appears in the indexed columns.
GOOD • Tables that have frequent, large batch updates or insert operations.
PRACTICES • Indexes should not be used on columns that contain a high number of NULL
values.
Start-Tech Academy
SQL functions
Functions are used to process data and improve its quality
Examples:
Classification
Pattern Matching Data type conversion User access control
LENGTH
LENGTH function returns the length of the specified string, expressed as the number of characters.
Start-Tech Academy
LENGTH
LENGTH function returns the length of the specified string, expressed as the number of characters.
Start-Tech Academy
UPPER & LOWER
UPPER/ LOWER function converts all characters in the specified string to uppercase/ lowercase.
upper( string )
Syntax
lower( string )
Start-Tech Academy
UPPER & LOWER
UPPER/ LOWER function converts all characters in the specified string to uppercase/ lowercase.
Start-Tech Academy
REPLACE
REPLACE function replaces all occurrences of a specified string
Start-Tech Academy
REPLACE
REPLACE function replaces all occurrences of a specified string
SELECT
Customer_name,
Example country,
Replace (country,’United States’,’US’) AS country new
FROM customer;
Start-Tech Academy
TRIM,LTRIM & RTRIM
TRIM function removes all specified characters either from the beginning or the end of a string
RTRIM function removes all specified characters from the right-hand side of a string
LTRIM function removes all specified characters from the left-hand side of a string
Start-Tech Academy
TRIM,LTRIM & RTRIM
TRIM function removes all specified characters either from the beginning or the end of a string
RTRIM function removes all specified characters from the right-hand side of a string
LTRIM function removes all specified characters from the left-hand side of a string
Example SELECT trim(both ' ' from ' Start-Tech Academy ');
Start-Tech Academy
CONCAT
|| operator allows you to concatenate 2 or more strings together
Start-Tech Academy
CONCAT
|| operator allows you to concatenate 2 or more strings together
SELECT
Customer_name,
Example city|| ' , '||state|| ' , '||country AS address
FROM customer;
Start-Tech Academy
SUBSTRING
SUBSTRING function allows you to extract a substring from a string
Start-Tech Academy
SUBSTRING
SUBSTRING function allows you to extract a substring from a string
SELECT
Customer_id,
Customer_name,
SUBSTRING (Customer_id FOR 2) AS cust_group
FROM customer
WHERE SUBSTRING(Customer_id FOR 2) = ‘AB’;
Example SELECT
Customer_id,
Customer_name,
SUBSTRING (Customer_id FROM 4 FOR 5) AS cust_number
FROM customer
WHERE SUBSTRING(Customer_id FOR 2) = ‘AB’;
Start-Tech Academy
STRING AGGREGATOR
STRING_AGG concatenates input values into a string, separated by delimiter
Start-Tech Academy
STRING AGGREGATOR
STRING_AGG concatenates input values into a string, separated by delimiter
SELECT
order_id ,
Example STRING_AGG (product_id,‘, ')
FROM sales
GROUP BY order_id;
Start-Tech Academy
CEIL & FLOOR
CEIL function returns the smallest integer value that is greater than or equal to a number
FLOOR function returns the largest integer value that is equal to or less than a number.
CEIL (number)
Syntax FLOOR (number)
Start-Tech Academy
CEIL & FLOOR
CEIL function returns the smallest integer value that is greater than or equal to a number
FLOOR function returns the largest integer value that is equal to or less than a number.
SELECT order_line,
sales,
Example CEIL (sales),
FLOOR (sales) FROM sales
WHERE discount>0;
Start-Tech Academy
RANDOM
RANDOM function can be used to return a random number between 0 and 1
RANDOM( )
Syntax The random function will return a value between 0 (inclusive) and 1 (exclusive),
so value >= 0 and value < 1.
Start-Tech Academy
RANDOM
RANDOM function can be used to return a random number between 0 and 1
Start-Tech Academy
SETSEED
If we set the seed by calling the setseed function, then the random function will return a repeatable sequence of
random numbers that is derived from the seed.
Start-Tech Academy
SETSEED
If we set the seed by calling the setseed function, then the random function will return a repeatable sequence of
random numbers that is derived from the seed.
SELECT SETSEED(0.5);
Example SELECT RANDOM();
SELECT RANDOM();
Start-Tech Academy
ROUND
ROUND function returns a number rounded to a certain number of decimal places
ROUND ( number)
Syntax
Start-Tech Academy
ROUND
ROUND function returns a number rounded to a certain number of decimal places
SELECT order_line,
sales,
ROUND (sales)
Example FROM sales
Start-Tech Academy
POWER
POWER function returns m raised to the nth power
POWER ( m, n )
Syntax
This will be equivalent to m raised to the power n.
Start-Tech Academy
POWER
POWER function returns m raised to the nth power
Start-Tech Academy
CURRENT DATE & TIME
CURRENT_DATE function returns the current date.
CURRENT_TIME function returns the current time with the time zone.
CURRENT_TIMESTAMP function returns the current date and time with the time zone.
CURRENT_DATE
CURRENT_TIME ( [ precision ] )
CURRENT_TIMESTAMP ( [ precision ] )
Syntax
• The CURRENT_DATE function will return the current date as a 'YYYY-MM-DD'
format.
• CURRENT_TIME function will return the current time of day as a
'HH:MM:SS.GMT+TZ' format.
• The CURRENT_TIMESTAMP function will return the current date as a 'YYYY-
MM-DD HH:MM:SS.GMT+TZ' format.
Start-Tech Academy
CURRENT DATE & TIME
CURRENT_DATE function returns the current date.
CURRENT_TIME function returns the current time with the time zone.
CURRENT_TIMESTAMP function returns the current date and time with the time zone.
SELECT CURRENT_DATE;
SELECT CURRENT_TIME;
Example SELECT CURRENT_TIME(1);
SELECT CURRENT_TIMESTAMP;
Start-Tech Academy
AGE
AGE function returns the number of years, months, and days between two dates.
Start-Tech Academy
AGE
AGE function returns the number of years, months, and days between two dates.
Start-Tech Academy
EXTRACT
EXTRACT function extracts parts from a date
Start-Tech Academy
EXTRACT
EXTRACT function extracts parts from a date
Unit Explanation
day Day of the month (1 to 31)
decade Year divided by 10
Day of the year (1=first day of year, 365/366=last day of the year,
doy
depending if it is a leap year)
Number of seconds since '1970-01-01 00:00:00 UTC', if date value.
epoch
Units Number of seconds in an interval, if interval value
hour Hour (0 to 23)
minute Minute (0 to 59)
Number for the month (1 to 12), if date value. Number of months
month
(0 to 11), if interval value
second Seconds (and fractional seconds)
year Year as 4-digits
Start-Tech Academy
EXTRACT
EXTRACT function extracts parts from a date
Start-Tech Academy
Pattern Matching
1. LIKE statements
3. ~ (Regular Expressions)
Start-Tech Academy
LIKE WILDCARDS
The PostgreSQL LIKE condition allows you to perform pattern matching using Wildcards.
Wildcard Explanation
% Allows you to match any string of any length (including zero length)
_ Allows you to match on a single character
AB_C means string starts with AB, then there is one character, then there is C
Start-Tech Academy
LIKE
The PostgreSQL LIKE condition allows you to perform pattern matching using Wildcards.
Start-Tech Academy
WILDCARDS
Wildcard Explanation
| Denotes alternation (either of two alternatives).
* Denotes repetition of the previous item zero or more times
+ Denotes repetition of the previous item one or more times.
? Denotes repetition of the previous item zero or one time.
Start-Tech Academy
CONVERSION TO STRING
TO_CHAR function converts a number or date to a string
Start-Tech Academy
CONVERSION TO STRING
TO_CHAR function converts a number or date to a string
Parameter Explanation
9 Value (with no leading zeros)
0 Value (with leading zeros)
. Decimal
, Group separator
PR Negative value in angle brackets
Format Mask S Sign
L Currency symbol
MI Minus sign (for negative numbers)
PL Plus sign (for positive numbers)
SG Plus/minus sign (for positive and negative numbers)
EEEE Scientific notation
Start-Tech Academy
CONVERSION TO STRING
TO_CHAR function converts a number or date to a string
Parameter Explanation
YYYY 4-digit year
MM Month (01-12; JAN = 01).
Mon Abbreviated name of month capitalized
Month Name of month capitalized, padded with blanks to length of 9 characters
DAY Name of day in all uppercase, padded with blanks to length of 9 characters
Day Name of day capitalized, padded with blanks to length of 9 characters
Format Mask DDD
DD
Day of year (1-366)
Day of month (01-31)
HH Hour of day (01-12)
HH12 Hour of day (01-12)
HH24 Hour of day (00-23)
MI Minute (00-59)
SS Second (00-59)
am, AM, pm,
Meridian indicator
or PM
Start-Tech Academy
CONVERSION TO STRING
TO_CHAR function converts a number or date to a string
Start-Tech Academy
CONVERSION TO DATE
TO_DATE function converts a string to a date.
Start-Tech Academy
CONVERSION TO DATE
TO_DATE function converts a string to a date.
Parameter Explanation
YYYY 4-digit year
MM Month (01-12; JAN = 01).
Mon Abbreviated name of month capitalized
Month Name of month capitalized, padded with blanks to length of 9 characters
DAY Name of day in all uppercase, padded with blanks to length of 9 characters
Day Name of day capitalized, padded with blanks to length of 9 characters
Format Mask DDD
DD
Day of year (1-366)
Day of month (01-31)
HH Hour of day (01-12)
HH12 Hour of day (01-12)
HH24 Hour of day (00-23)
MI Minute (00-59)
SS Second (00-59)
am, AM, pm,
Meridian indicator
or PM
Start-Tech Academy
CONVERSION TO DATE
TO_DATE function converts a string to a date.
Start-Tech Academy
CONVERSION TO NUMBER
TO_NUMBER function converts a string to a number
Start-Tech Academy
CONVERSION TO NUMBER
TO_NUMBER function converts a string to a number
Parameter Explanation
9 Value (with no leading zeros)
0 Value (with leading zeros)
. Decimal
, Group separator
PR Negative value in angle brackets
Format Mask S Sign
L Currency symbol
MI Minus sign (for negative numbers)
PL Plus sign (for positive numbers)
SG Plus/minus sign (for positive and negative numbers)
EEEE Scientific notation
Start-Tech Academy
CONVERSION TO NUMBER
TO_NUMBER function converts a string to a number
Start-Tech Academy
CREATE USER
CREATE USER statement creates a database account that allows you to log into the database
Start-Tech Academy
CREATE USER
CREATE USER statement creates a database account that allows you to log into the database
Start-Tech Academy
GRANT & REVOKE
Privileges to tables can controlled using GRANT & REVOKE. These permissions can be any combination of SELECT,
INSERT, UPDATE, DELETE, INDEX, CREATE, ALTER, DROP, GRANT OPTION or ALL.
Start-Tech Academy
GRANT & REVOKE
Privileges to tables can controlled using GRANT & REVOKE. These permissions can be any combination of SELECT,
INSERT, UPDATE, DELETE, INDEX, CREATE, ALTER, DROP, GRANT OPTION or ALL.
Privilege Description
SELECT Ability to perform SELECT statements on the table.
INSERT Ability to perform INSERT statements on the table.
UPDATE Ability to perform UPDATE statements on the table.
DELETE Ability to perform DELETE statements on the table.
Privileges TRUNCATE Ability to perform TRUNCATE statements on the table.
Ability to create foreign keys (requires privileges on both
REFERENCES
parent and child tables).
TRIGGER Ability to create triggers on the table.
CREATE Ability to perform CREATE TABLE statements.
ALL Grants all permissions.
Start-Tech Academy
GRANT & REVOKE
Privileges to tables can controlled using GRANT & REVOKE. These permissions can be any combination of SELECT,
INSERT, UPDATE, DELETE, INDEX, CREATE, ALTER, DROP, GRANT OPTION or ALL.
Start-Tech Academy
DROP USER
DROP USER statement is used to remove a user from the database.
Start-Tech Academy
DROP USER
DROP USER statement is used to remove a user from the database.
Start-Tech Academy
RENAME USER
ALTER USER statement is used to rename a user in the database
Start-Tech Academy
RENAME USER
ALTER USER statement is used to rename a user in the database
Start-Tech Academy
FIND ALL USERS
Run a query against pg_user table to retrieve information about Users
SELECT usename
Syntax FROM pg_user;
Start-Tech Academy
FIND LOGGED-IN USERS
Run a query against pg_stat_activity table to retrieve information about Logged-in Users
Start-Tech Academy
Interview & performance tuning tips
Part 1
Theoretical concepts for interview preparation
Agenda Part 2
Performance tuning tips which help in faster data retrieval and
maintains database integrity
TABLESPACES
Tablespaces allow database administrators to define locations in the file system where the files representing database
objects can be stored
Start-Tech Academy
TABLESPACES
Tablespaces allow database administrators to define locations in the file system where the files representing database
objects can be stored
Start-Tech Academy
TABLESPACES
Tablespaces allow database administrators to define locations in the file system where the files representing database
objects can be stored
• If the partition or volume on which the cluster was initialized runs out of
space and cannot be extended, a tablespace can be created on a different
partition and used until the system can be reconfigured.
Start-Tech Academy
Primary Key
Start-Tech Academy
Primary Key
Customer Table
Customer ID First Name Last Name Age
V_001 Jay Pee 23
V_002 Kay Qu 23
V_003 Ell Ao 13
V_004 Emm Qu 24
V_005 Emm Es 67
Start-Tech Academy
Primary Key
Order Table
Order ID Customer_ID Product_key Value
O_001 V_001 P_001_01 65
O_002 V_001 P_001_02 23
O_003 V_001 P_002_01 13
O_004 V_003 P_003_01 41
O_005 V_005 P_002_01 67
Start-Tech Academy
Primary Key
Product Table
Product ID Variant Combine_column Name
P_001 01 P_001_01 Cola 500 ml
P_001 02 P_001_02 Coal 1 l
P_002 01 P_002_01 Coffee beans
P_003 01 P_003_01 Surf
P_004 01 P_002_01 Cookies
Start-Tech Academy
Primary Key
➢ City Name
➢ Country Name
➢ State
➢ Population
City Data ➢ Mean Temperature
➢ Pin Code
➢ Longitude
➢ Latitude
Start-Tech Academy
Foreign Key
Order ID Customer_ID Product_key Value
O_001 V_001 P_001_01 65
Order Table O_002 V_001 P_001_02 23
O_003 V_001 P_002_01 13
➢ ATOMICITY
Atomicity is an all-or-none proposition
➢ CONSISTENCY
Consistency ensures that a transaction can only bring the database from one valid
state to another
ACID ➢ ISOLATION
Isolation keeps transactions separated from each other until they’re finished.
➢ DURABILITY
Durability guarantees that the database will keep track of pending changes in such a
way that the server can recover from an abnormal termination
TRUNCATE
The TRUNCATE TABLE statement is used to remove all records from a table or set of tables in PostgreSQL. It performs
the same function as a DELETE statement without a WHERE clause.
Start-Tech Academy
TRUNCATE
The TRUNCATE TABLE statement is used to remove all records from a table or set of tables in PostgreSQL. It performs
the same function as a DELETE statement without a WHERE clause.
Example
Same as
DELETE FROM Customer_20_60;
Start-Tech Academy
Normalization
If we have a separate product table and category values are not noted in sales
table, then we can insert the sales transaction.
Insert Anomaly Order Line Order ID Order Date Customer ID Product ID Sales Category Product Name
Bush Somerset Collection
1 CA-2016-152156 08-11-2016 CG-12520 FUR-BO-10001798 261.96 Furniture
Bookcase
Hon Deluxe Fabric
2 CA-2016-152156 08-11-2016 CG-12520 FUR-CH-10000454 731.94 Furniture Upholstered Stacking Chairs
Rounded Back
Self-Adhesive Address Labels
3 CA-2016-138688 12-06-2016 DV-13045 OFF-LA-10000240 14.62 Office Supplies
for Typewriters by Universal
Bretford CR4500 Series Slim
4 US-2015-108966 11-10-2015 SO-20335 FUR-TA-10000577 957.5775 Furniture
Rectangular Table
Normalization
While updating data:
If we have a separate product table, we need to update only one row of data.
Update Anomaly
Order Line Order ID Order Date Customer ID Product ID Sales Category Product Name
1595 CA-2015-118423 24-03-2015 DP-13390 FUR-BO-10000362 359.058 Furniture Sauder Inglewood Library Bookcases
1611 CA-2014-156349 26-05-2014 ML-17395 FUR-BO-10000362 290.666 Furniture Sauder Inglewood Library Bookcases
2604 CA-2016-165848 04-06-2016 EN-13780 FUR-BO-10000362 136.784 Furniture Sauder Inglewood Library Bookcases
5395 US-2014-123183 19-11-2014 GR-14560 FUR-BO-10000362 1025.88 Furniture Sauder Inglewood Library Bookcases
7681 CA-2014-133592 31-12-2014 KM-16375 FUR-BO-10000362 341.96 Furniture Sauder Inglewood Library Bookcases
Normalization
While deleting data:
Deletion
Anomaly Order Line Order ID Order Date Customer ID Product ID Sales Category Product Name
FUR-BO- Bush Birmingham Collection
3513 CA-2017-140326 04-09-2017 HW-14935 825.174 Furniture
10000112 Bookcase Dark Cherry
Normalization
Rules
Order_ID Order_Date Ship_Date Customer_ID Product _ID
CA-2016-152156 08-11-2016 11-11-2016 CG-12520 FUR-BO-10001798
CA-2016-152156 08-11-2016 11-11-2016 CG-12520 FUR-CH-10000454
CA-2016-138688 12-06-2016 16-06-2016 DV-13045 OFF-LA-10000240
US-2015-108966 11-10-2015 18-10-2015 SO-20335 FUR-TA-10000577
US-2015-108966 11-10-2015 18-10-2015 SO-20335 OFF-ST-10000760
CA-2014-115812 09-06-2014 14-06-2014 BH-11710 FUR-FU-10001487
First Normal Form
• Maintain datatypes in a column
Rules
Order_ID Order_Date Ship_Date Customer_ID Product _ID
CA-2016-152156 08-11-2016 11-11-2016 CG-12520 FUR-BO-10001798
CA-2016-152156 08-11-2016 11-11-2016 CG-12520 FUR-CH-10000454
CA-2016-138688 12-06-2016 16-06-2016 DV-13045 OFF-LA-10000240
US-2015-108966 11-10-2015 18-10-2015 SO-20335 FUR-TA-10000577
US-2015-108966 11-10-2015 18-10-2015 SO-20335 OFF-ST-10000760
CA-2014-115812 09-06-2014 14-06-2014 BH-11710 FUR-FU-10001487
First Normal Form
• Each column should have unique column name
Rules
Order_ID Order_Date Ship_Date Customer_ID Product _ID
CA-2016-152156 08-11-2016 11-11-2016 CG-12520 FUR-BO-10001798
CA-2016-152156 08-11-2016 11-11-2016 CG-12520 FUR-CH-10000454
CA-2016-138688 12-06-2016 16-06-2016 DV-13045 OFF-LA-10000240
US-2015-108966 11-10-2015 18-10-2015 SO-20335 FUR-TA-10000577
US-2015-108966 11-10-2015 18-10-2015 SO-20335 OFF-ST-10000760
CA-2014-115812 09-06-2014 14-06-2014 BH-11710 FUR-FU-10001487
Second Normal Form
• Order_ID and Product_ID together form the composite primary key for this table
• Product name and Category only depend on product_ID and not on Order_ID
Rules
Customer ID Customer Name Age
CG-12520 Claire Gute 67
DV-13045 Darrin Van Huff 31
SO-20335 Sean O'Donnell 65
Boyce-Codd Normal Form
Scenario: John bought a Football and a baseball bat and received two coupons as a reward
Rules
Customer Product coupon
John Football Free home delivery
John Baseball Bat 10% off on next purchase
Scenario: John bought a Football and a baseball bat and received two coupons as a reward
• This table suggests that the purchaser of football did not get the free delivery coupon
4th Normal Form
Brand Product
Shop No. Brand Shop No. Product Nike Sport shoes
2 Nike 2 Sport shoes Nike Track suit
2 Adidas 2 Track suit Adidas Track suit
Adidas Sport shoes
Best Practices
Displays the execution plan for a query statement without running the query.
EXPLAIN VERBOSE
(Syntax) Displays the full query plan instead of just a summary.
query
Query statement to explain.
Start-Tech Academy
Best Practices
SOFT DELETE
Soft deletion means you don’t actually delete the record instead you are
SOFT DELETE marking the record as deleted
vs
HARD DELETE
HARD DELETE
Hard deletion means data is physically deleted from the database table.
Start-Tech Academy
Best Practices
UPDATE
Update customer set customer_name = (trim(upper(customer_name))
where (trim(upper(customer_name)) <> customer_name
UPDATE Every updated row is actually a soft delete and an insert. So updating every
vs row will increase the storage size of the table
CASE
CASE STATEMENT
Instead you can use the case statements while creating such tables
Start-Tech Academy
Best Practices
SYNTAX
VACUUM [ table ]
VACCUM USE
➢ Reclaims disk space occupied by rows that were marked for deletion by
previous UPDATE and DELETE operations.
➢ Compacts the table to free up the consumed space
➢ Use it on tables which you are updating and deleting on a regular basis
Start-Tech Academy
Best Practices
➢ The TRUNCATE statement is typically far more efficient than using the
DELETE statement with no WHERE clause to empty the table
TRUNCATE ➢ TRUNCATE requires fewer resources and less logging overhead
VS
➢ Instead of creating table each time try to use truncate as it will keep the
DELETE
table structure and properties intact
Start-Tech Academy
Best Practices
Pattern Matching
➢ Whenever possible use LIKE statements in place of REGEX expressions
➢ Do not use ‘Similar To’ statements, instead use Like and Regex
STRING ➢ Avoid unnecessary string operations such as replace, upper, lower etc
FUNCTIONS
String Operations
➢ Use trim instead of replace whenever possible
➢ Avoid unnecessary String columns. For eg. Use date formats instead of
string for dates
Start-Tech Academy
Best Practices
Syntax
SELECT a.order_line , a.product_id, b.customer_name, b.age
FROM sales_2015 AS a LEFT JOIN customer_20_60 AS b
ON a.customer_id = b.customer_id
JOINS ORDER BY customer_id;
Best Practices
➢ Use subqueries to select only the required fields from the tables
➢ Avoid one to many joins by mentioning Group by clause on the matching
fields
Start-Tech Academy
Best Practices
A schema is a collection of database objects associated with one particular database.
You may have one or multiple schemas in a database.
Start-Tech Academy
Best Practices
A schema is a collection of database objects associated with one particular database.
You may have one or multiple schemas in a database.
Start-Tech Academy
Final Project
In this Project, you will be using all the skills that you have acquired
About throughout this course.
• Ball-by-ball data
• Match-wise data
IPL dataset • Create an SQL based database and perform the given tasks
• The queries and results of this project will help to answer questions in the
final assessment