Ex5 To 8
Ex5 To 8
Aim:
To implement queries and manage the database using SQL Programming with
procedures, function, constraints and security using triggers.
Procedure:
Stored Procedures/Functions:
A PostgreSQL function or a stored procedure is a set of SQL and procedural
commands such as declarations, assignments, loops; flow-of-control etc. stored on the
database server and can be involved using the SQL interfaces. And it is also known
as PostgreSQL stored procedures.
Single row or Scalar functions return a value for every row that is processed in
a query.
Numeric Functions
String Functions
Group Functions:
These functions group the rows of data based on the values returned by the
query.
NUMERIC FUNCTIONS
Functions Description
ABS Calculates the absolute value of an expression.
REMAINDER Returns the remainder after one numeric expression is divided by another.
FLOOR Returns the largest whole number equal to or less than a specified number.
Returns a value that indicates if a specified number is less than, equal to, or
SIGN
greater than 0 (zero).
STRING FUNCTIONS:
Functions Description
CHR Return the character value
Pad the right side of a string with a specific set of characters. This function
RPAD
is useful for formatting the output of a query. (expr1,n,expr2)
Remove all specified characters from the left end side of a string.
LTRIM Optionally you can specify an initial character or characters to trim to, or it
will default to a blank.
Remove all specified characters from the right end side of a string.
RTRIM Optionally you can specify an initial character or characters to trim to, or it
will default to a blank.
Search string for substring and find the the location of the substring in the
INSTR
string.
Get the characters having the binary equivalent to the number in the
NCHR national character set. This function is equivalent to using the CHR
function with the USING NCHAR_CS clause.
EXTRACT(YEAR,MONTH,DAY,HOUR,MINUTE,SECOND
EXTRACT(datetime) from Date) function returns extract value of a specified
datetime field from a datetime or interval expression.
Example:
BEGIN
RETURN val + 5;
END; $$
LANGUAGE PLPGSQL;
Calling a Function:
Syntax:
SELECT function_name(20);
Example:
SELECT inc(20);
Stored Procedure
Safe languages can be used by any users. SQL and PL/pgSQL are safe languages.
Syntax:
LANGUAGE SQL
AS $$
<SQL CODE>
$$;
Example:
create or replace procedure transfer(
senderint,
receiverint,
amountdec
)
languageplpgsql
as $$
declare
acc1int;
acc2int;
begin
select balance INTO acc1 from accounts where id = sender;
update accounts set balance = balance - amount where id = sender;
select balance into acc2 from accounts where id = receiver;
update accounts set balance = balance + amount where id = receiver;
insert into trans(said,sobal,raid,robal) values (sender,acc1,receiver,acc2);
commit;
end;$$;
Trigger
PostgreSQL Triggers are database callback functions, which are automatically
performed/invoked when a specified database event occurs.
A trigger that is marked FOR EACH ROW is called once for every row that the
operation modifies.
The following table summarizes which types of triggers may be used on tables, views, and
foreign tables:
Statement-
When Event Row-level
level
TRUNCATE — Tables
TRUNCATE — Tables
INSERT/UPDATE/DELETE Views —
INSTEAD OF
TRUNCATE — —
Result:
Thus the query manipulation and querying database using SQL Programming is
executed with Querying/Managing the database using SQL Programming.
Ex. No.: 6 Database design using Normalization – bottom-up approach
Date :
Aim:
Procedure:
Normalization:
Normalization is a database design technique which organizes tables in a manner that
reduces redundancy and dependency of data.
It divides larger tables to smaller tables and links them using relationships.
The inventor of the relational model Edgar Codd proposed the theory of normalization with
the introduction of First Normal Form, and he continued to extend theory with Second and
Third Normal Form. Later he joined with Raymond F. Boyce to develop the theory of Boyce-
Codd Normal Form.
Theory of Data Normalization in SQL is still being developed further. For example, there are
th
discussions even on 6 Normal Form. However, in most practical applications,
rd
normalizationachieves its best in 3 Normal Form. The evolution of Normalization theories is
illustrated below-
Assume a video library maintains a database of movies rented out. Without any normalization,
all information is stored in one table as shown below.
Here you see Movies Rented column has multiple values.
What is a KEY?
A KEY is a value used to identify a record in a table uniquely. A KEY could be a single
column or combination of multiple columns
Note: Columns in a table that are NOT used to identify a record uniquely are called non-key
columns.
A composite key is a primary key composed of multiple columns used to identify a record
uniquely
In our database, we have two people with the same name Robert Phil, but they live in different
places.
Hence, we require both Full Name and Address to identify a record uniquely. That is a
composite key.
Rule 1- Be in 1NF
Rule 2- Single Column Primary Key
nd
It is clear that we can't move forward to make our simple database in 2 Normalization form
unless we partition the table above.
Table 1
Table 2
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains
member information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id
You will only be able to insert values into your foreign key that exist in the unique key in the
parent table. This helps in referential integrity.
The above problem can be overcome by declaring membership id from Table2 as foreign key
of membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in the
parent table, an error will be shown!
A transitive functional dependency is when changing a non-key column, might cause any of
the other non-key columns to change
Consider the table 1. Changing the non-key column Full Name may change Salutation.
Rule 1- Be in 2NF
Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
TABLE 1
Table 2
Table 3
We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF. In Table 3
Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in Table 3
Now our little example is at a level that cannot further be decomposed to attain higher
forms of normalization. In fact, it is already in higher normalization forms. Separate efforts for
moving into next levels of normalizing data are normally needed in complex databases.
However, we will be discussing next levels of normalizations in brief in the following.
Boyce-Codd Normal Form (BCNF)
rd
Even when a database is in 3 Normal Form, still there would be anomalies resulted if
it has more than one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form.
If no database table instance contains two or more, independent and multivalued data
th
describing the relevant entity, then it is in 4 Normal Form.
Result:
Ex. No.:7 Develop database applications using IDE/RAD tools (Eclipses)
Date :
Thus
we implemented database design using Normalization with bottom up approach.
Aim:
Procedure:
https://jdbc.postgresql.org/download.html
Class.forName("org.postgresql.Driver");
Connection c = DriverManager.getConnection
("jdbc:postgresql://<Host>:<Port Id>/<Schema>",
“<User Name>",
“<Password>“
);
Example:
Connection c = DriverManager.getConnection
("jdbc:postgresql://localhost:5432/Test","postgres","admin@321");
Statement s = c.createStatement();
s.executeUpdate(“<Query>");
while(rs.next())
System.out.println(
rs.getString("name"));
Statement.close();
Connection.close();
Program:
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
throwsClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
Connectionc = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/Test","postgres","admin@321");
Statement s = c.createStatement();
while(rs.next())
s.close();
c.close();
Conclusion:
Date : diagrams
Aim:
To develop database design using EER to ODB mapping / UML Class Diagrams.
Procedure:
UML Class Diagram
Describes the system’s data, including attributes of and relationships between the
“objects.”
Object databases (ODB)
Object data management systems (ODMS)
Meet some of the needs of more complex applications
Specify:
o Structure of complex objects
o Operations that can be applied to these objects
Introduction to object-oriented concepts and features
Origins in OO programming languages
Object has two components:
o State (value) and behavior (operations)
Instance variables
o Hold values that define internal state of object
Operation is defined in two parts:
Signature or interface and implementation
Inheritance
Permits specification of new types or classes that inherit much of their structure
and/or operations from previously defined types or classes
Operator overloading
Generalization
Is a relationship that recognizes that some kinds of entities can be subdivided
into smaller, more specialized groups.
General Hardware Company ERD
Each box represents a class and has three sections separated by horizontal lines.
At the top, in capital letters, is the class name
In the middle are the class attributes
At the bottom are the class operations (not shown)
Encapsulation of Operations and Persistence of Objects
Encapsulation
Related to abstract data types and information hiding in programming languages
Define behavior of a type of object based on operations that can be externally
applied
External users only aware of interface of the operations
Object constructor
Destructor operation
Modifier operations
Persistence of Objects
Transient objects
Persistent objects
Naming mechanism
Reachability
Inheritance
Format:
Subtype
Useful when creating a new type that is similar but not identical to an already
defined type
Example:
Extent
Persistent collection
Transient collection
Multiple inheritance
Selective inheritance
Conclusion:
Thus database design using EER-to-ODB mapping / UML class diagrams was
constructed.