0% found this document useful (0 votes)
16 views24 pages

Unit-2

The document provides an overview of the Relational Model and SQL, detailing concepts such as attributes, tables, tuples, and integrity constraints. It discusses operations like insert, update, delete, and select, as well as best practices, advantages, and disadvantages of the relational database model. Additionally, it covers Data Definition Language (DDL) commands for managing database structures.

Uploaded by

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

Unit-2

The document provides an overview of the Relational Model and SQL, detailing concepts such as attributes, tables, tuples, and integrity constraints. It discusses operations like insert, update, delete, and select, as well as best practices, advantages, and disadvantages of the relational database model. Additionally, it covers Data Definition Language (DDL) commands for managing database structures.

Uploaded by

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

UNIT II RELATIONAL MODEL AND SQL 10

Relational model concepts -- Integrity constraints -- SQL Data manipulation


– SQL Data definition – Views -- SQL programming.

WHAT IS RELATIONAL MODEL?


Relational Model (RM) represents the database as a collection of relations. A
relation is nothing but a table of values. Every row in the table represents a
collection of related data values. These rows in the table denote a real-world entity
or relationship.
The table name and column names are helpful to interpret the meaning of values
in each row. The data are represented as a set of relations. In the relational model,
data are stored as tables. However, the physical storage of the data is independent
of the way the data are logically organized.
Some popular Relational Database management systems are:
 DB2 and Informix Dynamic Server – IBM
 Oracle and RDB – Oracle
 SQL Server and Access – Microsoft
In this tutorial, you will learn
 Relational Model Concepts in DBMS
 Relational Integrity Constraints
 Operations in Relational Model
 Best Practices for creating a Relational Model
 Advantages of Relational Database Model
 Disadvantages of Relational Model

Relational Model Concepts in DBMS


1. Attribute: Each column in a Table. Attributes are the properties which
define a relation. e.g., Student_Rollno, NAME,etc.
2. Tables – In the Relational model the, relations are saved in the table
format. It is stored along with its entities. A table has two properties rows
and columns. Rows represent records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single
record.
4. Relation Schema: A relation schema represents the name of the relation
with its attributes.
5. Degree: The total number of attributes which in the relation is called the
degree of the relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the
RDBMS system. Relation instances never have duplicate tuples.
9. Relation key – Every row has one, two or multiple attributes, which is
called relation key.
10. Attribute domain – Every attribute has some pre-defined value and scope
which is known as attribute domain

RELATIONAL INTEGRITY CONSTRAINTS


Relational Integrity constraints in DBMS are referred to conditions which must
be present for a valid relation. These Relational constraints in DBMS are
derived from the rules in the mini-world that the database represents.
There are many types of Integrity Constraints in DBMS. Constraints on the
Relational database management system is mostly divided into three main
categories are:
1. Domain Constraints
2. Key Constraints
3. Referential Integrity Constraints
Domain Constraints
Domain constraints can be violated if an attribute value is not appearing in the
corresponding domain or it is not of the appropriate data type.
Domain constraints specify that within each tuple, and the value of each
attribute must be unique. This is specified as data types which include standard
data types integers, real numbers, characters, Booleans, variable length strings,
etc.
Example:
Create DOMAIN CustomerName
CHECK (value not NULL)

The example shown demonstrates creating a domain constraint such that


CustomerName is not NULL
Key Constraints
An attribute that can uniquely identify a tuple in a relation is called the key of
the table. The value of the attribute for different tuples in the relation has to be
unique.
Example:
In the given table, CustomerID is a key attribute of Customer Table. It is most
likely to have a single key for one customer, CustomerID =1 is only for the
CustomerName =” Google”.
CustomerID CustomerName Status
1 Google Active
2 Amazon Active
3 Apple Inactive
Referential Integrity Constraints
Referential Integrity constraints in DBMS are based on the concept of Foreign
Keys. A foreign key is an important attribute of a relation which should be
referred to in other relationships. Referential integrity constraint state happens
where relation refers to a key attribute of a different or same relation. However,
that key element must exist in the table.
Example:

In the above example, we have 2 relations, Customer and Billing.


Tuple for CustomerID =1 is referenced twice in the relation Billing. So we
know CustomerName=Google has billing amount $300
Operations in Relational Model
Four basic update operations performed on relational database model are
Insert, update, delete and select.
 Insert is used to insert data into the relation
 Delete is used to delete tuples from the table.
 Modify allows you to change the values of some attributes in existing
