A User is basically used to connect to database. All db objects like table,index,view can be created under that user.
A profile enforces set of password security rules and resource usage limit.
A role is a collection of privileges. It allows easier management of privileges.
A privilege is a permission to execute either a SQL statements or to perform action on database objects.
A GRANT statement assigns one or more privileges to a specific user.
Database - It is made up of one or more tablespaces
Tablespace - It is made up of one or more data files, a tablespace contains segments
Segment - It is made up of one or more extents.
Extent - It is a continuous set of blocks on a disk
Block - It is the smallest unit of allocation in the database.
Datafiles - It contain the application data being stored
Redo log file - It store all the transactions made to the database.
Control file - It store information specifying the structure of the database
Parameter file - It contains all the important information necessary to start a database.
Password file - It contain the password information for all users.
SEQUENCE - It can be used to populate data in the primary key or unique columns of a table.
VIEWS - It represents the result of a query to one or more underlying tables
INDEX - In index allows to find and retrieve specific rows much faster than it could do without an index.
TRIGGER - In trigger functionality can be useful as it will invoke the required function on defined events.
PROCEDURE - In stored procedures do not return but performs the action against values in the table.
FUNCTION - In function it return the value based on the in given but can't do operation on table
PACKAGE - It provide a convenient way of organizing the functions and procedures.
4. CREATE USER
A user in the Oracle database is an authorized account that
can access and use the database.
Each user has his credentials (username and password) to
access the database.
Whenever a user is logged into the database, a session is
started in which they can access objects and perform actions
for which they have privileges.
The privileges are assigned to them after the user is created
by the database administrator.
5. USER CREATION
CREATE USER username IDENTIFIED BY
password
[DEFAULT TABLESPACE tablespace]
[QUOTA {size | UNLIMITED} ON tablespace]
[PROFILE profile]
[PASSWORD EXPIRE]
[ACCOUNT {LOCK | UNLOCK}];
CREATE USER c##john IDENTIFIED
john123
DEFAULT TABLESPACE DATA1
QUOTA 10M ON tbs1
PROFILE profile1
PASSWORD EXPIRE
ACCOUNT UNLOCK;
6. USER ALTERATION
ALTER USER username IDENTIFIED BY new_password;
ALTER USER username {LOCK|UNLOCK};
ALTER USER username ACCOUNT EXPIRE;
ALTER USER username DEFAULT TABLESPACE
tablespace_name;
ALTER USER username TEMPORARY TABLESPACE
temp_tablespace;
ALTER USER username QUOTA 10M ON tablespace_name;
ALTER USER c##john IDENTIFIED BY john321;
ALTER USER c##john UNLOCK;
ALTER USER c##john ACCOUNT EXPIRE;
ALTER USER c##john DEFAULT TABLESPACE
data2;
ALTER USER c##john TEMPORARY TABLESPACE
temp2;
ALTER USER c##john QUOTA 10M ON data2;
7. PROFILE CREATION
Profiles in Oracle are used to manage system resource
allocation and password management policies for the database.
User accounts can have only a single profile and a default
already exists within Oracle named DEFAULT.
Assigning a new profile to a user account supersedes any earlier
profile. and Profiles cannot be assigned to roles or other profiles.
Profiles restrict database usage by a system user and restrict
users from performing operations that exceed reasonable
resource utilization.
9. PROFILE CREATION
*SESSION_PER_USER – No. of allowed concurrent sessions for a user
*CPU_PER_SESSION – CPU time limit for a session, expressed in hundredth of seconds.
*CPU_PER_CALL – Specify the CPU time limit for a call (a parse, execute, or fetch), expressed
in hundredths of seconds.
*CONNECT_TIME – Specify the total elapsed time limit for a session, expressed in minutes.
*IDLE_TIME – Specify the permitted periods of continuous inactive time during a session,
expressed in minutes.
*LOGICAL_READS_PER_SESSION – Specify the permitted number of data blocks read in a
session, including blocks read from memory and disk.
10. PROFILE CREATION
*FAILED_LOGIN_ATTEMPTS : No. of failed attempts to log in to the user account before
the account is locked
*PASSWORD_LIFE_TIME: No. of days the account will be open. after that it will expiry.
*PASSWORD_REUSE_TIME : Number of a time limit before a previous password can be
re-entered.
*PASSWORD_REUSE_MAX: Number of days before which a password can be reused
*PASSWORD_LOCK_TIME: Number of days the user account remains locked after failed
login
*PASSWORD_GRACE_TIME: Number of grace days for user to change password
11. CREATE ROLE
Roles in Oracle are used to group privileges or other roles so that
they can be assigned to users easily, instead of manually defining
them individually for each user.
Roles are usually created by database administrators, however,
any other user with privileges can also create roles.
If a role is not password authenticated or a secure application
role, then we can grant the role indirectly to the user.
Each role granted to a user is, at a given time, either enabled or
disabled.
12. ROLE,GRANT,PRIVILEG
E
Role Creation :
CREATE ROLE role_name;
CREATE ROLE c##role1;
CREATE ROLE c##role1 IDENTIFIED by r@123;
Grant Privilege to role|user :
GRANT CREATE SESSION TO user|role;
GRANT CREATE SESSION TO c##role1;
GRANT CREATE TABLE TO user|role;
GRANT CREATE TABLE TO c##john;
DATABASE ALTER DATABASE, ALTER SYSTEM, AUDIT SYSTEM
INDEX CREATE ANY/ALTER ANY/DROP ANY INDEX
PROFILE CREATE/ALTER/DROP PROFILE
ROLE
CREATE/ALTER ANY/DROP ANY /GRANT ANY (allows
REVOKE)
Rollback Segment CREATE/ALTER/DROP ROLLBACK SEGMENT
USER CREATE/ALTER/BECOME/DROP USER
VIEW CREATE/CREATE ANY/DROP ANY VIEW
SYNONYM
CREATE/CREATE ANY/CREATE PUBLIC/DROP ANY/DROP
PUBLIC SYNONYM
SESSION CREATE/ALTER/RESTRICTED SESSION
TABLE
CREATE/CREATE ANY/ALTER ANY/DROP ANY/SELECT
ANY/INSERT ANY/UPDATE ANY/DELETE ANY/LOCK ANY
TABLE
TABLESPACE CREATE/ALTER/DROP/MANAGE TABLESPACE
13. ROLE,GRANT,PRIVILEG
E
Assign the Role to a User :
GRANT ROLE TO user;
GRANT c##role1 TO c##john;
Revoke Privilege to role|user :
REVOKE CREATE TABLE
FROM c##john;
Drop a Role or User:
DROP ROLE c##john
DROP ROLE c##role1
GRANT INSERT ON table_name TO role|user;
GRANT INSERT ON Emp TO c##john ;
GRANT ALL PRIVILEGES TO user|role;
GRANT ALL PRIVILEGES TO c##role1;
GRANT CREATE INDEX TO c##john
WITH ADMIN OPTION ;
GRANT SELECT ON table_name TO c##role1
WITH GRANT OPTION ;
14. CONCLUSIO
N
User
A User is basically used to connect to database. All db objects
like table,index,view can be created under that user.
Role
A role is a collection of privileges. It allows easier management
of privileges.
Profile
A profile enforces set of password security rules and resource
usage limit.
Privilege
A privilege is a permission to execute either a SQL statements
or to perform action on database objects.
Grant
A GRANT statement assigns one or more privileges to a
specific user.
The GRANT statement assigns one or more privileges to a specific user.
16. Logical vs Physical Storage
○ One characteristic of an RDBMS is the independence of logical
data structures such as tables, views, and indexes from physical
storage structures.
○ The physical database structures of an Oracle database are
viewable at the operating system level.
○ Logical storage helps users locate specific data and improves the
efficiency of the retrieval process.
○ The logical units of database space allocation are data blocks,
extents, segments, and tablespaces. At a physical level, the data is
stored in data files on disk.
○ We can manage physical storage of data without affecting access
to logical structures.
19. ○ At the operating system level, Oracle Database stores
database data in structures called data files.
○ The datafiles allocated for a database physically store
information on logical structures of database, such as tables
and indexes.
○ One or more datafiles form a logical unit of database
storage, called a tablespace.
○ Datafiles provide data to users when requested and save it
in cache memory of Oracle.
○ Every Oracle database has one or more datafiles.
DATA FILES
20. CONTROL FILES
○ Oracle Database uses the control file to locate database
files and to manage the state of the database
○ A control file contains information such as data files,
online redo log files, and archived redo log files.
○ The control file contains information required to recover
the database, including checkpoints.
○ Oracle Database enables multiple, identical control files to
be open concurrently and written to the same database.
○ At least one unique control file must be present for the
database to start.
21. REDO LOG FILE
○ An online redo log files is made up of redo entries that record
all changes made to the data.
○ The online redo log files enable Oracle Database to recover
committed data that it has not yet written to the data files.
○ The database maintains online redo log files to protect
against data loss. Specifically, after an instance failure.
○ If the database crashes, the RDBMS can reprocess all
changes on datafiles which will take the database data back to
the state it was when the last redo record was written.
○ Every Oracle database has a set of two or more online redo
log files.
22. ARCIHVED LOG FILE
○ An archived redo log file is a copy of a filled member of
an online redo log group.
○ The file is not considered part of the database but is an
offline copy of an online redo log file created by the
database.
PARAMETER FILE
○ A parameter file is a file that contains a list of
initialization parameters and a value for each parameter.
○ A server parameter file is a binary file that acts as a
repository for initialization parameters.
○ An initialization parameter file is a text file that contains a
list of initialization parameters.
23. PASSWORD FILE
○ Password file can be used for local or remote
connections to Oracle Database.
○ A Password file in Oracle is a file that stores the
usernames and passwords of all users who need access
to a particular Oracle database or system.
ALERT AND TRACE FILE
○ The alert file, or alert log, is a special trace file. The
alert log of a database is a chronological log of
messages and errors.
○ A trace file is a file that contains diagnostic data used to
investigate problems.
25. TABLESPACES
○ A database is divided into logical storage units called
Tablespaces.
○ At the physical level, a tablespace stores data in one or more
data files or temp files.
○ A database must have the SYSTEM and SYSAUX
tablespaces.
○ Each tablespace consists of at least one data file.
○ Tablespaces logically organize data that are physically stored
in datafiles.
○ The Tablespace can store tables, but can also store many
other database objects such as indexes, views, sequences,
etc.
○ Tablespaces make it easier to allocate space quotas to users
26. SEGMENTS
○ A Segment is a set of extents that contains all the data for a logical
storage structure within a tablespace.
○ A single data segment in a database stores the data for one user
object.
○ More extents are automatically allocated by Oracle to a segment if its
existing extents become full.
○ The different types of segments are the data segments, index
segments, rollback segments and temporary segments.
• Data segment - stores table data
• Index segment - stores index data
• Temporary segment - temporary space used during SQL
execution
• Rollback Segment - stores undo information
27. EXETENTS
○ An Extent is a logical unit of database storage space allocation
made up of several contiguous data blocks.
○ The database allocates an initial extent for a data segment when the
segment is created.
○ If the initial extent become full, and if more space is required, then
the database automatically allocates an incremental extent for this
segment.
○ Once allocated to an index / table, the extent remains allocated to
that particular object unless we drop the object using
a DROP statement.
○ When the existing space in a segment is completely used, Oracle
allocates a new extent for the segment.
28. DATA BLOCKS
○ All the data in the Oracle database is stored In Data blocks in
both discs and memory.
○ A Data block is the smallest unit of allocation in the database.
○ Oracle does not store a whole table in one Data block and
return it from there directly.
○ A Data block has a specific size and cannot be extended
directly.
Header
contains information regarding the type of block , transaction information on the block and
the address (location) of the block on the disk
Table Directory contains information about the tables that store rows in this block
Row Directory contains information describing the rows that are to be found on the block.
Free space available space within the block
Data data within the block
29. CONCLUSION
Database - It is made up of one or more tablespaces
Tablespace - It is made up of one or more data files, a tablespace contains
segments
Segment - It is made up of one or more extents.
Extent - It is a continuous set of blocks on a disk
Block - It is the smallest unit of allocation in the database.
Datafiles - It contain the application data being stored
Redo log file - It store all the transactions made to the database.
Control file - It store information specifying the structure of the database
Parameter file - It contains all the important information necessary to start a
database.
Password file - It contain the password information for all users.
LOGICAL
STORAGE
PHYSICAL
STORAGE
32. SEQUENCE IN POSTGRESQL
CREATE [ IF NOT EXISTS ] SEQUENCE name
[ INCREMENT [ BY ] increment ]
[ MINVALUE minvalue | NO MINVALUE ]
[ MAXVALUE maxvalue | NO MAXVALUE ]
[ START [ WITH ] start ]
[ [ NO ] CYCLE ]
[ OWNED BY { table_name.column_name | NONE } ];
CREATE SEQUENCE seq1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
START WITH 1
CYCLE
OWNED BY emp.emp_id;
SELECT NEXTVALUE(‘seq1’); DROP SEQUENCE seq;
33. SEQUENCE IN POSTGRESQL
● The query starts with CREATE SEQUENCE keywords followed by the name of the sequence.
● The INCREMENT keyword is used to increase the value by adding it to the current value.
● The user can set MAXVALUE and MINVALUE to mark the end of the sequence but it takes the default value if NO
MINVALUE or NO MAXVALUE is selected.
● The START keyword specifies where the sequence starts from.
● If CYCLE is specified, the sequence will start again from the MINVALUE once the MAXVALUE is reached. If not
specified, calling nextval() after reaching the MAXVALUE will result in an error.
● OWNED BY specifies which table and column should "own" the sequence, which means that the sequence will be
automatically dropped if the owning table or column is dropped.
34. TRIGGERS IN POSTGRESQL
CREATE [ OR REPLACE ] TRIGGER trigger_name
{ BEFORE | AFTER } { event}
ON table_name
[ FOR [ EACH ] { ROW | STATEMENT } ]
[ WHEN ( condition ) ]
EXECUTE { FUNCTION | PROCEDURE } function_name;
CREATE OR REPLACE TRIGGER tgr1
BEFORE UPDATE
ON emp
FOR EACH ROW
WHEN (OLD.data IS DISTINCT FROM NEW.data)
EXECUTE PROCEDURE data_update();
ALTER TRIGGER tgr1 ON Emp
RENAME TO new_tgr1;
ALTER TABLE Emp DISABLE|ENABLE
TRIGGER tgr1 | ALL;
35. TRIGGERS IN POSTGRESQL
● Trigger_name specifies the name of the trigger which we have to specify after the keyword TRIGGER.
● {BEFORE | AFTER } specify the time of trigger execution.
● Event_name is the name of the event/operation that is to be triggered such as UPDATE, INSERT, DELETE.
● Table_name gives the name of the table on which the trigger is to be executed/fired.
● [FOR [EACH] { ROW | STATEMENT }] Row level triggers executes once for each and every row in the transaction.
Statement level triggers executes only once for each single transaction.
● If a WHEN clause is supplied, the PostgreSQL statements specified are only executed for rows for which the WHEN
clause is true. If no WHEN clause is supplied, the PostgreSQL statements are executed for all rows.
● EXECUTE PROCEDURE is followed by the trigger function that is to be executed when a trigger is fired.
36. TRIGGERS IN POSTGRESQL
CREATE OR REPLACE FUNCTION insert_trigger_fnc()
RETURNS trigger AS $$
BEGIN
INSERT INTO Emp_bkp ( EmpId, LastName ,FirstName)
VALUES(NEW.EmpId, NEW.LastName, NEW.FirstName);
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
CREATE TRIGGER insert_trigger
AFTER INSERT
ON Emp
FOR EACH ROW
EXECUTE PROCEDURE insert_trigger_fnc();
DROP TRIGGER insert_trigger;
37. VIEWS IN POSTGRESQL
CREATE [OR REPLACE] VIEW view-name
[COLUMNS]
AS
SELECT column(s)
FROM table(s)
[WHERE condition(s)];
CREATE OR REPLACE VIEW Price_View
(product_id, unit_price)
AS
SELECT id, price
FROM Price
WHERE price > 200;
ALTER VIEW Price_View RENAME TO Cost_View; DROP VIEW Price_View;
38. VIEWS IN POSTGRESQL
CREATE MATERIALIZED VIEW [ IF NOT EXISTS ]
view_name
AS
SELECT column(s)
FROM table(s)
[WHERE condition(s)];
[ WITH [ NO ] DATA ]
CREATE MATERIALIZED VIEW
Price_View
AS
SELECT id, price
FROM Price
WHERE price > 200;
WITH DATA
REFRESH MATERIALIZED VIEW CONCURRENTLY Price_View; DROP MATERIALIZED VIEW Price_View;
39. VIEWS IN POSTGRESQL
•First, specify the view_name after the CREATE MATERIALIZED VIEW clause
•Second, add the query that gets data from the underlying tables after the AS keyword.
•Third, if we want to load data into the materialized view at the creation time, use the WITH
DATA option. In case we use WITH NO DATA, the view is flagged as unreadable. It means that we
cannot query data from the view until we load data into it.
PARAMETER VIEW MATERIALIZED VIEW
Basic A View is never stored it is only displayed. A Materialized View is stored on the disk.
Define View is the virtual table formed from one or more base
tables or views.
Materialized view is a physical copy of the base
table.
Update Views are updated every time
when the base tables are updated.
Materialized View has to be updated manually or
using triggers.
Speed Slow processing. Fast processing.
Memory usage View do not require memory space. Materialized View utilizes memory space.
40. INDEXES IN POSTGRESQL
CREATE [UNIQIE] INDEX index_name ON table_name
[USING B-tree|GIN|HASH|GiST|BRIN|SP-GiST]
( column_name1 [ASC | DESC] [NULLS {FIRST | LAST}],
column_name2 [ASC | DESC] [NULLS {FIRST | LAST}],
column_name3 [ASC | DESC] [NULLS {FIRST | LAST}])
WHERE CONDITION(s);
CREATE INDEX index1 ON Emp
USING B-tree
( contact_number ASC ,
emp_id DESC,
passport_number NULLS LAST)
Where passport_flag = ‘Y’;
ALTER INDEX [ IF EXISTS ] index1 RENAME
TO new_index1;
DROP INDEX IF EXISTS index_name ;
41. INDEXES IN POSTGRESQL
• First, specify the index name after the CREATE INDEX clause. The index name should be meaningful and easy to remember.
• Second, specify the name of the table to which the index belongs.
• Third, specify the index method such as BTREE, HASH, GIST, SPGIST, GIN, and BRIN. PostgreSQL uses BTREE by default.
• Finally, list one or more columns of the index. The ASC and DESC specify the sort order. The default sort order is ASC.
• If a column contains NULL, we can specify NULLS FIRST or NULLS LAST option. The NULLS FIRST is the default when DESC is
specified and NULLS LAST is the default when DESC is not specified.
B-Tree - This is the Default index type is used for operations like >, >=, <, <= and it Supports multi-columns.
Hash - This index size is small compared to the B-tree index hence occupy less space but Does not support the multi-columns index.
BRIN - Good fit for time-series data. Performs better than B-Tree and very small in size compared to B-Tree
GIN - It is also called inverted index. Good fit Array, Range Types, Full text search .
GiST - It Good fit for Full-text search or Geometric types.For dynamic data, GiST is a better option compared to GIN.
Partial Index - Index with “where” cause.Segment of records are indexed, so it is small and efficient.
42. FUNCTION IN POSTGRESQL
create function function_name(param_list)
returns return_type
language plpgsql
AS $$
declare
--variable
Begin
-- logic
end;
$$
create function get_count(len_from int, len_to int)
returns int
language plpgsql
AS $$
declare
film_count integer;
begin select count(*) into film_count from film
where length between len_from and len_to;
return film_count;
end;
$$;
43. FUNCTION IN POSTGRESQL
•First, specify the name of the function after the CREATE FUNCTION keywords. If we want to replace the existing
function, we can use the or replace keywords.
•Then, specify the function PARAMETER list surrounded by parentheses after the function name. A function can have
zero or many parameters.
•Next, specify the datatype of the returned value after the RETURNS keyword.
•After that, use the LANGUAGE PLPGSQL to specify the procedural language of the function. Note that PostgreSQL
supports many procedural languages, not just plpgsql.
•Finally, place a block in the DOLLAR-QUOTED STRING CONSTANT($$).
•At Last, DECLARE The Variable And Write The Logics In The BEGIN End Blocks.
SELECT get_count(40,90); DROP FUNCTION get_count();
44. PROCEDURE in postgresql
create procedure procedure_name(param_list)
language plpgsql
as $$
declare
-- variable declaration
begin
-- stored procedure body
end;
$$
44
create procedure amount_proc( sender_id int, amount dec )
language plpgsql
as $$
begin
update accounts set balance = balance - amount
where id = sender_id;
commit;
end;
$$
45. PROCEDURE in postgresql
•First, specify the name of the stored procedure after the CREATE PROCEDURE keywords.
•Second, define PARAMETERS for the stored procedure. A stored procedure can accept zero or more parameters.
•Third, specify LANGUAGE PLPGSQL as the procedural language for the stored procedure. Note that we can use other
procedural languages for the stored procedure such as SQL, C, etc.
•Finally, use the DOLLAR-QUOTED STRING CONSTANT syntax to define the body of the stored procedure.
Parameters in stored procedures can have the IN and INOUT modes. They cannot have the out mode.
CALL amount_proc(1,1000); DROP PROCEDURE get_count();
46. PACKAGES IN POSTGRESQL
CREATE OR REPLACE PACKAGE BODY empinfo_pkg AS
Procedure amount_proc( sender_id int, amount dec ) as
begin
update accounts set balance = balance - amount
where id = sender_id;
commit;
end;
Function get_count(len_from int, len_to int)
returns int as
declare
film_count integer;
begin select count(*) into film_count from film
where length between len_from and len_to;
return film_count;
End empinfo_pkg;
CREATE OR REPLACE PACKAGE BODY package_body_name AS
Procedure procedure_name(param_list)
as
Declare
-- variable declaration
begin
-- stored procedure body
end;
Function function_name(param_list)
returns return_type
as
declare
--variable
Begin
--logic
end;
End package_body_name ;
47. PACKAGES IN POSTGRESQL
CREATE OR REPLACE PACKAGE empinfo_pkg as
Procedure procedure_name( param_lists );
Function get_count( param_lists )
Return return_type;
End empinfo_pkg;
CREATE OR REPLACE PACKAGE empinfo_pkg as
Procedure amount_proc( sender_id int, amount dec );
Function get_count( len_from int, len_to int )
Return int;
End empinfo_pkg;
DROP PACKAGE [ BODY ] package_name
DROP PACKAGE drops an existing package. To execute this command, we must be a superuser or the owner
of the package. Specify BODY to remove only the package body without dropping the package specification.
Omit BODY to remove both the package specification and body.
48. CONCLUSION
- It can be used to populate data in the primary key or unique columns of a table.
- It represents the result of a query to one or more underlying tables
- In index allows to find and retrieve specific rows much faster than it could do without an index.
- In trigger functionality can be useful as it will invoke the required function on defined events.
- In stored procedures do not return but performs the action against values in the table.
- In function it return the value based on the in given but can't do operation on table
- It provide a convenient way of organizing the functions and procedures.