0% found this document useful (0 votes)
212 views

Ch-3 SQL

SQL is a standard language used to access and manipulate databases. It allows users to define, manipulate, and control data within a relational database management system (RDMS). SQL statements are used to perform tasks like querying and modifying database tables and views. The basic structure of an SQL query consists of SELECT, FROM, and WHERE clauses which correspond to the projection, Cartesian product, and selection operations in relational algebra.

Uploaded by

vrushali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
212 views

Ch-3 SQL

SQL is a standard language used to access and manipulate databases. It allows users to define, manipulate, and control data within a relational database management system (RDMS). SQL statements are used to perform tasks like querying and modifying database tables and views. The basic structure of an SQL query consists of SELECT, FROM, and WHERE clauses which correspond to the projection, Cartesian product, and selection operations in relational algebra.

Uploaded by

vrushali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 88

Ch-2 SQL

SQL Introduction:
• SQL is a standard language for accessing and manipulating databases.
SQL stands for Structured Query Language. SQL lets you access and
manipulate databases. 
• SQL is the standard language for the Relational Database System. SQL is
a database computer language designed for the retrieval and management
of data in a relational database.
•  All the Relational Database Management Systems (RDMS) like MySQL,
MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL
as their standard database language.
Introduction to Query Language
•  A query language for relational models is based on relational algebra. It provides a notion for representing
queries.
• The commercial database system requires a more user-friendly query language. SQL i.e. Structured Query
Language (SQL), it uses a combination of relational algebra and relational calculus constructs. 
• SQL contains other capabilities besides querying a database.
•  These capabilities include features for defining the structure of the data, features for modifying data in the
databases and features for specifying security constraints. 
• There are numerous versions of SQL. The original version was developed at IBM's San Jose Research
Laboratory by Dr. E. F. Codd in early 1970. This was based on the relational database model. 
• After that IBM's research division and Donald Chamberlin developed a prototype language called sequel i.e.
Structured English Query Language. 
• For some legal reason, IBM eventually changed the name sequel/2 to SQL (Structured Query Language). In
1986, ANSI and ISO had declared SQL as a standard language. Therefore sometimes, it is referred to as
Standard Query Language. From 1986, SQL has become a universally adopted language. 
Features of SQL:
1. SQL is very flexible.
 2. SQL based applications are portable i.e., they can be run on any system. 
3. SQL is a high level language. 
4. SQL is a free-format syntax which gives users the ability to structure SQL statements on any of
the screen.
 5. SQL can be embedded also in front end application code like of PHP, JAVA and so on. 

Elements of SQL:
SQL contains following elements:
1. Queries retrieve data based on particular or specific creation.
 2. Statements may control program flow, transactions etc. 
3. Expressions can produce either scalar values or tables which consisting of rows and columns of
data. 
4. Clauses are in some cases optional, constituent components of queries and statements.
The user can write a SQL statement and submit it to the DBMS. DBMS will retrieve the
appropriate data from the disk and return it to the user.
 Architecture of SQL: 
• Fig.  shows SQL architecture which shows detailed process of SQL. 
• When you are executing an SQL command for any RDBMS, the system determines the best way to carry
out your request and SQL engine figures out how to interpret the task.

SQL Request

DBMS DataBase

Data
Advantages of SQL: 

1.Simplicity: Many problems can be expressed in SQL more easily, simply and concisely than in
lower level languages. Simplicity, in turn, means increased productivity. 

2 .Completeness: The language is relationally complete. Users can write a very large class of
queries.

3. Data Independence: SQL DML statements include no reference to explicit access paths such
as indexes or physical sequence.

4.Ease of Extension: It can be easily extended by using built-in functions. -4.Support for Higher
Level Languages: SQL can conveniently be used with higher languages.
BASIC STRUCTURE
• SQL is used as a standard relational database language because it allows users to access data in RDBMS
(Relational Database Management System) such as Oracle, Sybase, Informix, PostgreSQL etc. 
• SQL also allows the user to define the data in a database and manipulates that data.
•  The non-relational database systems also support SQL interface. SQL is a special purpose, nonprocedural
language that supports the definition, manipulation and control of data in RDBMS.It is called as special-
purpose because only the database can be handled.
•  The SQL has several parts like Data Definition Language (DDL), Data Manipulation Language (DML)
View definition, Embedded SQL, Integrity, Authorization, Transaction control.
•  Even though SQL has various parts, we will consider only DDL which allows us to create and maintain
data manipulation objects such as tables, views, sequences. 
• View means duplicate copy of table used for security purposes. The sequence is for creating numeric
values.
•  A query is a database command that retrieves records. Using queries, we can pull data from one or more
fields from one or more tables.
•  The statement which is used to retrieve the information is called as a query. A query is used to extract data
from the database in a readable format according to the user's request.
• For instance, if you have an employee table, you might issue a SQL statement that return the employee
who is paid the most. This request to the database for usable employee information is a typical query that
can be performed in a relational database. 
The basic structure of an SQL expression consists of three clauses as given below: 

1.The SELECT Clause corresponds to projection operation of the relational algebra.The attributes desired in the result of a
query. 
2.The FROM clause corresponds to the Cartesian product operation of the relational algebra.It list  the relations to be scanned
in the evaluation of the expression. 
3.The WHERE clause corresponds to the selection predicate of the relational algebra. It consist of a predicate involving
attributes of the relations that appear in the FROM clause. 
A typical SQL query has the following form or structure:
SELECT A1, A2, ..........., An
 FROM r1, r2, ............. rn
 WHERE p;
where, A1 .... An - represents an attribute,
r1,r2, .... rn- represents relation, and
p - is a predicate.
SQL forms the cartesian product of the relations named in the from clause, performs a relational  algebra selection using
the where clause predicate, and then projects the result onto the attributes of the select clause.
Example:
SELECT * 
FROM Book
WHERE price > 100.00
• Query processing includes translation of high-level queries into low-level expressions that can be
used at the physical level of the file system, query optimization and actual execution of the query
to get the result. 
• It is a three-step process that consists of parsing and translation, optimization and execution of
the query submitted by the user as shown in Fig.
Creating and Deleting a Database:
 To Create Database: 