tuples.
 Select allows you to choose a specific range of data.

Whenever one of these operations are applied, integrity constraints specified on


the relational database schema must never be violated.
Insert Operation
The insert operation gives values of the attribute for a new tuple which should
be inserted into a relation.

Update Operation
You can see that in the below-given relation table CustomerName= ‘Apple’ is
updated from Inactive to Active.

Delete Operation
To specify deletion, a condition on the attributes of the relation selects the tuple
to be deleted.

In the above-given example, CustomerName= “Apple” is deleted from the table.


The Delete operation could violate referential integrity if the tuple which is
deleted is referenced by foreign keys from other tuples in the same database.
Select Operation

In the above-given example, CustomerName=”Amazon” is selected


Best Practices for creating a Relational Model
 Data need to be represented as a collection of relations
 Each relation should be depicted clearly in the table
 Rows should contain data about instances of an entity
 Columns must contain data about attributes of the entity
 Cells of the table should hold a single value
 Each column should be given a unique name
 No two rows can be identical
 The values of an attribute should be from the same domain
Advantages of Relational Database Model
 Simplicity: A Relational data model in DBMS is simpler than the
hierarchical and network model.
 Structural Independence: The relational database is only concerned with
data and not with a structure. This can improve the performance of the
model.
 Easy to use: The Relational model in DBMS is easy as tables consisting
of rows and columns are quite natural and simple to understand
 Query capability: It makes possible for a high-level query language like
SQL to avoid complex database navigation.
 Data independence: The Structure of Relational database can be changed
without having to change any application.
 Scalable: Regarding a number of records, or rows, and the number of
fields, a database should be enlarged to enhance its usability.
Disadvantages of Relational Model
 Few relational databases have limits on field lengths which can’t be
exceeded.
 Relational databases can sometimes become complex as the amount of
data grows, and the relations between pieces of data become more
complicated.
 Complex relational database systems may lead to isolated databases
where the information cannot be shared from one system to another.
Summary
 The Relational database modelling represents the database as a collection
of relations (tables)
 Attribute, Tables, Tuple, Relation Schema, Degree, Cardinality, Column,
Relation instance, are some important components of Relational Model
 Relational Integrity constraints are referred to conditions which must be
present for a valid Relation approach in DBMS
 Domain constraints can be violated if an attribute value is not appearing
in the corresponding domain or it is not of the appropriate data type
 Insert, Select, Modify and Delete are the operations performed in
Relational Model constraints
 The relational database is only concerned with data and not with a
structure which can improve the performance of the model
 Advantages of Relational model in DBMS are simplicity, structural
independence, ease of use, query capability, data independence,
scalability, etc.
 Few relational databases have limits on field lengths which can’t be
exceeded.

RELATIONAL MODEL CONCEPT


Relational model can represent as a table with columns and rows. Each row is
known as a tuple. Each table of the column has a name or attribute.
Domain: It contains a set of atomic values that an attribute can take.
Attribute: It contains the name of a column in a particular table. Each attribute
Ai must have a domain, dom(Ai)
Relational instance: In the relational database system, the relational instance is
represented by a finite set of tuples. Relation instances do not have duplicate
tuples.
Relational schema: A relational schema contains the name of the relation and
name of all columns or attributes.
Relational key: In the relational key, each row has one or more attributes. It
can identify the row in the relation uniquely.
Example: STUDENT Relation
NAME ROLL_NO PHONE_NO ADDRESS AGE
Ram 14795 7305758992 Noida 24
Shyam 12839 9026288936 Delhi 35
Laxman 33289 8583287182 Gurugram 20
Mahesh 27857 7086819134 Ghaziabad 27
Ganesh 17282 9028 9i3988 Delhi 40
 In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and
AGE are the attributes.
 The instance of schema STUDENT has 5 tuples.
 t3 = <Laxman, 33289, 8583287182, Gurugram, 20>

Properties of Relations
 Name of the relation is distinct from all other relations.
 Each relation cell contains exactly one atomic (single) value
 Each attribute contains a distinct name
 Attribute domain has no significance
 tuple has no duplicate value
 Order of tuple can have a different sequence
INTEGRITY CONSTRAINTS
 Integrity constraints are a set of rules. It is used to maintain the quality of
