Creating Roles:


The Syntax to create a role

CREATE ROLE role_name
[IDENTIFIED BY password];

For example: To create a role called "developer" with password as "pwd",the code will be as follows

CREATE ROLE testing
[IDENTIFIED BY pwd];

It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a privilege direclty to every user. If a role is identified by a password, then, when you GRANT or REVOKE privileges to the role, you definetely have to identify it with the password.
We can GRANT or REVOKE privilege to a role as below.

For example: To grant CREATE TABLE privilege to a user by creating a testing role:

First, create a testing Role
CREATE ROLE testing

Second, grant a CREATE TABLE privilege to the ROLE testing. You can add more privileges to the ROLE.
GRANT CREATE TABLE TO testing;

Third, grant the role to a user.
GRANT testing TO user1;

To revoke a CREATE TABLE privilege from testing ROLE, you can write:

REVOKE CREATE TABLE FROM testing;

The Syntax to drop a role from the database is as below:

DROP ROLE role_name;

For example: To drop a role called developer, you can write:

DROP ROLE testing;





Privileges: Privileges defines the access rights provided to a user on a database object. There are two types of privileges.

1) System privileges - This allows the user to CREATE, ALTER, or DROP database objects.
2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or DELETE data from database objects to which the privileges apply.

Few CREATE system privileges are listed below:

System Privileges Description
CREATE object allows users to create the specified object in their own schema.
CREATE ANY object allows users to create the specified object in any schema.

The above rules also apply for ALTER and DROP system privileges.

Few of the object privileges are listed below:

Object Privileges Description
INSERT allows users to insert rows into a table.
SELECT allows users to select data from a database object.
UPDATE allows user to update data in a table.
EXECUTE allows user to execute a stored procedure or a function.

Roles: Roles are a collection of privileges or access rights. When there are many users in a database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles, you can grant or revoke privileges to users, thereby automatically granting or revoking privileges. You can either create Roles or use the system roles pre-defined by oracle.

Some of the privileges granted to the system roles are as given below:

System Role Privileges Granted to the Role
CONNECT CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE SEQUENCE, CREATE SESSION etc.
RESOURCE CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE TRIGGER etc. The primary usage of the RESOURCE role is to restrict access to database objects.
DBA ALL SYSTEM PRIVILEGES


Creating Roles:

The Syntax to create a role

CREATE ROLE role_name
[IDENTIFIED BY password];

For example: To create a role called "developer" with password as "pwd",the code will be as follows

CREATE ROLE testing
[IDENTIFIED BY pwd];

It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a privilege direclty to every user. If a role is identified by a password, then, when you GRANT or REVOKE privileges to the role, you definetely have to identify it with the password.
We can GRANT or REVOKE privilege to a role as below.

For example: To grant CREATE TABLE privilege to a user by creating a testing role:

First, create a testing Role
CREATE ROLE testing

Second, grant a CREATE TABLE privilege to the ROLE testing. You can add more privileges to the ROLE.
GRANT CREATE TABLE TO testing;

Third, grant the role to a user.
GRANT testing TO user1;

To revoke a CREATE TABLE privilege from testing ROLE, you can write:

REVOKE CREATE TABLE FROM testing;

The Syntax to drop a role from the database is as below:

DROP ROLE role_name;

For example: To drop a role called developer, you can write:

DROP ROLE testing;






SQL Joins are used to relate information in different tables. A Join condition is a part of the sql query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL WHERE Clause of select, update, delete statements.

The Syntax for joining two tables is:

SELECT col1, col2, col3...
FROM table_name1, table_name2 
WHERE table_name1.col2 = table_name2.col1; 

If a sql join condition is omitted or if it is invalid the join operation will result in a Cartesian product. The Cartesian product returns a number of rows equal to the product of all rows in all the tables being joined. For example, if the first table has 20 rows and the second table has 10 rows, the result will be 20 * 10, or 200 rows. This query takes a long time to execute.

Lets use the below two tables to explain the sql join conditions.
database table "product";
product_id product_name supplier_name unit_price
100 Camera Nikon 300
101 Television Onida 100
102 Refrigerator Vediocon 150
103 Ipod Apple 75
104 Mobile Nokia 50
database table "order_items";
order_id product_id total_units customer
5100 104 30 Infosys
5101 102 5 Satyam
5102 103 25 Wipro
5103 101 10 TCS
SQL Joins can be classified into Equi join and Non Equi join.
1) SQL Equi joins
It is a simple sql join condition which uses the equal sign as the comparison operator. Two types of equi joins are SQL Outer join and SQL Inner join.
For example: You can get the information about a customer who purchased a product and the quantity of product.
2) SQL Non equi joins
It is a sql join condition which makes use of some comparison operator other than the equal sign like >, <, >=, <=

1) SQL Equi Joins:
An equi-join is further classified into two categories: 
a) SQL Inner Join 
b) SQL Outer Join 

