Unit-2
Unit-2
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.
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:
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;
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
OR
OR
OR
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.
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;
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];
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 |
+ + +
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;
RETURN quantity;
END;
$$ LANGUAGE plpgsql;