The CREATE DATABASE statement is used to create a new database.After creating a database,
we can create several other database objects (tables, views, procedure into it.
Syntax:
CREATE DATABASE Database_Name;
•  Always database name should be unique within the RDBMS. 

Example: If you want to create new database <user_DB>, then


CREATE DATABASE then CREATE DATABASE statement would be as follows:
CREATE DATABASE user_DB;
To Drop/Delete Database: 
The DROP DATABASE statement is used to drop or delete a database. Dropping of the database will
drop all database objects (tables, views, procedures etc.) inside it.
Syntax:
DROP DATABASE Database_Name;
Example:
DROP DATABASE user_DB;

• PostgreSQL provides two ways of creating a new database using CREATE DATABASE, an
SQLcommand and Using createdb a command-line executable. 
• The syntax for createdb is:
createdb [option... ] [dbname [description]].

•  In PostgreSQL we can delete a database using DROP DATABASE, an SQL command and using
dropdb a command-line executable. 
• PostgreSQL command line executable dropdb is a command-line wrapper around the SQL command
DROP DATABASE.
•  The syntax for dropdb is:
dropdb [option...] dbname.
Data Types in PostgreSQL: 
PostgreSQL supports a wide set of data types. Some of them are: 
1. Numeric:
• PostgreSQL provides two distinct types of numbers namely, integers and floating-point numbers, Integer
(INT) is a 4-byte integer that has a range from - 2,147,483,648 to 2,147,483,647. float(n) is a floating-point
number whose precision, at least, n, up to a maximum of 8 bytes. numeric or numeric(p,s) is a real number
with p digits with s number after the decimal point.The numeric(p,s) is the exact number. 

2. Character:
• CHAR(n) is the fixed-length character with space padded. If you insert a string that is shorter than the length
of the column, PostgreSQL pads spaces. If you insert a string that is longer than the length of the column,
PostgreSQL will issue an error. VARCHAR(n) is the variable-length character string. With VARCHAR(n), you
can store up to n characters.

 3. Date and Time:


• PostgreSQL supports a full set of SQL date and time types. The date data type is 4 bytes and shows date (no
time of day). 

4. Boolean:
• PostgreSQL provides the standard SQL type Boolean. The Boolean data type (1 byte) can have the state true
or false.
DATA DEFINITION LANGUAGE (DDL) COMMANDS:
•   DDL commands used for definition and creation objects in database like Table.
•   DDL commands are mainly used for design and definition the structure of a database.
•   SQL DDL commands are CREATE, ALTER, DROP, DESC, RENAME, and TRUNCATE as explained in
following topics. 

1. CREATE TABLE Command:


•   The SQL CREATE TABLE statement is used to create a new table.
•   Creating a basic table involves naming the table and defining its columns and each column's data type. 
Syntax: 
CREATE TABLE table_name(
column1 datatype, 
column2 datatype,
 column3 datatype,
columnN datatype,
 PRIMARY KEY( one or more columns )
);
Following example, creates a CUSTOMERS table with ID as primary key and NOT NULL are the constraints showing
that these fields can not be NULL while creating records in this table:
Syntax:
  CREATE TABLE CUSTOMERS(
ID  INT NOT NULL, 
NAME VARCHAR (20) NOT NULL, 
AGE INT NOT NULL, 
ADDRESS CHAR (25), 
SALARY DECIMAL (18, 2),
  PRIMARY KEY (ID)
);
• We can verify if our table has been created successfully by looking at the message displayed by the SOL server,
otherwise we can use DESC command as follows:
DESC CUSTOMERS; 
Field Type Null Key Default Extra
ID Int(11) No PRI - -
Name Varchar(20) No - - -
Age Int(11) No - - -
Address char(25) Yes - Null -
Salary Decimal(18,2) Yes - Null -
CREATE TABLE command consist of following constraints:
(i) Unique Constraint ensures that no two rows have the same value in the specified columns.
(ii) Primary Key Constraints declares a column as the primary key of the table.
(iii) Check Constraint limits values that can be inserted into a column of a table.
(iv)Default Constraint assigns a default value can be specified for a column using the default clause.

 2. DROP TABLE Command: 


• The DROP TABLE statement is used to remove a table definition and all data, indexes, constraints, and
permission specifications for that table.
 Syntax:
DROP TABLE table_name; 
Example:
DROP TABLE CUSTOMERS; 
• Now, if you would try DESC command, then you would get error as follows:
DESC CUSTOMERS;
ERROR 1146 (42502): Table 'TEST.CUSTOMERS' doesn't exist
3. DESC Command: 
• The table structure can be described by using DESC command
Syntax:
DESC table_name; 
Example: Let us first verify CUSTOMERS table and then we would delete it from the database:
DESC CUSTOMERS;

Field Type Null Key Default Extra


ID Int(11) No PRI - -
Name Varchar(20) No - - -
Age Int(11) No - - -
Address char(25) Yes - Null -
Salary Decimal(18,2) Yes - Null -

• 'Delete' is used to delete tuples from the table whereas 'drop' is used to delete the whole table.
4. TRUNCATE Command: 
• TRUNCATE TABLE command is used to delete complete data from an existing table. 
TRUNCATE TABLE table_name; 
• Example: Consider the CUSTOMERS table having the following record:
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
5 Hardik 27 Bhopal 8500.0

Following is the example to truncate:


TRUNCATE TABLE CUSTOMERS; 
NOW, CUSTOMERS table is truncated and following would be the output from SELECT statement
SELECT * FROM CUSTOMERS; 
Empty set (0.00 sec)
ALTER TABLE Command:
• The ALTER TABLE command is used to modify the definition (structure) of a table by modifying the definition of its
columns. 
• The ALTER command is used to perform the following functions:
(i) Add, drop, modify table columns,
(ii) Add and drop constraints, and 
(iii) Enable and Disable constraints
Syntax:
• The basic syntax for ALTER TABLE to a add a new column in a existing table is,
ALTER TABLE table_name ADD column_name datatype;
•  The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is,
ALTER TABLE table_name DROP COLUMN column_name;
• Example: Consider the CUSTOMERS table having the following records:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
5 Hardik 27 Bhopal 8500.0
• Following is the example to ADD a new column in an existing table:
ALTER TABLE CUSTOMERS ADD Gender char(1);
•  Now, CUSTOMERS table is changed and following would be output from SELECT statement:

ID NAME AGE ADDRESS SALARY Gender


1 Ramesh 32 Ahmednagar 2000.0 NULL
2 Khilan 25 Delhi 1500.0 NULL
3 Kaushik 23 Kota 2000.0 NULL
4 Chaitali 25 Mumbai 6500.0 NULL
5 Hardik 27 Bhopal 8500.0 NULL

• Following is the example to DROP Gender column from existing table:


• ALTER TABLE CUSTOMERS DROP Gender; .
• Now, CUSTOMERS table is changed and following would be output from SELECT statement:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
5 Hardik 27 Bhopal 8500.0
To add a constraint, the table constraint syntax is used. For example:
ALTER TABLE products ADD CHECK (name <>’);
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product group id) REFERENCES product_groups;
To change a column to a different data type, use a command
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
To rename a table use following query:
ALTER TABLE products RENAME TO items;

 6. RENAME Command: 