information.
 Integrity constraints ensure that the data insertion, updating, and other
processes have to be performed in such a way that data integrity is not
affected.
 Thus, integrity constraint is used to guard against accidental damage to
the database.
Types of Integrity Constraint

1. Domain constraints
 Domain constraints can be defined as the definition of a valid set of
values for an attribute.
 The data type of domain includes string, character, integer, time, date,
currency, etc. The value of the attribute must be available in the
corresponding domain.
Example:

2. Entity integrity constraints


 The entity integrity constraint states that primary key value can't be null.
 This is because the primary key value is used to identify individual rows
in relation and if the primary key has a null value, then we can't identify
those rows.
 A table can contain a null value other than the primary key field.
Example:

3. Referential Integrity Constraints


 A referential integrity constraint is specified between two tables.
 In the Referential integrity constraints, if a foreign key in Table 1 refers
to the Primary Key of Table 2, then every value of the Foreign Key in
Table 1 must be null or be available in Table 2.
Example:

4. Key constraints
 Keys are the entity set that is used to identify an entity within its entity set
uniquely.
 An entity set can have multiple keys, but out of which one key will be the
primary key. A primary key can contain a unique and null value in the
relational table.

Example:

Introduction to DDL
 DDL stands for Data Definition Language.
 It is a language used for defining and modifying the data and its structure.
 It is used to build and modify the structure of your tables and other
objects in the database.
DDL commands are as follows,
1. CREATE
2. DROP
3. ALTER
4. RENAME
5. TRUNCATE
 These commands can be used to add, remove or modify tables within a
database.
 DDL has pre-defined syntax for describing the data.

1. CREATE COMMAND
 CREATE command is used for creating objects in the database.
 It creates a new table.
Syntax:
CREATE TABLE <table_name>
( column_name1 datatype,
column_name2 datatype,
.
.
.
column_name_n datatype
);
Example : CREATE command
CREATE TABLE employee
(
empid INT,
ename CHAR,
age INT,
city CHAR(25),
phone_no VARCHAR(20)
);

2. DROP COMMAND
 DROP command allows to remove entire database objects from the
database.
 It removes entire data structure from the database.
 It deletes a table, index or view.

Syntax:
DROP TABLE <table_name>;
OR
DROP DATABASE <database_name>;
Example : DROP Command
DROP TABLE employee;
OR
DROP DATABASE employees;

 If you want to remove individual records, then use DELETE command of


the DML statement.

3. ALTER COMMAND
 An ALTER command allows to alter or modify the structure of the
database.
 It modifies an existing database object.
 Using this command, you can add additional column, drop existing
column and even change the data type of columns.
Syntax:
ALTER TABLE <table_name>
ADD <column_name datatype>;

OR

ALTER TABLE <table_name>


CHANGE <old_column_name> <new_column_name>;

OR

ALTER TABLE <table_name>


DROP COLUMN <column_name>;
Example : ALTER Command
ALTER TABLE employee
ADD (address varchar2(50));

OR

ALTER TABLE employee


CHANGE (phone_no) (contact_no);

OR

ALTER TABLE employee


DROP COLUMN age;
To view the changed structure of table, use 'DESCRIBE' command.
For example:
DESCRIBE TABLE employee;

4. RENAME COMMAND
 RENAME command is used to rename an object.
 It renames a database table.
Syntax:
RENAME TABLE <old_name> TO <new_name>;

Example:
RENAME TABLE emp TO employee;

5. TRUNCATE COMMAND
 TRUNCATE command is used to delete all the rows from the table
permanently.
 It removes all the records from a table, including all spaces allocated for
the records.
 This command is same as DELETE command, but TRUNCATE
command does not generate any rollback data.
Syntax:
TRUNCATE TABLE <table_name>;

Example:
TRUNCATE TABLE employee;
SQL COMMANDS
 SQL commands are instructions. It is used to communicate with the database. It is
also used to perform specific tasks, functions, and queries of data.
 SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL)


 DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
 All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
Here are some commands that come under DDL:
 CREATE
 ALTER
 DROP
 TRUNCATE

a. CREATE It is used to create a new table in the database.


Syntax:
1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,. .. ]);
Example:
1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100),
DOB DATE);
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
1. DROP TABLE table_name;
Example
1. DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be
either to modify the characteristics of an existing attribute or probably to add a
new attribute.
Syntax:
To add a new column in the table
1. ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify existing column in the table:
1. ALTER TABLE table_name MODIFY(column_definitions. .. );
EXAMPLE
1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.
Syntax:
1. TRUNCATE TABLE table_name;
Example:
1. TRUNCATE TABLE EMPLOYEE;