a) SQL Inner Join:
All the rows returned by the sql query satisfy the sql join condition specified.
For example: If you want to display the product information for each order the query will be as given below. Since you are retrieving the data from two tables, you need to identify the common column between these two tables, which is theproduct_id.
The query for this type of sql joins would be like,
SELECT order_id, product_name, unit_price, supplier_name, total_units 
FROM product, order_items 
WHERE order_items.product_id = product.product_id;
The columns must be referenced by the table name in the join condition, because product_id is a column in both the tables and needs a way to be identified. This avoids ambiguity in using the columns in the SQL SELECT statement.
The number of join conditions is (n-1), if there are more than two tables joined in a query where 'n' is the number of tables involved. The rule must be true to avoid Cartesian product.
We can also use aliases to reference the column name, then the above query would be like,
SELECT o.order_id, p.product_name, p.unit_price, p.supplier_name, o.total_units 
FROM product p, order_items o 
WHERE o.product_id = p.product_id; 
b) SQL Outer Join:
This sql join condition returns all rows from both tables which satisfy the join condition along with rows which do not satisfy the join condition from one of the tables. The sql outer join operator in Oracle is ( + ) and is used on one side of the join condition only.
The syntax differs for different RDBMS implementation. Few of them represent the join conditions as "sql left outer join", "sql right outer join".
If you want to display all the product data along with order items data, with null values displayed for order items if a product has no order item, the sql query for outer join would be as shown below:
SELECT p.product_id, p.product_name, o.order_id, o.total_units 
FROM order_items o, product p 
WHERE o.product_id (+) = p.product_id; 
The output would be like,
product_id product_name order_id total_units
------------- ------------- ------------- -------------
100 Camera
101 Television 5103 10
102 Refrigerator 5101 5
103 Ipod 5102 25
104 Mobile 5100 30
NOTE:If the (+) operator is used in the left side of the join condition it is equivalent to left outer join. If used on the right side of the join condition it is equivalent to right outer join.
SQL Self Join:
A Self Join is a type of sql join which is used to join a table to itself, particularly when the table has a FOREIGN KEY that references its own PRIMARY KEY. It is necessary to ensure that the join statement defines an alias for both copies of the table to avoid column ambiguity.
The below query is an example of a self join,
SELECT a.sales_person_id, a.name, a.manager_id, b.sales_person_id, b.name 
FROM sales_person a, sales_person b 
WHERE a.manager_id = b.sales_person_id; 
2) SQL Non Equi Join:
A Non Equi Join is a SQL Join whose condition is established using all comparison operators except the equal (=) operator. Like >=, <=, <, >
For example: If you want to find the names of students who are not studying either Economics, the sql query would be like, (lets use student_details table defined earlier.)
SELECT first_name, last_name, subject 
FROM student_details 
WHERE subject != 'Economics' 
The output would be something like,
first_name last_name Subject
------------- ------------- -------------
Anajali Bhagwat Maths
Shekar Gowda Maths
Rahul Sharma Science
Stephen Fleming Science





















Create a table named photo_test and insert some test data as :-
 Collapse
create table photo_test
(
pgm_main_Category_id int,
pgm_sub_category_id int,
file_path varchar(MAX)
)
 
insert into photo_test values
(17,15,'photo/bb1.jpg');     
                                                 
insert into photo_test values(17,16,'photo/cricket1.jpg');                                                    
insert into photo_test values(17,17,'photo/base1.jpg');                                                       
insert into photo_test values(18,18,'photo/forest1.jpg');                                                       
insert into photo_test values(18,19,'photo/tree1.jpg');                                                           
insert into photo_test values(18,20,'photo/flower1.jpg');                                                     
insert into photo_test values(19,21,'photo/laptop1.jpg');                                                       
insert into photo_test values(19,22,'photo/camer1.jpg');                                                 
 
insert into photo_test values(19,23,'photo/cybermbl1.jpg');                                                    
insert into photo_test values
(17,24,'photo/F1.jpg');
There are three groups of pgm_main_category_id each with a value of 17 (group 17 has four records),18 (group 18 has three records) and 19 (group 19 has three records). 
Now, if you want to select top 2 records from each group, the query is as follows:-
 Collapse
select pgm_main_category_id,pgm_sub_category_id,file_path from
(
select pgm_main_category_id,pgm_sub_category_id,file_path,
rank() over (partition by pgm_main_category_id order by pgm_sub_category_id asc) as rankid
from photo_test
) photo_test
where rankid < 3 -- replace 3 by any number 2,3 etc for top2 or top3.
order by pgm_main_category_id,pgm_sub_category_id
The result is as:-
 Collapse
 
pgm_main_category_id    pgm_sub_category_id      file_path
17                       15                      photo/bb1.jpg
17                       16                      photo/cricket1.jpg
18                       18                      photo/forest1.jpg
18                       19                      photo/tree1.jpg
19                       21                      photo/laptop1.jpg
19                       22                      photocamer1.jpg

Create a table named Employee_Test and insert some test data as:-

Create a table named Employee_Test and insert some test data as:-
 Collapse
CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)
 
INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
It is very easy to find the highest salary as:-
 Collapse
--Highest Salary
select max(Emp_Sal) from Employee_Test
Now, if you are asked to find the 3rd highest salary, then the query is as:-
 Collapse
