Chapter 8 SQL Semester II 2023 for students final(2)
Chapter 8 SQL Semester II 2023 for students final(2)
Introduction to SQL
1
Chapter 8
Introduction to SQL
DDL
• Create database Command
• Create table command
• Alter table command
2
Introduction to SQL Language
• The name SQL stands for Structured Query Language.
3
Introduction to SQL Language(Cont..)
• SQL is different from most other computer languages.
• With SQL, you describe the type of information you want. The
computer then determines the best procedure to use to
obtain it and runs that procedure. This is called a declarative
computer language because the focus is on the result
• You specify what the result should look like. The computer is
allowed to use any method of processing as long as it obtains
the correct result.
4
Introduction to SQL Language(Cont..)
• Most other computer languages are procedural. These are
languages like C, Cobol, Java, Assembler, Fortran, Visual Basic,
and others. In these languages, you describe the procedure
that will be applied to the data; you do not describe the
result. The result is whatever emerges from applying the
procedure to the data.
• SQL is a nonprocedural language, in contrast to the
procedural or third generation languages (3GLs) such as
COBOL and C that had been created up to that time.
Introduction to SQL Language(Cont..)
6
What Can SQL do?
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
What Can SQL do? (Cont..)
8
SQL DML and DDL
• SQL can be divided into two parts: The Data Manipulation
Language (DML) and the Data Definition Language (DDL).
DML
• The query and update commands form the DML part of SQL:
11
Relational database management system (RDBMS)
• A relational database management system (RDBMS) is a program
used to create, update, and manage relational databases.
• Some of the most well-known RDBMSs include :
– MySQL,
– PostgreSQL,
– Oracle Database.
12
PostgreSQL
PostgreSQL
• is an advanced, enterprise-class, and open-source relational
database system.
• PostgreSQL supports SQL (relational)
• PostgreSQL is a highly stable database
• PostgreSQL is used as a primary database for many web
applications as well as mobile and analytics applications.
13
• Language support
• PostgreSQL support most popular
programming languages:
– Python
– Java
– C#
– C/C+
– Ruby
– JavaScript (Node.js)
14
Installing PostgreSQL on Windows
15
Step 2) Check options.
You are given two options 1) Interactive Installer by EnterpriseDB
and 2) Graphical Installer by BigSQL.
• BigSQL currently installs pgAdmin version 4 which is
deprecated. It’s best to choose
16
Step 3) Select PostgreSQL version.
18
Step 7) Check data location.
– Click Next
– Click Next
20
PostgreSQL Create Database using pgAdmin
1. Launch PostgreSQL.
To launch PostgreSQL go to Start Menu and search
pgAdmin 4
2. Check pgAdmin.
You will see pgAdmin homepage.
3. Find PostgreSQL 15.
Click on Servers > PostgreSQL 15 in the left tree
4. Enter password.
– Enter super user password set during installation
– Click OK
5. In the Object Tree, right click and select create a
database to Postgres create database
21
22
6 In the pop-up,
– Enter Database Name
– Comment if any database – optional
– Click Save
7.DB is created and shown in the Object tree.
23
PostgreSQL Create Table: pgAdmin
24
25
Step 2) In the popup, Enter the Table Name
26
Step 4) In the object tree, you will see the table created
27
The CREATE DATABASE Statement
• The syntax for the typical CREATE DATABASE statement looks
like this:
SYNTAX:
CREATE DATABASE database_name
How to create database in PostgreSQL
command line and the GUI
29
Step 3) Enter the command
CREATE DATABASE university;
30
Step 4) Enter command \l to get a list of all
databases
Step 5) To connect to a Database use PostgreSQL
database command
\c university
31
Drop Database in PostgreSQL
– The DROP DATABASE in PostgreSQL is a statement
to permanently remove all catalog entries and
data directory.
– The database owner can only execute this
command. It can not be executed while someone
is connected with the target database. You need
to connect to some other database to execute the
DROP DATABASE command.
– So, you should be extra cautious when performing
this operation.
– PostgreSQL DROP DATABASE Syntax:
DROP DATABASE [IF EXISTS) name;
32
PostgreSQL Drop Database Using SQL
Shell(Command Line)
33
The CREATE TABLE Statement
• Here's the basic syntax for the CREATE TABLE
statement:
CREATE TABLE table_name
(field1 datatype [ NOT NULL ],
field2 datatype [ NOT NULL ],
field3 datatype [ NOT NULL ]...)
The CREATE TABLE Statement with primary key
35
PostgreSQL Data Types
• PostgreSQL supports the following data types:
– Text Types
– Numeric Types
– Dates and Times
Character Data types
Name Description
Allows you to declare variable-
varchar(n) length with a limit
Char(n) Fixed-length, blank padded
Use can use this data type to
Text declare a variable with
unlimited length
36
Numeric Datatypes
37
If you declared it as
decimal datatype ranges
from 131072 digits
decimal variable
before the decimal point
to 16383 digits after the
decimal point
If you declare it as the
number, you can include
number up to 131072
numeric variable
digits before the decimal
point to 16383 digits
after the decimal point
6 decimal digits
real 4 bytes
precision
15 decimal digits
double 8 bytes precision
38
Example 1:
39
Example 2:
40
PostgreSQL - DROP Table
• The PostgreSQL DROP TABLE statement is used to
remove a table definition and all associated data,
indexes, rules, triggers, and constraints for that
table.
Syntax
• Basic syntax of DROP TABLE statement is as
follows −
41
• You can verify if your table has been created successfully
using \d command, which will be used to list down all the
tables in an attached database.
• testdb-# \d
testdb-# \d employee
42
More on Data Types
• Name Storage Size Description
small
Range
smallserial 2 bytes autoincrementing 1 to 32767
integer
autoincrementing 1 to
serial 4 bytes integer 2147483647
large 1 to
bigserial 8 bytes autoincrementing 9223372036
integer 854775807
43
Example: Drop department table
Solution:
drop table department;
44
PostgreSQL - CONSTRAINTS
• The following are commonly used constraints available in
PostgreSQL.
– NOT NULL Constraint − Ensures that a column cannot have NULL
value.
command
CREATE TABLE department
(
dno int ,
dname varchar(50) NOT NULL
)
Eg:
create table coures_taken(
sid int ,
cno varchar(10),
constraint pk_sid_cno primary key(sid,cno)
);
Or
create table coures_taken(
sid int ,
cno varchar(10),
primary key(sid,cno)
);
50
Dropping Constraints
• To remove a constraint you need to know its name.
Eg:
CREATE TABLE COMPANY3(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
52
Foreign Key Constraints
• A foreign key constraint specifies that the
values in a column (or a group of columns)
must match the values appearing in some row
of another table.
• We say this maintains the referential integrity
between two related tables.
Example:
CREATE TABLE department
(
dno int ,
dname varchar(50) NOT NULL
)
CREATE TABLE employee(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL,
dno int references department(dno));
SQL FOREIGN KEY Constraint on ALTER
TABLE
alter table employee
56
To DROP a FOREIGN KEY Constraint
• To drop a FOREIGN KEY constraint, use the following SQL:
Eg:
ALTER TABLE persons
ALTER COLUMN age
DROP DEFAULT;;
SQL CHECK Constraint
• The CHECK constraint is used to limit the value
range that can be placed in a column.
• If you define a CHECK constraint on a single
column it allows only certain values for this
column.
• If you define a CHECK constraint on a table it
can limit the values in certain columns based
• SQL CHECK Constraint on CREATE TABLE
when the "Persons" table is created. The CHECK constraint specifies that
the column “Age" must only include integers greater than 18.:
FirstName varchar(255),
)
CHECK constraint on multiple columns
• To allow naming of a CHECK constraint, and for
defining a CHECK constraint on multiple
columns, use the following SQL syntax:
CREATE TABLE Persons
(
id int primary key,
Age int,
CONSTRAINT Persons_id_age check(id > 0 and
age > 18)
)
SQL CHECK Constraint on ALTER TABLE
• To create a CHECK constraint on the "P_Id"
column when the table is already created, use
the following SQL:
alter table e3
add constraint persons_age_chk check(age>18);
• To allow naming of a CHECK constraint, and for
defining a CHECK constraint on multiple
columns, use the following SQL syntax:
Eg:
drop index persons_fname_index;
The DROP TABLE Statement
• The DROP TABLE statement is used to delete a table.
74
Add Column in a Table
• We can add columns in a table using the ALTER TABLE
command with the ADD clause. For example,
Syntax:
ALTER TABLE table_name
ADD column_name datatype constraint;
Eg:
ALTER TABLE Persons
ADD phone varchar(10);
75
Add Multiple Columns in a Table
• We can also add multiple columns at once in a
table.
76
Example:
ALTER TABLE Persons
ADD phone varchar(10),
ADD address varchar(10),
Add Salary numeric(5,2);
77
Dropping a column from a table
Eg:
ALTER TABLE persons
RENAME TO employees;
80
Renaming a column
Eg:
ALTER TABLE persons
RENAME column fname TO first_name;
81
Lesson Summary
• The name SQL stands for Structured Query Language.
• SQL is a standard language for accessing and manipulating
databases.
• SQL is a nonprocedural language.
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
82
Homework
83
2. Write a SQL statement to create countries table with the
following fields and constraints.
84
3. Write a SQL statement to create a simple table movies which
should include columns movie_id, movie_name, movie_type and
movie_rating only if it does not exist. The movie_id should be an
unique indentifier of the table. It should store an auto
incremented value. Each field should not be null too
85
5.Write a SQL statement to add a column movie_director to the
movies_renamed table.
86
SQL-DML
87
SQL-DML
DML
• Insert Command
• Update command
• Delete command
• Select
88
DML (Data Manipulation Language)
89
Inserting Records (INSERT SQL Command)
90
INSERT statement examples
91
Inserting a single row into a table
• The following statement inserts a new row into the links table:
92
Inserting a date value
– To insert a date value into a column with the DATE
type, you use the date in the format 'YYYY-MM-
DD'.
93
Inserting values for all columns
Method 1:
INSERT INTO student (studID, FirstName, LastName, Sex)
VALUES ('AB101', 'Jemal', 'Abdella', 'Male')
Method 2:
INSERT INTO Student
VALUES ('AB101', 'Jemal', 'Abdella', 'Male')
94
INSERT Multiple Rows
95
Example: Inserting multiple records
INSERT INTO
links (url, name)
VALUES
('https://www.google.com','Google'),
('https://www.yahoo.com','Yahoo'),
('https://www.bing.com','Bing');
96
UPDATE statement
UPDATE table_name
SET column1 = value1,
column2 = value2,
...
WHERE condition;
97
Example:
UPDATE Student
SET FirstName = 'Merima', Sex = 'Female'
98
DELETE statement
99
Example
Syntax:
SELECT [ALL | DISTINCT] column1 [, column2]
FROM table1 [, table2]
[WHERE conditions]
[GROUP BY column-list]
[HAVING conditions]
[ORDER BY column-list [ASC | DESC] ]
101
The SELECT statement has the following clauses:
• Select distinct rows using DISTINCT operator.
• Sort rows using ORDER BY clause.
• Filter rows using WHERE clause.
• Group rows into groups using GROUP BY clause.
• Filter groups using HAVING clause.
• Join with other tables using joins such as INNER JOIN,
LEFT JOIN, FULL OUTER JOIN, CROSS JOIN clauses.
• Perform set operations using UNION, INTERSECT, and
EXCEPT.
102
Basic form of the SELECT statement
SELECT
select_list
FROM
table_name;
103
• PostgreSQL SELECT examples using Sample
dvdrental Database
104
1. SELECT statement to query data from one column
Write a SELECT statement to find the first names of all customers
from the customer table:
Solution:
select first_name
from customer
105
2. Using SELECT statement to query data from
multiple columns
Solution:
select first_name,email
from customer;
106
3. Using SQL SELECT statement to query data from all
columns of a table.
Solution:
select *
from customer;
107
4. SELECT statement with expressions
Solution
Select first_name || last_name|| ‘ “,email
From customer;
SELECT 5 * 3;
109
Column Alias
• A column alias allows you to assign a column or an expression
in the select list of a SELECT statement a temporary name.
The column alias exists temporarily during the execution of
the query.
Syntax of using a column alias:
SELECT column_name AS alias_name FROM table_name
Or
• If you want to rename the last_name heading, you can assign it a new
name using a column alias like this:
SELECT
first_name, last_name AS surname
FROM customer;
Or you can make it shorter by removing the AS keyword as follows:
SELECT
first_name, last_name surname
FROM customer 111
Assigning a column alias to an expression
SELECT
first_name || ' ' || last_name Full_Name
FROM
customer;
SELECT
first_name || ' ' || last_name “Full Name “
FROM
customer;
112
ORDER BY clause
• The ORDER BY clause allows you to sort rows returned by
a SELECT clause in ascending or descending order based on a
sort expression.
SELECT
select_list
FROM
table_name
ORDER BY
sort_expression1 [ASC | DESC],
...
sort_expressionN [ASC | DESC];
113
ORDER BY clause (Cont..)
114
1.The following query uses the ORDER BY clause to sort
customers by their first names in ascending order:
SELECT
first_name,
last_name
FROM
customer
ORDER BY
first_name ASC;
SELECT
first_name,
last_name
FROM
customer
ORDER BY
first_name DESC;
116
3. ORDER BY clause to sort rows by multiple columns
• The following statement selects the first name and last name from the
customer table and sorts the rows by the first name in ascending order
and last name in descending order
SELECT
first_name,
last_name
FROM
customer
ORDER BY
first_name ASC,
last_name DESC;
117
SELECT DISTINCT clause
• The DISTINCT clause is used in the SELECT statement to
remove duplicate rows from a result set.
• The DISTINCT clause keeps one row for each group of
duplicates.
• The DISTINCT clause can be applied to one or more columns
in the select list of the SELECT statement.
SELECT SELECT
DISTINCT column1 DISTINCT column1,column2
FROM FROM
table_name; table_name;
118
SELECT DISTINCT examples
• Let’s create a new table called distinct_demo and insert data
into it for practicing the DISTINCT clause.
119
INSERT INTO distinct_demo (bcolor, fcolor)
VALUES
('red', 'red'),
('red', 'red'),
('red', NULL),
(NULL, 'red'),
('red', 'green'),
('red', 'blue'),
('green', 'red'),
('green', 'blue'),
('green', 'green'),
('blue', 'red'),
('blue', 'green'),
('blue', 'blue');
120
SELECT
id,
bcolor,
fcolor
FROM
distinct_demo ;
121
DISTINCT multiple columns
SELECT
DISTINCT bcolor,
fcolor
FROM
distinct_demo
ORDER BY
bcolor,
fcolor;
• The query returns the unique combination of bcolor and fcolor from the
distinct_demo table
122
WHERE clause
• The SELECT statement returns all rows from one or more
columns in a table.
• To select rows that satisfy a specified condition, you use a
WHERE clause.
The syntax of the WHERE clause is as follows:
SELECT select_list
FROM table_name
WHERE condition
ORDER BY sort_expression
123
Order of Evaluation:
124
• To form the condition in the WHERE clause, you use
comparison and logical operators:
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> or != Not equal
AND Logical operator AND
OR Logical operator OR
IN Return true if a value matches any value in a list
BETWEEN Return true if a value is between a range of values
LIKE Return true if a value matches a pattern
IS NULL Return true if a value is NULL
NOT Negate the result of other operators
125
1) Using WHERE clause with the equal (=) operator example
• The following statement uses the WHERE clause customers
whose first names are Jamie:
SELECT
last_name,
first_name
FROM
customer
WHERE
first_name = 'Jamie';
126
2) Using WHERE clause with the AND operator example
127
3) Using the WHERE clause with the OR operator example
• This example finds the customers whose last name is
Rodriguez or first name is Adam by using the OR operator:
SELECT
first_name,
last_name
FROM
customer
WHERE
last_name = 'Rodriguez' OR
first_name = 'Adam';
128
4) Using WHERE clause with the IN operator example
• If you want to match a string with any string in a list, you can
use the IN operator.
value IN (value1,value2,...)
129
• For example, the following statement returns customers
whose first name is Ann, or Anne, or Annie:
SELECT
first_name,
last_name
FROM
customer
WHERE
first_name IN
('Ann','Anne','Annie');
130
NOT IN operator
131
5) Using the WHERE clause with the LIKE operator example
• To find a string that matches a specified pattern, you use the LIKE operator.
The following example returns all customers whose first names start with the
string Ann:
SELECT
first_name,
last_name
FROM
customer
WHERE
first_name LIKE 'Ann%
• The % is called a wildcard that matches any string. The 'Ann%' pattern
matches any string that starts with 'Ann'.
132
Wildcard characters
• PostgreSQL supports two types of wildcards
represented with a percentage sign “%,” and an
underscore sign “_”.
• The percentage wildcard "%" matches sequences of
characters, while the underscore wildcard "_"
matches a single character.
• These wildcards are used with the LIKE operator to
perform the pattern matching.
133
Examples:
_x all those values that start with anything but their second letter
must be “x”.
_x_ you can place anything at the first and third index however
the second index must have the letter “x”.
135
6) Using the WHERE clause with the BETWEEN operator
example
• The following example finds customers whose customer_id is
between 1 and 10
select customer_id,first_name
from customer
where customer_id between 1 and 10;
136
NOT BETWEEN
SELECT
customer_id,
payment_id,
amount
FROM
payment
WHERE
amount NOT BETWEEN 8 AND 9;
137
7) Using the WHERE clause with the not equal operator (<>)
example
• This example finds customers whose first names start with Bra
and last names are not Motley:
SELECT
first_name,
last_name
FROM
customer
WHERE
first_name LIKE 'Bra%' AND
last_name <> 'Motley';
• Note that you can use the != operator and <> operator
interchangeably because they are equivalent.
138
table aliases
• Table aliases temporarily assign tables new names during the
execution of a query.
• he following illustrates the syntax of a table alias:
table_name AS alias_name;
139
Aggregate functions
• Aggregate functions perform a calculation on a set of rows
and return a single row.
– These are:
• SUM()
• MIN()
• MAX()
• AVG()
• COUNT()
140
SUM()
1. Display the total amount of payments using the payment
table.
Solution
SELECT SUM(amount) as “Total Payement”
FROM payment;
141
AVG() function
SELECT AVG(amount)
FROM payment;
SELECT round(AVG(amount))
FROM payment; 142
COUNT() function
SELECT
COUNT(*)
FROM
film;
143
MAX() function
SELECT
max(replacement_cost)
FROM
film;
144
MIN() function
SELECT
min(replacement_cost)
FROM
film;
145
Example:
Using payment table, display the max, min, and average
amount.
Solution
SELECT MAX(salary) as Max , MIN(salary) as MIN , AVG(salary)
as Average
FROM payment
146
GROUP BY clause
• The GROUP BY clause divides the rows returned from the
SELECT statement into groups.
• For each group, you can apply an aggregate function e.g.,
SUM() to calculate the sum of items or COUNT() to get the
number of items in the groups.
147
• The following statement illustrates the basic syntax of the
GROUP BY clause:
SELECT
column_1,
column_2,
...,
aggregate_function(column_3)
FROM
table_name
GROUP BY
column_1,
column_2,
148
...;
Example:
1.Use emp table to display the sum
of the salaries of employees in
each job category.
Solution:
149
Example:
2.Use emp table to display the number
employees in
each job category.
Solution:
150
3. Using emp table, display the max and min salaries of
employees for each job category.
151
HAVING clause
152
Example:
1.Use emp table to display the sum
of the salaries of employees in
Each job category with total salary
Greater than 5000.
Solution:
153
Lesson Summary
• INSERT statement allows you to insert a new row into a table
• UPDATE statement allows you to modify data in a table.
• DELETE statement allows you to delete one or more rows from
a table
154
Summary
Syntax:
SELECT [ALL | DISTINCT] column1 [, column2]
FROM table1 [, table2]
[WHERE conditions]
[GROUP BY column-list]
[HAVING conditions]
155
Lesson Summary
156
Lesson Summary
• Use the ORDER BY clause in the SELECT
statement to sort rows.Use the ASC option
to sort rows in ascending order and DESC
option to sort rows in descending order.
SELECT DISTINCT statement to remove duplicate
rows returned by a query
157
Homework
(For the following questions, use the dvdrental sample database)
158
4. Write a query that list the film_id,title and length of all films with
film length between 50 and 100 sorted in ascending order by title.
159
SQL-DML Part III
160
• Join commands
• The CROSS JOIN
• The INNER JOIN
• The LEFT OUTER JOIN
• The RIGHT OUTER JOIN
• The FULL OUTER JOIN
• Subquery
• View
• Function
• Stored Procedure
• Triggers
161
Joins
• joins clause is used to combine records from two or more
tables in a database.
164
The CROSS JOIN
• A CROSS JOIN matches every row of the first table with every
row of the second table
165
Sample Tables for CROSS JOIN example
166
Select * from basket_a cross join basket_b
167
The INNER JOIN
• A INNER JOIN creates a new result table by combining column
values of two tables (table1 and table2) based upon the join-
predicate.
• The query compares each row of table1 with each row of table2
to find all pairs of rows, which satisfy the join-predicate.
• When the join-predicate is satisfied, column values for each
matched pair of rows of table1 and table2 are combined into a
result row.
168
INNER JOIN (Cont…)
FROM table1
ON table1.common_filed = table2.common_field;
169
Example:
select a,basket_a,b,fruit_b
from basket_a inner join basket_b
on fruit_a=fruit_b
170
The LEFT OUTER JOIN
• In LEFT OUTER JOIN, an inner join is performed first. Then, for
each row in table T1 that does not satisfy the join condition
with any row in table T2, a joined row is added with null
values in columns of T2.
• Thus, the joined table always has at least one row for each
row in T1.
• The following is the syntax of LEFT OUTER JOIN −
171
Example:
Select a,fruit_a,b,fruit_b
from basket_a left outer join basket_b on
fruit_a=fruit_b;
172
The RIGHT OUTER JOIN
• In RIGHT OUTER JOIN, an inner join is performed first. Then,
for each row in table T2 that does not satisfy the join
condition with any row in table T1, a joined row is added with
null values in columns of T1.
• Thus, the joined table always has at least one row for each
row in T2.
• The following is the syntax of RIGHT OUTER JOIN −
173
Example:
Select a,fruit_a,b,fruit_b
from basket_a right outer join basket_b on
fruit_a=fruit_b;
174
FULL OUTER JOIN
• First, an inner join is performed. Then, for each row in
table T1 that does not satisfy the join condition with any
row in table T2, a joined row is added with null values in
columns of T2. In addition, for each row of T2 that does
not satisfy the join condition with any row in T1, a joined
row with null values in the columns of T1 is added.
• The following is the syntax of FULL OUTER JOIN −
Select a,fruit_a,b,fruit_b
from basket_a full outer join basket_b on
fruit_a=fruit_b;
176
Sample Tables for INNER JOIN example
178
Solution (Using Table alies)
SELECT
c.customer_id,first_name,last_name,
amount,payment_date
FROM customer C INNER JOIN payment p
ON c.customer_id = p.customer_id
ORDER BY payment_date;
179
Keyword using
• Whenever two tables join on the same column name we can
use the using syntax.
Eg:
SELECT
c.customer_id,first_name,last_name,
amount,payment_date
FROM customer C INNER JOIN payment p
USING (customer_id)
ORDER BY payment_date;
180
INNER JOIN to join three tables
The following diagram illustrates the relationship between three tables: staff,
payment, and customer.
• Each staff handles zero or many payments. And each payment is processed
by one and only one staff.
• Each customer made zero or many payments. Each payment is made by
one customer.
181
Example :Write a query that displays the:
– customer id,first name and last name,
– Staff first name and last name
– Amount and payment date
Solution
SELECT c.customer_id,,c.first_name customer_first_name,
c.last_name customer_last_name,s.first_name
staff_first_name,s.last_name staff_last_name,
amount, payment_date
FROM customer c INNER JOIN payment p
ON p.customer_id = c.customer_id
INNER JOIN staff s ON p.staff_id = s.staff_id
ORDER BY payment_date;
182
OR
SELECT c.customer_id,,c.first_name customer_first_name,
c.last_name customer_last_name,s.first_name
staff_first_name,s.last_name staff_last_name,
amount, payment_date
FROM customer c INNER JOIN payment p
USING(customer_id )
INNER JOIN staff s USING(staff_id)
ORDER BY payment_date;
183
self-join
• A self-join is a regular join that joins a table to itself.
184
self-join (Cont..)
• The following statements create the employee table
and insert some sample data into the table.
185
Sample table for self-join example
INSERT INTO employee (
employee_id,
first_name,
last_name,
manager_id
)
VALUES
(1, 'Windy', 'Hays', NULL),
(2, 'Ava', 'Christensen', 1),
(3, 'Hassan', 'Conner', 1),
(4, 'Anna', 'Reeves', 2),
(5, 'Sau', 'Norman', 2),
(6, 'Kelsie', 'Hays', 3),
(7, 'Tory', 'Goff', 3),
(8, 'Salley', 'Lester', 3); 186
Example: Write a query that displays list of all employees with their
respective mangers
SELECT
e.first_name || ' ' || e.last_name employee,
m .first_name || ' ' || m .last_name manager
FROM
employee e
INNER JOIN employee m ON m .employee_id =
e.manager_id
ORDER BY manager;
187
NULL Values
– NULL is the term used to represent a missing value.
– A NULL value in a table is a value in a field that appears to
be blank.
– A field with a NULL value is a field with no value.
– NULL value is different from a zero value or a field that
contains spaces
188
IS NOT NULL operator
Eg: select * from emp where comm is not null;
189
Subquery
• allows you to construct complex queries
• Suppose we want to find the films whose rental rate is higher than the
average rental rate. We can do it in two steps:
• Find the average rental rate by using the SELECT statement and average
function ( AVG).
• Use the result of the first query in the second SELECT statement to find the
films that we want.
190
• The following query gets the average rental rate:
SELECT SELECT
AVG (rental_rate) film_id,
FROM title,
film; rental_rate
FROM
film
WHERE
rental_rate > 2.98;
Now, we can get films whose rental rate is higher than the
average rental rate:
191
• A subquery is a query nested inside another query
• To construct a subquery, we put the second query in brackets
and use it in the WHERE clause as an expression:
SELECT
film_id,
title,
rental_rate
FROM
film
WHERE
rental_rate > (
SELECT
AVG (rental_rate)
FROM
film 192
• The query inside the brackets is called a subquery or an inner query.
• A subquery is used to return data that will be used in the main query
as a condition to further restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE and DELETE
statements along with the operators like =, <, >, >=, <=, IN, etc.
193
Using IN with subquery
194
select empno,ename,sal
from emp
where empno
in (select empno from emp where sal > 2000);
195
VIEWS
• Views are virtual tables. That is, they are not real tables;
196
Creating Views
• views are created using the CREATE VIEW statement
• views can be created from a single table, multiple
tables, or another view.
The basic CREATE VIEW syntax is as follows −
197
CREATE VIEW example
Solution:
SELECT empno,ename,salary
FROM employee;
198
Example :create a view called customer_payment_view with
customer_id, first_name, last_name, amount, payment_date
columns from both customer and payment tables.
199
Dropping Views
Syntax:
DROP VIEW view_name;
Solution:
Drop view employee_view;
200
Function
• function or a stored procedure is a set of SQL and procedural
commands such as declarations, assignments, loops, flow-of-
control etc. stored on the database server
201
Syntax of PostgreSQL CREATE Function command
CREATE [OR REPLACE] FUNCTION function_name (arguments)
RETURNS return_datatype
LANGUAGE plpgsql
AS $variable_name$
DECLARE
declaration;
[...] -- variable declaration
BEGIN
< function_body >
[...] -- logic
RETURN { variable_name | value }
END;
202
$$
Example:
203
Solution:
create or replace function count_films1(len_from integer,len_to
integer)
returns integer
language plpgsql
as
$function$
declare
total integer;
begin
select count_films1(120,200);
205
Example 2:
206
Solution
create or replace function compute_sum(d_no integer)
returns numeric
language plpgsql
as
$function$
declare
total numeric;
begin
select sum(sal) into total
from emp
where deptno=d_no;
return total;
end;
$function$;
207
Stored PROCEDURE
208
Creating a Stored PROCEDURE
Syntax:
210
Example:
1.Create a stored procedure that takes two arguments(an id
number and balance for an account holder) and inserts the
record of this account to the accounts table.
211
Solution
create or replace procedure transfer(from_id integer,to_id
integer,amount numeric)
language plpgsql
as
$$
declare
begin
update accounts
set balance=balance-amount
where id=from_id;
update accounts
set balance=balance+amount
where id=to_id;
end; 212
$$;
How to call a stored procedure?
Syntax:
call the_stored_procedure_name(arguments)
call transfer(1,2,5000.00)
213
Example:
2. Create a stored procedure that takes three arguments(two id
numbers and amount) and transfers the amount from the
balance of account of the first id to the account of the second id.
214
Solution
begin
insert into accounts(name,balance)
values(name,balance);
end;
$$;
215
Solution(Cont..)
call insert_record(‘Kedir’,20000.00);
216
TRIGGERS
• Triggers are database callback functions, which are
automatically performed/invoked when a specified database
event occurs.
• Trigger is a function, which involved automatically whenever
an event linked with a table.
• The event can be described as any of the following INSERT,
UPDATE, DELETE or TRUNCATE.
217
Type of Triggers
– Row-level trigger
– Statement-level trigger
218
Creating a trigger in postgresql
Steps:
1. Firstly, we can specify a trigger function.
– Trigger is a function, which invoked automatically
whenever an event linked with a table. The event can be
described as any of the following INSERT, UPDATE, DELETE
or TRUNCATE.
219
Syntax of Create trigger function
220
Syntax of PostgreSQL CREATE TRIGGER command:
• The event parameter is used to define the event which requested the
trigger, and it can be INSERT, UPDATE, DELETE, or TRUNCATE.
221
• A trigger that is marked FOR EACH ROW is called once for every row
that the operation modifies. In contrast, a trigger that is marked FOR
EACH STATEMENT only executes once for any given operation,
regardless of how many rows it modifies.
222
CREATE TABLE Clients(
ID INT GENERATED ALWAYS AS IDENTITY,
First_name VARCHAR(50) NOT NULL,
Last_name VARCHAR(50) NOT NULL,
PRIMARY KEY(ID)
);
224
Creating a trigger function
return NEW;
end;
$$
language plpgsql;
225
Creating a trigger
226
Testing the trigger on Updating clients table
UPDATE clients
SET first_name='Ayele'
WHERE id=1;
227
Drop Trigger command
Example:
228
Lesson Summary
• Use the DROP VIEW statement to remove one or more views
from the database.
• Joins clause is used to combine records from two or more
tables in a database.
• Join Types in PostgreSQL are −
• The CROSS JOIN
• The INNER JOIN
• The LEFT OUTER JOIN
• The RIGHT OUTER JOIN
• The FULL OUTER JOIN
229
Lesson Summary(cont..)
• Views are virtual tables. That is, they are not real tables;
• A view can be created from one or many tables,
• a view does not store data physically like a table
230
Lesson Summary(cont..)
Syntax for creating a function
language plpgsql
as $$
declare
-- variable declaration
begin
end; $$ 232
Lesson Summary(cont..)
234
Homework (Cont…)
2. Question on comparing the rows with the same table. Use the film
table from the sample database to write a query that finds all pair
of films that have the same length
235
Homework (Cont…)
236
Homework (Cont…)
237
5. Use the following two tables:
a. Create a trigger
CREATE TABLE employees(
ID INT GENERATED ALWAYS AS IDENTITY, function that inserts
records to the
First_name VARCHAR(50) NOT NULL, log_employees table
Last_name VARCHAR(50) NOT NULL, when records in the
PRIMARY KEY(ID) employees table are
);
CREATE TABLE log_employees ( updated.
ID INT GENERATED ALWAYS AS IDENTITY,
Emp_id INT NOT NULL, b.create a trigger that
Old_First_name VARCHAR(50) NOT NULL,
executes the trigger
New_First_name VARCHAR(50) NOT NULL,
changed_on TIMESTAMP(5) NOT NULL function when a record
); of employees table is
updated.
238
References
https://www.postgresqltutorial.com/postgresql-getting-
started/what-is-postgresql/
239