2. DATA MANIPULATION LANGUAGE


 DML commands are used to modify the database. It is responsible for all form of
changes in the database.
 The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.
Here are some commands that come under DML:
 INSERT
 UPDATE
 DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data


into the row of a table.
Syntax:
1. INSERT INTO TABLE_NAME
2. (col1, col2, col3,. ... col N)
3. VALUES (value1, value2, value3, ..... valueN);
Or
1. INSERT INTO TABLE_NAME
2. VALUES (value1, value2, value3, ..... valueN);
For example:
1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");
b. UPDATE: This command is used to update or modify the value of a column
in the table.
Syntax:
1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [W
HERE CONDITION]
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.


Syntax:
1. DELETE FROM table_name [WHERE condition];
For example:
1. DELETE FROM javatpoint
2. WHERE Author="Sonoo";

3. DATA CONTROL LANGUAGE


DCL commands are used to grant and take back authority from any database
user.
Here are some commands that come under DCL:
 Grant
 Revoke

a. Grant: It is used to give user access privileges to a database.


Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER
_USER;

b. Revoke: It is used to take back permissions from the user.


Example
1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. TRANSACTION CONTROL LANGUAGE


TCL commands can only use with DML commands like INSERT, DELETE
and UPDATE only.
These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them.
Here are some commands that come under TCL:
 COMMIT
 ROLLBACK
 SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the


database.
Syntax:
1. COMMIT;
Example:
1. DELETE FROM CUSTOMERS
2. WHERE AGE = 25;
3. COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not
already been saved to the database.
Syntax:
1. ROLLBACK;
Example:
1. DELETE FROM CUSTOMERS
2. WHERE AGE = 25;
3. ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without
rolling back the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;

5. DATA QUERY LANGUAGE


DQL is used to fetch the data from the database.
It uses only one command:
 SELECT

a. SELECT: This is the same as the projection operation of relational algebra.


It is used to select the attribute based on the condition described by WHERE
clause.
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;

SQL VIEWS
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if
the data were coming from one single table.
A view is created with the CREATE VIEW statement.
CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates the
view, every time a user queries it.
SQL CREATE VIEW Examples
The following SQL creates a view that shows all customers from Brazil:
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
We can query the view above as follows:
Example
SELECT * FROM [Brazil Customers];
The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:
Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
We can query the view above as follows:
Example
SELECT * FROM [Products Above Average Price];

SQL Updating a View


A view can be updated with the CREATE OR REPLACE VIEW statement.
SQL CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';

SQL Dropping a View


A view is deleted with the DROP VIEW statement.
SQL DROP VIEW Syntax
DROP VIEW view_name;
The following SQL drops the "Brazil Customers" view:
Example
DROP VIEW [Brazil Customers];
A view is nothing more than a SQL statement that is stored in the database with
an associated name. A view is actually a composition of a table in the form of a
predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be
created from one or many tables which depends on the written SQL query to
create a view.
Views, which are a type of virtual tables allow users to do the following −
 Structure data in a way that users or classes of users find natural or
intuitive.
 Restrict access to the data in such a way that a user can see and
(sometimes) modify exactly what they need and no more.
 Summarize data from various tables which can be used to generate
reports.

Creating Views
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to
the specific implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as
you use them in a normal SQL SELECT query.
Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Following is an example to create a view from the CUSTOMERS table. This
view would be used to have customer name and age from the CUSTOMERS
table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an
actual table. Following is an example for the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result.
+ + +
| name | age |
+ + +
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+ + +

The WITH CHECK OPTION


The WITH CHECK OPTION is a CREATE VIEW statement option. The
purpose of the WITH CHECK OPTION is to ensure that all UPDATE and
INSERTs satisfy the condition(s) in the view definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating same view
CUSTOMERS_VIEW with the WITH CHECK OPTION.
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL
values in the view's AGE column, because the view is defined by data that does
not have a NULL value in the AGE column.
Updating a View
A view can be updated under certain conditions which are given below −
 The SELECT clause may not contain the keyword DISTINCT.
 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
 The query may not contain GROUP BY or HAVING.
 Calculated columns may not be updated.
 All NOT NULL columns from the base table must be included in the view