--3rd Highest Salary
select min(Emp_Sal) from Employee_Test where Emp_Sal in
(select distinct top 3 Emp_Sal from Employee_Test order by Emp_Sal desc)
The result is as :- 1200 
To find the nth highest salary, replace the top 3 with top n (n being an integer 1,2,3 etc.)
 Collapse
--nth Highest Salary
select min(Emp_Sal) from Employee_Test where Emp_Sal in
(select distinct top n Emp_Sal from Employee_Test order by Emp_Sal desc)



Packages used:
1.      javax.swing.*              : Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
2.      java.awt.*                    : Contains all of the classes for creating user interfaces and for painting graphics and images.
3.      java.awt.event.*                      : Provides interfaces and classes for dealing with      different types of events fired by AWT components
4.      java.sql.*                                 : Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language.
Classes used:
·         JFrame             : An extended version of java.awt.Frame that adds support for the JFC/Swing component architecture.
·         Container        : A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list
·         JLabel  : A display area for a short text string or an image, or both
·         JButton           : An implementation of a "push" button.
·         JTextField : JTextField is a lightweight component that allows the editing of a single line of text.
·         Connection                  : A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection. A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on.
·         Statement                    : The object used for executing a static SQL statement and returning the results it produces.
·         ResultSet                     : table of data representing a database result set, which is usually generated by executing a statement that queries the database.
Logical flow of the program:
·         The swing program extends JFrame class and implements ActionListener.
·         Container object containing the JButtons,JTextFields are defined.
·         Connection is established between the database and the swing program with the data source.
·         When the “delete ” button is pressed the corresponding record is deleted through the object of Statement class.
·         When “next” or “previous” buttons are pressed corresponding navigation is implemented.
·         Id text field in the frame is not editable.


Important notes:
·         The swing program must import the package “javax.swing.*”.
·         To stop the execution of the program on closing frame,use the method setDefaultCloseOperation(EXIT_ON_CLOSE).
·         While writing the code for JDBC-ODBC bridge enclose it in try-catch blocks.
·         For backward mavigation, object of Statement should be initialized like this
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE )

To update a database table using java swing application.
Packages used:
1.      javax.swing.*              : Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
2.      java.awt.*                    : Contains all of the classes for creating user interfaces and for painting graphics and images.
3.      java.awt.event.*                      : Provides interfaces and classes for dealing with      different types of events fired by AWT components
4.      java.sql.*                                 : Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language.
Classes used:
·         JFrame             : An extended version of java.awt.Frame that adds support for the JFC/Swing component architecture.
·         Container        : A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list
·         JLabel  : A display area for a short text string or an image, or both
·         JButton           : An implementation of a "push" button.
·         JTextField : JTextField is a lightweight component that allows the editing of a single line of text.
·         Connection                  : A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection. A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on.
·         Statement                    : The object used for executing a static SQL statement and returning the results it produces.
·         ResultSet                     : table of data representing a database result set, which is usually generated by executing a statement that queries the database.
Logical flow of the program:
·         The swing program extends JFrame class and implements ActionListener.
·         Container object containing the JButtons,JTextFields are defined.
·         Connection is established between the database and the swing program with the data source.
·         When the “update ” button is pressed the corresponding record is updated through the object of Statement class.
·         When “next” or “previous” buttons are pressed corresponding navigation is implemented.
·         Id text field in the frame is not editable.


Important notes:
·         The swing program must import the package “javax.swing.*”.
·         To stop the execution of the program on closing frame,use the method setDefaultCloseOperation(EXIT_ON_CLOSE).
·         While writing the code for JDBC-ODBC bridge enclose it in try-catch blocks.
·         For backward mavigation, object of Statement should be initialized like this
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE )

A JAVA program to find Fibanocci/cuberoot/square root/palindrome/factorial/odd-even/prime.
Packages used:
1.      java.io.*                       : Provides for system input and output through data streams, serialization and the file system.
2.      javax.swing.*  : Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
3.      java.awt.*                    : Contains all of the classes for creating user interfaces and for painting graphics and images.
4.      java.awt.event.*          : Provides interfaces and classes for dealing with different types of events fired by AWT components
5.      java.math.*      : Provides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic
Classes used:
·         JFrame : Provides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic
·         Container        : A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list
·         JLabel  : A display area for a short text string or an image, or both
·         JButton           : An implementation of a "push" button.
·         JTextField : JTextField is a lightweight component that allows the editing of a single line of text.
Logical flow of the program:
·         A class inheriting JFrame and implementing ActionListener is created.
·         Container holds components like JLabel,JButton,JTextField.
·         According to the button clicked corresponding action is performed.
·         Result of the corresponding operation is displayed on the text field.
Important notes:
·         In all swing program the package that should be imported is “javax.swing.*”.
·         If in the program JApplet is inherited then the “init()” method is used to initialize the applet.
·         If in the program JFrame is inherited then the inheriting class’s constructor initializes the swing application.
1.If super() method is called ,it should be the first line inside the constructor.
2.Frame’s visibility and size must be set.


Copyright © 2012 OpenTechZone | Kesari Technologies |