RENAME command is used to rename a table.
 Syntax:
RENAME TABLE old-table-name to new-table-name ;
Example:
CREATE TABLE employees 
(id NUMBER(6), 
name VARCHAR(20)
);
• INSERT INTO employees( ID, Name ) values( 1, 'Amar’);
• INSERT INTO employees( ID, Name ) values( 2, 'Deepa’);
• INSERT INTO employees ( ID, Name ) values( 3, ‘Kiran’);
ID Name
SELECT * FROM employees; 
1 Amar

2 Deepa

3 Kiran

For renaming the table use following query:


RENAME TABLE employees to employees_new; 
SELECT * FROM employees new;

ID Name

1 Amar

2 Deepa

3 Kiran
• Data manipulation language (DML) commands:
• DML commands are used for manipulating data in database.
• DML commands are used for storing, retrieving, modifying, and deleting data.

Various DMI commands are explained below:


 1. INSERT INTO Command:
• The INSERT statement is used to add new rows (records) of data to a table in the database. 
Syntax:
INSERT INTO TABLE_NAME [(columni, column2, column3, ... columnN)]
VALUES (valuel, value2, value3, ...valueN); 
Here, column1, column2....columnN are the names of the columns in the table into which you want to
insert data.
•  You can populate data into a table through select statement over another table provided another table has
a set of fields, which are required to populate first table.
Here, is the syntax.
• INSERT INTO first table name [(column1, column2, ... columnN) SELECT column1, column2, ...columnN
FROM second_table_name [WHERE condition];
•  Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID, NAME, AGE,ADDRESS, SALARY) VALUES (1, 'Ramesh',
32, 'Ahmedabad', 2000.00 ); 

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (2, 'Khilan',
25, 'Delhi', 1500.00 );
 
INSERT INTO CUSTOMERS (ID, NAME, AGE,ADDRESS, SALARY) VALUES (3, 'kaushik',
23, 'Kota', 2000.00 );
 
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (4, 'Chaitali',
25, 'Mumbai', 6500.00 ); 

INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (5, 'Hardik',
27, 'Bhopal', 8500.00 ); 

INSERT INTO CUSTOMERS (ID, NAME, AGE,ADDRESS, SALARY)VALUES (6, 'Komal', 22, 'MP',
4500.00 ); 
• You can create a record in CUSTOMERS table using second syntax as follows:
INSERT INTO CUSTOMERS
VALUES (7, 'Amar', 24, 'Indore', 9500.00 );
• All the above statements would produce the following records in CUSTOMERS table:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
5 Hardik 27 Bhopal 8500.0
6 Komal 22 MP 4500.0
7 Amar 24 Indore 9500.0
2. UPDATE Command:
•  The UPDATE statement is used to modify the existing rows in a table. •
• We can use WHERE clause with UPDATE query to update selected rows otherwise all the
record would be affected.
• Syntax:
UPDATE table_name 
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
• Example: Consider the CUSTOMERS table having the following records:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
5 Hardik 27 Bhopal 8500.0
• Following is an example, which would update ADDRESS for a customer whose ID is 6:
• UPDATE CUSTOMERS 
SET ADDRESS = 'Pune’
WHERE ID = 5; 
• Now, CUSTOMERS table would have the following records:
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
5 Hardik 27 Pune 8500.0
• If we want to modify all ADDRESS and SALARY column values in CUSTOMERS table, we do
not need to use WHERE clause and UPDATE query would be as follows:
UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1200.00; 
• Now, CUSTOMERS table would have the following records:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Pune 1200.0
2 Khilan 25 Pune 1200.0
3 Kaushik 23 Pune 1200.0
4 Chaitali 25 Pune 1200.0
5 Hardik 27 Pune 1200.0
3. DELETE Command:
• The DELETE Statement is used to delete rows (records) from a table. 
• We can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would
be deleted. 
• Syntax:
DELETE FROM table_name
[WHERE condition];
Example: Consider Customer table having the following record:

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
5 Hardik 27 Bhopal 8500.0
Following is the example, which would DELETE a customer, whose ID is 6:
DELETE FROM Customer
WHERE ID=5;
Now Customer table would be :
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmednagar 2000.0
2 Khilan 25 Delhi 1500.0
3 Kaushik 23 Kota 2000.0
4 Chaitali 25 Mumbai 6500.0
If we want to DELETE all records from Customer table, we do not need to use WHERE clause and DELETE
query would be as follows:
DELETE FROM Customer;
Now Customer table not having any records.
Forms of basic SQL queries
• A Relational database consist of collection of relation, each of which is assigned a unique name.
• SQL allows the use of NULL values to indicate that the value is unknown or does not exist. For retrieving
record from table we use basic structure for data retrieval.
• This SQL expression consist of following three clauses:
SELECT<list of attributes>
FROM<table name>
WHERE<Condition>;
SQL forms the cartesian product of relation named in the FROM clause.

Simple SQL queries:


Lets consider relational database of banking system given below, Underline attribute are the primary key.
Branch(Branch_name,branch_city,assets)
Customer(cust_name,cust_street,cust_city)
• Loan(Loan_no,branch_name,amount)
• Account(acc_no,branch_name,balance)
• Borrower(cust_name,loan_no)
• Depositor(cust_name,acc_no)

• In above relations,
• Branch and loan : one to many
• Branch and account :one to many
• Customer and loan: many to many
• Customer and account: Many to many
• Therefor Borrower and depositor are the two tables created to show many to many.
• ER diagram for above schema:
Time
Acc_no Balance Br_Name Br_city

M Acc_ 1
Account Bran Branch Asset
ch
M 1

Dep
osito Loan
r _br

M M
M M
Borr
Customer Loan
ower
Cust_name

Loan_no Amount
Cust_city Cust_street
Relation=Loan
Relation=Borrower
Loan_no Branch_name amount CUST_NAME LOAN_NO
1 J M Road 200000 Umesh 1
2 J M Road 500000 Mugdha 3
3 F C Road 680000 Paresh 5
4 M G Road 520000 Rupali 2
5 G P Road 250000
Umesh 6
6 F C Road 100000
Rupali 7
7 F C Road 100000
Acc_no Branch_name balance
branch_name branch_city assets
112 G P Road 10000
J M Road Pune 100000
443 F C Road 5000
M G Road Pune 500000
553 G P Road 2000
F C Road Pune 200000
880 F C Road 15000
G P Road Nagpur 120000
998 M G Road 20000
Relation=Branch

Relation=Account
Cust_name Cust_city Cust_street Cust_name Acc_no
Sayali Nagpur G P Road Sayali 443
Umesh Pune J M Road Umesh 998
Mugdha Pune F C Road Rima 443
Nitin Pune F C Road Sayali 880
Rima Nagpur G P Road Paresh 112
Paresh Pune M G Road
Rupali Pune M G Road Relation=Depositor

Relation=customer
SELECT Clause
• The SELECT clause in SQL is used to retrieve or fetch data from a database.
Syntax:
SELECT columni, column2, ...
FROM table_name;
•  Here, columni, column2, ... are the field names of the table you want to select data from. If you
want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
•  Example: Find name of all branches in the loan relation: Branch_Name
SELECT branch_name J M Road
FROM loan; J M Road
• Here, is a terminator which shows the end of a query. F C Road
• The result of this query is shown in Fig. M G Road
G P Road
F C Road
F C Road
• It displays the duplicate values also. If we want to force the elimination of duplicate values, insert a
keyword DISTINCT before a field name. By default SQL takes a keyword ALL and that's why it displays all
the values.
• The DISTINCT keyword is used to return only distinct (different) values. Syntax:
SELECT DISTINCT column_names
FROM table_name;
• The example with distinct is as follows:
SELECT DISTINCT branch_name
FROM loan;
The result of this query is as shown in Fig.(b). Branch_Name

J M Road

F C Road

M G Road

G P Road
• SOL allows us to use the keyword ALL to specify explicitly that duplicates are not removed. The query is as
follows:
SELECT ALL branch_name
FROM loan;
• The result of this query is similar to the result depicted in Fig. (a).Find all the attributes in loan relation,
SELECT loan_no, branch_name, amount
FROM loan;
•  It displays the result depicted in Fig. (a). 
• When all the attributes from a table to be selected then in place of writing all the attribute names, a
symbol '*' (asterisk) can be placed. 
• So the above query can be written in the following format.
SELECT *
FROM loan;
•  It will display the same result like Fig. 3.6 (a).
• The SELECT clause can also contain an arithmetic expression which includes the following operators in it,
such as,
• Addition Subtraction Mod (to find remainder) Division Multiplication
• Raise to and Constants.
• Lets write some more queries using these operators.
• Find all the attributes in loan relation where interest on the amount is calculated as 3% of the amount. 
Query:
SELECT loan_no, branch_name, amount, amount * 0.03
FROM loan;
•  As we know the table has only three attributes, but we want to have result of amount * 0.03. 
• The result of this query is shown in Fig. Loan_no Branch_name amount Expr
1 J M Road 200000 6000
2 J M Road 500000 15000
3 F C Road 680000 20400
4 M G Road 520000 15600
5 G P Road 250000 7500
6 F C Road 100000 3000
7 F C Road 100000 3000
WHERE Clause
• It corresponds to select operation. This clause is used to define a predicate.
• While specifying predicate, SQL uses logical connectives AND, OR and NOT. SQL allows us to use the on
operator to compare strings and arithmetic expressions as well as data types. The available comparison
operators are < <= > >=,=0.
Syntax:
SELECT column1, column2…
FROM table_name
WHERE condition;
•  Let's write queries for WHERE clause.
•  Find all the loan numbers for loan made at FC Road branch with loan amount greater than 300000.
Query:
SELECT loan_no FROM loan;
WHERE branch_name = 'FC Road' AND amount > 300000; 
• It will select all loan numbers first from loan table and then apply predicate for branch_name and amount.
•  The result of the query is as shown in Fig.
Loan_no

3
• Find the loan number of those loans with loan amount between Rs. 200000 to 550000. Query:
SELECT loan_no FROM loan
WHERE amount > 200000 and amount < 550000; 
• The result is as shown in Fig. Loan_no
1
2
3
4
5

BETWEEN Operator:
• The range can be specified by relational operator. If we do not want to use these operators, the range can be
specified by a keyword BETWEEN. 
• This operator allows selecting range. So the above query can be rewritten as follows:
SELECT loan_no FROM loan
WHERE amount Between 200000 and 550000; 
The result is as shown in Fig.
FROM Clause 
• FROM clause itself defines a Cartesian product of a relation. This clause is also used to find natural  join of
more than one table.
• The SQL From clause is the source of a row set to be operated upon in a Data Manipulation language
(DML) statement 
Syntax:
SELECT * FROM table name
WHERE predicate; 
• Find all customers who have a loan from the bank, find their names and loan no
Query:
SELECT cust_name, loan.loan_no, borrower.loan_no
FROM loan, borrower; 
• The result will have Cartesian product of borrower and loan as shown in Fig
• For finding natural join, we have to provide the comparison using where clause. Now query will be as
follows:
SELECT cust_name, loan_no 
FROM loan, borrower
WHERE loan.loan_no = borrower.loan_no; 
• This will find cartesian product first and then natural join. The result of natural join is as shown in Fig.
Cust_name Loan_no
Umesh 1 Find names and loan numbers of all customer who have loan at FC
Rupali 2 Road branch.
 Query:
Mugdha 3
SELECT cust_name, loan.loan no 
Paresh 5
FROM Loan, Borrower 
Umesh 6 WHERE loan.loan_no = borrower.loan_no
Rupali 7 AND branch_name = 'FC Road';  Cust_name Loan_no
The result is depicted in the Fig.
Mugdha 3
Umesh 6
Rupali 7
Rename Operation
• SOL provides a mechanism for renaming both the relations and attribute.For this keyword AS is used. It
can appear in both SELECT and FROM clause.
• Let's consider previous query;suppose we want to change name of loan.loan_no to loan_id, the query is
rewritten as  follows: 
Query:
SELECT cust name, loan.loan no AS loan_id 
FROM loan, borrower
WHERE loan.loan no borrower.loan_no and branch name="FC Road”;
• The result of this query is similar to Fig. except  the name of attribute. This is depicted in fig:

Cust_name Loan_id
Mugdha 3
Umesh 6
Rupali 7
Change the relation name. 
• Find names of all branches that have assets greater than at least one branch located in pune, 
Query:
SELECT distinct T.branch_name 
FROM branch as T, branch as s
WHERE T.assets > S.assets
AND S.branch_city = 'Pune'
• Here, S and T are called as Tuple variables which are used to compare two records (tuples) in
the same relation. 
• The tuple variables are defined in the FROM clause. 
• In query we have used two tuple variables to Branch_name
compare the assets and attribute. F C Road
•  The result of this query is as depicted in Fig.
G P Road

M G Road

Fig. : Result of T.assets > S.assets and S.branch_city = 'pune’


• If we do a single change in the previous query, the result is as shown in Fig.
SELECT distinct T.branch_name 
FROM branch T, branch
WHERE T.assets > S.assets AND T.branch_city = 'Pune';
Fig. Result of T.branch city = 'Pune’ Branch_Name

F C Road

M G Road

ORDER BY Clause:
•  The ORDER BY clause is used to sort the data in ascending or descending order, based on one or more
columns. Some database sorts query results in ascending order by default.
Syntax:
SELECT column-list 
FROM table_name
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
• You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to
sort, that column should be in column-list.
•  Example: Consider the CUSTOMERS table having the following records:
id | name | age | address | salary
-----+----------+-----+---------------------------+---------
101 | Ramesh | 32 | Ahamadnagar | 2000.00
102 | Keshav | 25 | Delhi | 1500.00
103 | Kaushik | 23 | Kota | 2000.00
104 | Chaitali | 25 | Mumbai | 6500.00
105 | Hardik | 27 | Bhopal | 8500.00
106 | Harsh | 47 | Beed | 7500.00
107 | Akash | 37 | Pune | 7500.00
45 | Aarati | 37 | Pune | 7500.00
Following is an example, which would sort the result in ascending order by NAME and SALARY:
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY; 
• Output:
• id | name | age | address | salary
• -----+----------+-----+---------------------------+---------
• 45 | Aarati | 37 | Pune | 7500.00
• 107 | Akash | 37 | Pune | 7500.00
• 104 | Chaitali | 25 | Mumbai | 6500.00
• 105 | Hardik | 27 | Bhopal | 8500.00
• 106 | Harsh | 47 | Beed | 7500.00
• 103 | Kaushik | 23 | Kota | 2000.00
• 102 | Keshav | 25 | Delhi | 1500.00
• 101 | Ramesh | 32 | Ahamadnagar | 2000.00
• Following is an example, which would sort the result in descending order by NAME:
SELECT * FROM CUSTOMERS
ORDER BY NAME DESC; 
• Output:
id | name | age | address | salary
-----+----------+-----+---------------------------+---------
101 | Ramesh | 32 | Ahamadnagar | 2000.00
102 | Keshav | 25 | Delhi | 1500.00
103 | Kaushik | 23 | Kota | 2000.00
106 | Harsh | 47 | Beed | 7500.00
105 | Hardik | 27 | Bhopal | 8500.00
104 | Chaitali | 25 | Mumbai | 6500.00
107 | Akash | 37 | Pune | 7500.00
45 | Aarati | 37 | Pune | 7500.00
String Operations 
• Database consists of some string values. The most commonly used operation on string is
pattern matching. The operator used for pattern matching is LIKE. the patterns are case
sensitive, i.e. uppercase characters or vice versa.
With the keyword LIKE, we can use two characters:
1. Percent (%): It matches with any substring. It means that % stands for more number of
character.
2. Underscore(_) :It matches with any single character. It means stands for one character
only.

Consider the following example:


 1. "mad%": It matches with any any string which begins with "mad". It may have
characters after “mad”.For example: madhav, madhuri, madam, madhura etc.

2. "%mi%": It matches any string containing "mi" in it. The result may have character
before and after it.For example: amit, Sumit, Ashmit, Tasmit etc. 
3. “---": matches with any string which has exactly 3 characters in it.
• For example: jam, Ram, mat etc. 

4.”_a_”:It matches with any string which has exactly 3 characters and the middle
character is “a”. For example: Ram, bat, mat etc.
Let's write queries for string operation. 
• Select the row from branch table whose branch name starts with letter "M".
Query:
SELECT * FROM branch
WHERE branch_name like 'M%'; 
• The result of this query is shown in Fig.
Branch_name Branch_city Asset
M G Road Pune 500000
• Select tuples from customer table whose name of customer has a character 'e' at third position.
 Query:
SELECT * FROM CUSTOMER
WHERE cust_name like "- - e%"
•  The result is depicted in Fig.

cust_name cust_city Cust_street


Umesh Pune J M Road

• Find names of all customers whose street address includes the substring 'FC’.
Query:
SELECT cust_name FROM customer
WHERE cust-street like '%FC%"; 
Cust_name
Mugdha
Nitin
SET OPERATIONS 
• SQL supports few set operations to be performed on table data. These are used to get
meaningful results from data under different special conditions. 
• Set operators combine the results of two or more component queries into one result.
• Queries containing set operators are called compound queries. 
Fig. shows set operators used in set operations

1. UNION Operator:
•  The UNION operator returns all rows that are selected by either query. Use the UNION
operator to return all rows from multiple tables and eliminate any duplicate rows.

 2. UNION ALL Operator: Use the UNION ALL operator to return all rows from multiple
queries.
3. INTERSECT Operator: 
Use the INTERSECT operator to return all rows that are common to multiple queries.

4. MINUS Operator: Use the MINUS operator to return all distinct rows selected by the
first query,but not present in the second query result set (the first SELECT statement
MINUS the second SELECT statement).
 1. UNION Operation:
It is used to combine the results of two or more Select statements.However, it will
eliminate duplicate rows from its result set. In case of union, number of columns and
datatype must be same in both the tables. 
Syntax:
SELECT field1, field2, .. field n
 FORM tables 
UNION 
SELECT field1, field2, ..field_n
FORM tables; 
Union Select query will be
SELECT * FROM First
UNION
SELECT * FROM Second

2. UNION ALL Operation: 


This operation is similar to Union. But it also shows the duplicate rows.
Syntax:
SELECT field1, field2, ..field n FROM tables 
UNION ALL
SELECT field1, Field2, ..field n 
FROM tables 

Example: Take following two tables Union All query will be like:
SELECT * FROM First 
UNION ALL
SELECT * FROM Second;
INTERSECT Operation: 
• Intersect operation is used to combine two SELECT statements, but it only retuns the records which are
common from both SELECT statements. In case of Intersect the number of columns and datatype must be
same.
Syntax:
SELECT field1, field2, ..field_n FROM tables 
INTERSECT
SELECT field1, field2, .. field_n FROM tables;

Intersect query will be like:


SELECT * FROM First 
INTERSECT
SELECT * FROM Second; 
MINUS Operation: 
• MINUS operation combines re belongs to first set of result of two SELECT statements and return only those
result which belongs to first set of result.
Syntax:
SELECT fieldi, field2, ..., field n
FROM tables
 [WHERE conditions]
 MINUS 
SELECT field1, field2, ...., field n
 FROM tables 
[WHERE conditions];

SELECT * FROM First


 MINUS
SELECT * FROM Second;
4. INTERSECT ALL Operation: 
The INTERSECT ALL is equal to the INTERSECT command, except that INTERSECT ALL selects all
repeated values. 
Syntax:
SELECT field, field2, .. field_n FROM tables 
INTERSECT ALL
SELECT field, field2, ..field_n FROM tables; 

INTERSECT ALL query look like:


SELECT f_name FROM EMP_Pune 
INTERSECT ALL
 SELECT f_name FROM EMP_Satara;
AGGREGATE OPERATORS AND FUNCTIONS
1 Aggregate Functions
• Aggregate means to sum. So actually aggregate function works on the whole database. These
functions take a collection of values as inputs and return a single value. SQL offers 5 built-in
aggregate functions:
 1. avg: This function returns Average value.
 2. min: This function returns minimum value. 
3. max: This function returns maximum value. 
4. sum: This function returns sum of numeric value. 
5. count: This function returns the total number of values.

These operations are called aggregate functions because they operate on  on aggregates of
tuples.
 The result of aggregate function is a single value. 
The input to sum and avg must be a collection of numbers but the other  operation can operate on
collection of non-numeric datatypes such as string.
•  Find average amount balance of FC Road branch.
Query:
SELECT avg (balance)
FROM account
WHERE branch_name = 'FC Road'; 

Find total account balance in MG Road branch 


Query: 
SELECT sum(balance)
FROM account
WHERE branch_name = 'MG Road'; 

All the balance value of FC Road are added and divided by the total number of values for FC
Road.

Sometimes, we have to apply aggregate function not only to a single tuple but for set of tuples.
This is specified using GROUP BY clause.
Aggregate Operators (GROUP BY and HAVING) 

1. HAVING Clause:
The HAVING clause enables you to specify conditions that filter which group results appear in the final results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause. 
Syntax:
 The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY
clause if used. The following is the syntax of the SELECT statement, including the HAVING clause:

SELECT column1, column2


FROM table1, table2
WHERE ( conditions ]
GROUP BY column1, column 2
HAVING [conditions ]
ORDER BY column1, column 2 

 Example: Consider the CUSTOMERS table having the following records:


• Following is the example, which would display record for which similar age count would be more than or
equal to 2:
SELECT ID, NAME, AGE, ADDRESS, SALARY 
FROM CUSTOMERS 
GROUP BY age
HAVING COUNT (age) >= 2;

2. GROUP BY Clause:
• The GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into
groups. The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause. 
Syntax:
The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER  BY
clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
•  If you want to know the total amount of salary on each customer, then GROUP BY query would be as
follows:
SELECT NAME, SUM( SALARY) 
FROM CUSTOMERS
GROUP BY NAME; 
• Now, let us have following table where CUSTOMERS table has the following records with duplicate names:
•  Now again if you want to know the total amount of salary on each customer, then GROUP BY query would
be as follows:
SELECT NAME, SUM( SALARY)
FROM CUSTOMERS
GROUP BY NAME;
DATE AND STRING FUNCTIONS
•  Date Functions
• SQL provides a number of functions that return values related to the current date and time. 
SELECT NOW();
function shows function returns current date and time based on the database server's time zone setting.

 CURRENT_DATE:
SELECT CURRENT_DATE;
Result: 2019-08-23 

CURRENT_TIME.
SELECT CURRENT_TIME;
Result: 14:39:53.662522-05 

The TO DATE function is used to converting strings into dates. 


Syntax: TO_DATE(text, text) and the return type is date.

Examples: 
27/08/2019 TO_DATE(date, 'DD/MM/YYYY’)
 27-08-2019 TO_DATE(date, ‘DD-MM-YYYY’) 
08272019 TO_DATE(date, 'MMDDYY') 
August 25, 2019 TO_DATE(date, 'Month DD’,’ YYYY’)
The TO_TIMESTAMP() function converts string data into timestamps with timezone. 
Syntax: to_timestamp (text, text). 
AGE(timestamp, timestamp) function will Subtract arguments, producing a "symbolic" result
that uses years and months 
AGE(timestamp '2001-04-10', timestamp '1957-06-13')
Result:
43 years 9 mons 27 days 
age(timestamp) function subtract from current_date (at midnight).
For example:
AGE(timestamp '1990-06-13’).

date_part(text, timestamp) function get subfield (equivalent to extract).


For example:
date_part('hour', timestamp '2019-02-16 20:38:40')
Result: 20 

date_trunc(text, timestamp) function truncate to specified precision.


For example: date_trunc("hour', timestamp '2019-02-16 20:38:40')
Result: 20019-02-16 20:00:00 3.8.2 
String Functions 
• SQL provides functions and operators for examining and manipulating string values. Strings in this context
include values of the types character, character varying, and text. 
• The most commonly used PostgreSQL string functions that allow you to manipulate string data effectively. 
NULL VALUES
• NULLs are the special markers by using which SQL systems represent missing information. For example, if
we say that the weight of a person is null. Then it means that, the person is exist live otherwise he or she
does not have it. But we do not known how much it is.
• In other words we do not know the actual weight of that person which we can sensibly placed weight
column. 
• Therefore, we mark it as NULL. Using NULL keyword we clear a point to the database that not a value and
not blank or zero at the same time.
• The representation of NULL is implementation dependent. But SQL standard specify that we should have
a representation where null and not null values are distinguishable. 
• Definition of NULL: A NULL value is an implementation dependent special value which is usual from all
null values and there is effectively one and only one value. In general, if we do not explicitly specify a
column as NOT NULL, the column has nulls. If a column is allowed to contain nulls then RDBMS
automatically places a null into that column . 
• This is possibly done by RDBMS in the situation where a row is inserted into a table and no values are
specified for that column. 
• Similarly, if we write NOT NULL for a particular column name then we are not allowed the update a
column again. If we use a option "NOT NULL WITH DEFAULT", then it means that the column can contain
nulls. Still it is possible to omit the values for the column during INSERT or UPDATE. 
If we insert a row and no values are specified for that column then the RDBMS will insert one of the
default given below: 
1. Zero if a numeric column.
 2. Blank if a fixed-length string column.
3. Empty if a varying length column. 
 The INSERT command is used to insert a value given for every attribute. Lets write a query using
null values. 
Insert a tuple into Custom table without Salary. 

Query:
INSERT INTO CUSTOMER
VALUES (6, 'Komal' 22, 'MP' ,NULL); 
It will insert the value in the Customer table with NULL as salary.

Now, following is the usage of IS NOT NULL operator:


SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS
WHERE SALARY IS NOT NULL;
• Now, following is the usage of IS NULL operator:
SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS
WHERE SALARY IS NULL; 
Logical Connectives AND, OR and NOT
• Generally, to connect or compare logical conditions we use AND, OR and NOT keywords. 
• But once we have null values, we must define these logical operators using a three-valued logic,
where the expression is evaluated as true, false or unknown.
 For example:
SELECT cust_name FROM customer, account
WHERE cust_name = 'Sayali’
AND acc_no < 1000; 
In this case both conditions should be true then only the result of AND is true. Similarly, for OR any
one condition has to true then only result is true else it is false.
Impact on SQL Constructs
•  When we use Boolean expression in SQL then the impact of null values must be recognized. To
check this impact on nested queries we use keyword EXISTS or UNIQUE. 
• The arithmetic operators +, -, *, / returns null if any one argument is null. Similarly, null cause the
problems with aggregate function such as COUNT, SUM, AVG, MIM, MAX etc.
• Even comparison of two null values give a unknown result.

Disallowing NULL Values


• We can  disallow null values by specifying NOT NULL while defining the column in table.
• A field which have a null value should not be considered as a primary key.
For example:
rollno char (20) NOT NULL; 
NESTED SUB QUERIES
• A query within a query is called nested query. Sometimes, it is referred as nested sub-query. A Sub-query 
 is a SELECT-FROM-WHERE expression that is nested within another query.
•  Sub query can be defined as "a query within query”. A sub-query can use values from the outer query  in
which case it is known as a correlated sub-query.
•  A sub-query or inner query or nested query is a query within another SQL query an within the WHERE
clause.
• Sub-query is used to return data that will be used in the main query as  a condition to further restrict the data to be
retrieved. 
• Sub query can be used with the SELECT, INSERT. UPDATE. and DELETE statements along with the operator like
=,<,>,<=,>=, IN, Between etc.

Sub query with the SELECT Statement: 


• Sub-queries are most frequently used with the SELECT statement. The basic syntax is as follows:
SELECT column_name [,column_name] 
FROM table1 [, table2 ] 
WHERE column_name OPERATOR 
( SELECT column_name [, column_name] 
FROM table1 [, table2 ]
[WHERE] );
• Now, let us check following sub-query with SELECT statement:

SELECT * 
FROM CUSTOMERS 
WHERE ID IN (SELECT ID
  FROM CUSTOMERS 
WHERE SALARY > 4000);
Sub-queries with the INSERT Statement: 
• Sub-queries also can be used with INSERT statements. The INSERT statement uses the data returned from
the subquery to insert into another table. The selected data in the sub-query can be modified with any of the
character, date or number functions. 
• The basic syntax is as follows:
INSERT INTO table_name [ (column1 [, column2 ]) ] 
SELECT * / [ column1 [, column2 ]
FROM table1 [, table2 ] 
[ WHERE VALUE OPERATOR ]

Example:
CSTOMERS_BKP with similar structure as CUSTOMERS
• Consider a table CUSTOMERS BKP with similar structure as CUSTOMERS  table. Now to copy complete
CUSTORMER table into CUSTOMERS_BKP, following is the syntax:
INSERT INTO CUSTOMERS_BKP 
SELECT * FROM CUSTOMERS 
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ; 
Sub-queries with the UPDATE Statement:
The sub-query can be used in conjunction with the UPDATE statement. Either single or multiple columns in a
table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows:
UPDATE table 
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME 
FROM TABLE_NAME)
( WHERE) ]
Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
• Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose . AGE
is greater than or equal to 27:
UPDATE CUSTOMERS 
SET SALARY = SALARY * 0.25 
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
• This would impact two rows and finally CUSTOMERS table would have the following records:
Sub-queries  with the DELETE Statement:
The sub query can be used in conjunction with the DELETE statement like with any other statement mentioned above.
The basic syntax is as follows:
 DELETE FROM table_name
WHERE OPERATOR ( VALUE )
(SELECT COLUMN_NAME 
FROM TABLE_NAME
[ WHERE] );

 Example:
• Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. following example
deletes records from CUSTOMERS table for all the customers whose AGE is greater than or equal to 27:
DELETE FROM CUSTOMERS
  WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE > 27 ); 

This would impact two rows and finally CUSTOMERS table would have the following records:
SQL MECHANISMS FOR JOINING RELATIONS
• PostgreSQL JOINS are used to retrieve data from multiple tables. A PostgreSQL JOIN is performed whenever two or more tables are joined in a
SQL statement. 
There are different types of PostgreSQL joins:
1. INNER JOIN (or sometimes called simple join). 
2. LEFT OUTER JOIN (or sometimes called LEFT JOIN). 
3. RIGHT OUTER JOIN (or sometimes called RIGHT JOIN).
4. FULL OUTER JOIN (or sometimes called FULL JOIN). 

INNER JOIN (Simple Join)


The INNER JOIN selects all rows from both participating tables as long as there is a match between the columns. An SQL INNER JOIN is same as
JOIN clause, combining rows from two or more tables. 
Syntax:
SELECT * FROM table1 
INNER JOIN table2 
ON table1.column_name = table2.column_name;
OR 
SELECT * FROM table1 
JOIN table2
ON table1.column name = table2.column_name; 

 JOIN returns all rows from tables where the key record of one table is equal to the key records of another table.
• The INNER JOIN selects all rows from both participating tables as long as there is a match between the
columns. The SOL INNER JOIN is same as JOIN clause, combining rows from two or more tables.
• An inner join of table1 and table2 gives the result of table1 intersect table2, i.e. the inner part of a Venn
diagram intersection. 

OUTER JOIN
• The important variant of join operation which relies on null values, called outer joins. 
•  If we want outer join there we can write a query as follows:
SELECT cust_name, loan loan_no
• FROM LOAN NATURAL LEFT OUTER JOIN BORROWER; 
• IN LEFT OUTER JOIN. loan rows are appeared into a result where the loan rows are not matched with
borrowers rows. 
• But not vice versa. In RIGHT OUTER JOIN, borrower rows are appeared into a result with matching with
loan table. 
• In FULL OUTER JOIN, both the rows appeared in the result without a match. 
FULL OUTER JOIN
• This is a type of OUTER JOIN is called a FULL OUTER JOIN. This type of join returns all rows from the
LEFT-hand table and RIGHT-hand table with nulls in place where the join condition is not met.
 Syntax:
SELECT columns 
FROM table1
  FULL OUTER JOIN table2
ON table1.column = table2.column; 
In this FULL OUTER JOIN diagram, the SQL returns the shaded area.
LEFT OUTER JOIN 
• Another type of outer join is called a LEFT OUTER JOIN. This type of join returns all rows from the LEFT-
hand table specified in the ON condition and only those rows from the other table where the joined fields are
equal (join condition is met).
 Syntax:
SELECT columns 
FROM table1
  LEFT OUTER JOIN table2
ON table1.column = table2.column; 

In this LEFT OUTER JOIN diagram, the SQL returns the shaded area .

LEFT OUTER JOIN


• The LEFT OUTER JOIN would return the all records from table1 and only those records from table2 that
intersect with table1.
RIGHT OUTER JOIN 
• Another type of outer join is called the RIGHT OUTER JOIN. This type of join returns all rows RIGHT-hand
table specified in the ON condition and only those rows from the other table where the joined fields are
equal join condition is met).

Syntax:
SELECT Columns 
FROM table1
 RIGHT OUTER JOIN table2
 ON table1.column = table2.column;

In this diagram, The RIGHT OUTER JOIN returns the shaded area.

The RIGHT OUTER JOIN would return the all records from table2 and only those records from table1 that intersect with table2.
VIEWS
• A view is named query that provides another way to present data in the database tables. A view
is defined based on one or more tables, which are known as base tables.
•  When you create a view, we basically create a query and assign it a name, therefore a view is
useful for wrapping a commonly used complex query. Note that a normal view does not store any
data except the materialized view.
• We can manage views such as creating, modifying, and removing views from the database. 

Creating Views 
• To create a view, we use CREATE VIEW statement. The simplest syntax of the CREATE VIEW
statement is as follows:
CREATE VIEW view_name AS query;
For example: CREATE VIEW Cust AS Select * from Customer where cust_city='Pune';
• Whenever, you need to get a complete customer data, you just query it from the view by
executing the following simple SELECT statement.
SELECT cust_name 
FROM Cust
Where cust_street ='M G Road'; 
Changing Views Query
• To when the defining query of a view, you use the CREATE VIEW statement with
OR REPLACE addition as follows:
CREATE OR REPLACE view_name AS query;
For example: 
• CREATE VIEW Cust AS SELECT cust_name, cust_city FROM Customer ; 

 Modifying Views
• To change the definition of a view, we can use the ALTER VIEW statement 

For example:
You can change the name of the view from cust to custdata.
ALTER VIEW Cust RENAME TO CustData;
Removing Views:
• SQL allows us to delete an existing View. We can delete or drop a View
using the DROP statement.
• Syntax: DROP VIEW[if exists] view_name
• To remove an existing view in postgresSQL, you can use DROP VIEW
statement as follows:
DROP VIEW CustData;
Or
DROP VIEW IFEXISTS CustData;
postgres=# Select * from project;
pno | p_name | ptype | duration
-----+--------------------------------+----------------------+----------
1 | System | Computer | 4
2 | Robotics | Economic | 6
3 | Mechanical | Engineering | 8 postgres=# select * from emp_proj;
eno | pno | start_date | no_of_work_hr
-----+-----+------------+---------------
101 | 1 | 2020-02-04 | 30
102 | 2 | 2020-05-02 | 40
102 | 2 | 2019-05-12 | 50
postgres=# Select * from emp; 103 | 3 | 2019-05-03 | 50
eno | e_name | qualification | joindate
101 | 2 | 2016-04-05 |
-----+----------------------+-----------------+------------
101 | Mr.Patil | M.Sc | 2019-04-09
102 | Mr.Mane | M.Com | 2019-05-10
103 | Mr.Pandit | M.A | 2020-05-15

You might also like