in order for the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that
view. The following code block has an example to update the age of Ramesh.
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
This would ultimately update the base table CUSTOMERS and the same would
reflect in the view itself. Now, try to query the base table and the SELECT
statement would produce the following result.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Inserting Rows into a View
Rows of data can be inserted into a view. The same rules that apply to the
UPDATE command also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not
included all the NOT NULL columns in this view, otherwise you can insert rows
in a view in a similar way as you insert them in a table.
Deleting Rows into a View
Rows of data can be deleted from a view. The same rules that apply to the
UPDATE and INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.
SQL > DELETE FROM CUSTOMERS_VIEW
WHERE age = 22;
This would ultimately delete a row from the base table CUSTOMERS and the
same would reflect in the view itself. Now, try to query the base table and the
SELECT statement would produce the following result.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no
longer needed. The syntax is very simple and is given below −
DROP VIEW view_name;
Following is an example to drop the CUSTOMERS_VIEW from the
CUSTOMERS table.
DROP VIEW CUSTOMERS_VIEW;

PL/pgSQL is PostgreSQL's built-in programming language for writing functions


which run within the database itself, known as stored procedures in other
databases. It extends SQL with loops, conditionals, and return types. Though its
syntax may be strange to many developers it is much faster than anything running
on the application server because the overhead of connecting to the database is
eliminated, which is particularly useful when you would otherwise need to
execute a query, wait for the result, and submit another query.
Though many other procedural languages exist for PostgreSQL, such as
PL/Python, PL/Perl, and PLV8, PL/pgSQL is a common starting point for
developers who want to write their first PostgreSQL function because its syntax
builds on SQL. It is also similar to PL/SQL, Oracle's native procedural language,
so any developer familiar with PL/SQL will find the language familiar, and any
developer who intends to develop Oracle applications in the future but wants to
start with a free database can transition from PL/pgSQL to PL/SQL with relative
ease.
It should be emphasized that other procedural languages exist and PL/pgSQL is
not necessarily superior to them in any way, including speed, but examples in
PL/pgSQL can serve as a common reference point for other languages used for
writing PostgreSQL functions. PL/pgSQL has the most tutorials and books of all
the PLs and can be a springboard to learning the languages with less
documentation.
Here are links to some free guides and books on PL/pgSQL:
 The official documentation:
https://www.postgresql.org/docs/current/static/plpgsql.html
 w3resource.com tutorial: http://www.w3resource.com/PostgreSQL/pl-
pgsql-tutorial.php
 postgres.cz tutorial: http://postgres.cz/wiki/PL/pgSQL_(en)
 PostgreSQL Server Programming, 2nd Edition:
https://www.packtpub.com/big-data-and-business-intelligence/postgresql-
server-programming-second-edition
 PostgreSQL Developer's Guide: https://www.packtpub.com/big-data-and-
business-intelligence/postgresql-developers-guide

PROGRAMMING WITH PL/pgSQL


 Basic PL/pgSQL Function
 custom exceptions
 PL/pgSQL Syntax
 RETURNS Block

Overview
1. Advantages of Using PL/pgSQL
2. Supported Argument and Result Data Types
PL/pgSQL is a loadable procedural language for the PostgreSQL database
system. The design goals of PL/pgSQL were to create a loadable procedural
language that
 can be used to create functions, procedures, and triggers,
 adds control structures to the SQL language,
 can perform complex computations,
 inherits all user-defined types, functions, procedures, and operators,
 can be defined to be trusted by the server,
 is easy to use.
Functions created with PL/pgSQL can be used anywhere that built-in functions
could be used. For example, it is possible to create complex conditional
computation functions and later use them to define operators or use them in index
expressions.
In PostgreSQL 9.0 and later, PL/pgSQL is installed by default. However it is still
a loadable module, so especially security-conscious administrators could choose
to remove it.
1.1. Advantages of Using PL/pgSQL
SQL is the language PostgreSQL and most other relational databases use as query
language. It's portable and easy to learn. But every SQL statement must be
executed individually by the database server.
That means that your client application must send each query to the database
server, wait for it to be processed, receive and process the results, do some
computation, then send further queries to the server. All this incurs interprocess
communication and will also incur network overhead if your client is on a
different machine than the database server.
With PL/pgSQL you can group a block of computation and a series of queries
inside the database server, thus having the power of a procedural language and
the ease of use of SQL, but with considerable savings of client/server
communication overhead.
 Extra round trips between client and server are eliminated
 Intermediate results that the client does not need do not have to be
