Ch-3 SQL
Ch-3 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.
• 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.
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.
• '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
2 Deepa
3 Kiran
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.
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:
• 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
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.
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.
• 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
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;
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';
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:
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
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’).
Query:
INSERT INTO CUSTOMER
VALUES (6, 'Komal' 22, 'MP' ,NULL);
It will insert the value in the Customer table with NULL as salary.
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).
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 .
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