marshaled or transferred between server and client
 Multiple rounds of query parsing can be avoided
This can result in a considerable performance increase as compared to an
application that does not use stored functions.
Also, with PL/pgSQL you can use all the data types, operators and functions of
SQL.
1.2. Supported Argument and Result Data Types
Functions written in PL/pgSQL can accept as arguments any scalar or array data
type supported by the server, and they can return a result of any of these types.
They can also accept or return any composite type (row type) specified by name.
It is also possible to declare a PL/pgSQL function as accepting record, which
means that any composite type will do as input, or as returning record, which
means that the result is a row type whose columns are determined by specification
in the calling query, as discussed in Section 7.2.1.4.
PL/pgSQL functions can be declared to accept a variable number of arguments
by using the VARIADIC marker. This works exactly the same way as for SQL
functions, as discussed in Section 38.5.6.
PL/pgSQL functions can also be declared to accept and return the polymorphic
types described in Section 38.2.5, thus allowing the actual data types handled by
the function to vary from call to call. Examples appear in Section 43.3.1.
PL/pgSQL functions can also be declared to return a “set” (or table) of any data
type that can be returned as a single instance. Such a function generates its output
by executing RETURN NEXT for each desired element of the result set, or by
using RETURN QUERY to output the result of evaluating a query.
Finally, a PL/pgSQL function can be declared to return void if it has no useful
return value. (Alternatively, it could be written as a procedure in that case.)
PL/pgSQL functions can also be declared with output parameters in place of an
explicit specification of the return type. This does not add any fundamental
capability to the language, but it is often convenient, especially for returning
multiple values. The RETURNS TABLE notation can also be used in place of
RETURNS SETOF.

2. Structure of PL/pgSQL
Functions written in PL/pgSQL are defined to the server by executing CREATE
FUNCTION commands. Such a command would normally look like, say,
CREATE FUNCTION somefunc(integer, text) RETURNS integer
AS 'function body text'
LANGUAGE plpgsql;
The function body is simply a string literal so far as CREATE FUNCTION is
concerned. It is often helpful to use dollar quoting (see Section 4.1.2.4) to write
the function body, rather than the normal single quote syntax. Without dollar
quoting, any single quotes or backslashes in the function body must be escaped
by doubling them. Almost all the examples in this chapter use dollar-quoted
literals for their function bodies.
PL/pgSQL is a block-structured language. The complete text of a function body
must be a block. A block is defined as:
[ <<label>> ]
[ DECLARE
declarations ]
BEGIN
statements
END [ label ];
Each declaration and each statement within a block is terminated by a semicolon.
A block that appears within another block must have a semicolon after END, as
shown above; however the final END that concludes a function body does not
require a semicolon.
Tip
A common mistake is to write a semicolon immediately after BEGIN. This is
incorrect and will result in a syntax error.
A label is only needed if you want to identify the block for use in an EXIT
statement, or to qualify the names of the variables declared in the block. If a label
is given after END, it must match the label at the block's beginning.
All key words are case-insensitive. Identifiers are implicitly converted to lower
case unless double-quoted, just as they are in ordinary SQL commands.
Comments work the same way in PL/pgSQL code as in ordinary SQL. A double
dash (--) starts a comment that extends to the end of the line. A /* starts a block
comment that extends to the matching occurrence of */. Block comments nest.
Any statement in the statement section of a block can be a subblock. Subblocks
can be used for logical grouping or to localize variables to a small group of
statements. Variables declared in a subblock mask any similarly-named variables
of outer blocks for the duration of the subblock; but you can access the outer
variables anyway if you qualify their names with their block's label. For example:
CREATE FUNCTION somefunc() RETURNS integer AS $$
<< outerblock >>
DECLARE
quantity integer := 30;
BEGIN
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 30
quantity := 50;
--
-- Create a subblock
--
DECLARE
quantity integer := 80;
BEGIN
RAISE NOTICE 'Quantity here is %', quantity; -- Prints 80
RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints
50
END;

RAISE NOTICE 'Quantity here is %', quantity; -- Prints 50

RETURN quantity;
END;
$$ LANGUAGE plpgsql;

You might also like