Monday, 2 December 2013

MongoDB Queries - 2

MongoDB Update() method

MongoDB's update() method is used to update document into a collection. The update() method update values in the existing document.


> db.democol.find().pretty()

Result:

{
        "_id" : ObjectId("52963c2a6f63f810a98b7a98"),
        "title" : "Learn mongo",
        "by" : "mani",
        "likes" : 100
}
{
        "_id" : ObjectId("52963ce96f63f810a98b7a99"),
        "by" : "subramanian",
        "comments" : [
                {
                        "user" : "Tiara",
                        "message" : "Worth to read"
                }
        ],
        "likes" : 20,
        "title" : "Basic SQL"
}

> db.democol.update({'title':'Basic SQL'},{$set:{'title':'Learn SQL'}})
> db.democol.find().pretty()

Result:

{
        "_id" : ObjectId("52963c2a6f63f810a98b7a98"),
        "title" : "Learn mongo",
        "by" : "mani",
        "likes" : 100
}
{
        "_id" : ObjectId("52963ce96f63f810a98b7a99"),
        "by" : "subramanian",
        "comments" : [
                {
                        "user" : "Tiara",
                        "message" : "Worth to read"
                }
        ],
        "likes" : 20,
        "title" : "Learn SQL"
}

By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.

>db.democol.update({'title':'Basic SQL'},{$set:{'title':'Learn SQL'}},{multi:true})



The remove() Method

MongoDB's remove() method is used to remove document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag

deletion criteria : (Optional) deletion criteria according to documents will be removed.

justOne : (Optional) if set to true or 1, then remove only one document.

>db.mycol.find()

Result:

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'

>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()

Result:

{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}


Remove only one

If there are multiple records and you want to delete only first record, then set justOne parameter in remove() method

>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)



MongoDB Projection

In mongodb projection meaning is selecting only necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.

The find() Method

MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB when you execute find() method, then it displays all fields of a document. To limit this you need to set list of fields with value 1 or 0. 1 is used to show the filed while 0 is used to hide the field.

> db.democol.find({},{title:1,_id:0})

Result:

{ "title" : "Learn mongo" }
{ "title" : "Learn SQL" }

Sunday, 1 December 2013

MondoDB Queries

The find() Method

To query data from MongoDB collection, you need to use MongoDB's find() method.

> db.democol.find()

Result:

{ "_id" : ObjectId("52963c2a6f63f810a98b7a98"), "title" : "Learn mongo", "by" :
"mani", "likes" : 100 }
{ "_id" : ObjectId("52963ce96f63f810a98b7a99"), "title" : "Learn SQL", "by" : "s
ubramanian", "likes" : 20, "comments" : [  {  "user" : "Tiara",  "message" : "Wo
rth to read" } ] }


The pretty() Method

To display the results in a formatted way, you can use pretty() method.

> db.democol.find().pretty()

Result:

{
        "_id" : ObjectId("52963c2a6f63f810a98b7a98"),
        "title" : "Learn mongo",
        "by" : "mani",
        "likes" : 100
}
{
        "_id" : ObjectId("52963ce96f63f810a98b7a99"),
        "title" : "Learn SQL",
        "by" : "subramanian",
        "likes" : 20,
        "comments" : [
                {
                        "user" : "Tiara",
                        "message" : "Worth to read"
                }
        ]
}


AND in MongoDB

In the find() method if you pass multiple keys by separating them by ',' then MongoDB treats it AND condition. Basic syntax of AND is shown below:

> db.democol.find({by:"mani"}).pretty()

Result:

> db.democol.find({by:"mani"}).pretty()
{
        "_id" : ObjectId("52963c2a6f63f810a98b7a98"),
        "title" : "Learn mongo",
        "by" : "mani",
        "likes" : 100
}

> db.democol.find({by:"mani",title:"Learn mongo"}).pretty()

Result:

{
        "_id" : ObjectId("52963c2a6f63f810a98b7a98"),
        "title" : "Learn mongo",
        "by" : "mani",
        "likes" : 100
}


OR in MongoDB

To query documents based on the OR condition, you need to use $or keyword. Basic syntax of OR is shown below:

> db.democol.find({$or:[{by:"mani"},{title:"Learn SQL"}]}).pretty()

Result:

{
        "_id" : ObjectId("52963c2a6f63f810a98b7a98"),
        "title" : "Learn mongo",
        "by" : "mani",
        "likes" : 100
}
{
        "_id" : ObjectId("52963ce96f63f810a98b7a99"),
        "title" : "Learn SQL",
        "by" : "subramanian",
        "likes" : 20,
        "comments" : [
                {
                        "user" : "Tiara",
                        "message" : "Worth to read"
                }
        ]
}

Thursday, 28 November 2013

MongoDB Create and drop methods

Create Database:

If you want to create a database with name <mydb>, then use DATABASE statement would be as follows:

>use mydb
switched to db mydb


To check your currently selected database use the command db

>db
mydb


If you want to check your databases list, then use the command show dbs.

>show dbs
local     0.78125GB
mydb  0.23012GB
test      0.23012GB

Drop Database:

db.dropDatabase()

Create Collection:

Basic syntax of createCollection() command is as follows

db.createCollection(name, options)

In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection

ParameterTypeDescription
NameStringName of the collection to be created
OptionsDocument(Optional) Specify options about memory size and indexing

Options parameter is optional, so you need to specify only name of the collection. Following is the list of options you can use:


FieldTypeDescription
cappedBoolean(Optional) If true, enables a capped collection. Capped collection is a collection fixed size collecction that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.
autoIndexIDBoolean(Optional) If true, automatically create index on _id field.s Default value is false.
sizenumber(Optional) Specifies a maximum size in bytes for a capped collection. If If capped is true, then you need to specify this field also.
maxnumber(Optional) Specifies the maximum number of documents allowed in the capped collection.

While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

EXAMPLES:

Basic syntax of createCollection() method without options is as follows

>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>


You can check the created collection by using the command show collections

>show collections
mycollection
system.indexes


Following example shows the syntax of createCollection() method with few important options:

>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }
>


In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>


Drop Collection:

Basic syntax of drop() command is as follows

db.COLLECTION_NAME.drop()

Example:

>db.mycollection.drop()
true
>

MongoDB Environment

To start a mongodb, following are the commands:

Command used to start the mongod.exe is running for connections,

C:\Mongo\mongodb-win32-x86_64-2008plus-2.4.8\bin>mongod.exe --dbpath "c:\Mongo\data"

Command to run the mongodb,

C:\Mongo\mongodb-win32-x86_64-2008plus-2.4.8\bin>mongo.exe

MongoDB Introduction



  •  MongoDB is an open-source document database, and leading NoSQL database. MongoDB is written in      c++.
  • MongoDB is a cross-platform, document oriented database that provides, high performance, high  availability, and easy scalability. MongoDB works on concept of collection and document.
  • Below given table shows the relationship of RDBMS terminology with MongoDB



RDBMSMongoDB
DatabaseDatabase
TableCollection
Tuple/RowDocument
columnField
Table JoinEmbedded Documents
Primary KeyPrimary Key (Default key _id provided by mongodb itself)
Database Server and Client
Mysqld/Oraclemongod
mysql/sqlplusmongo


  • Any relational database has a typical schema design that shows number of tables and the relationship between these tables. While in MongoDB there is no concept of relationship


Advantages of MongoDB over RDBMS


  • Schema less : MongoDB is document database in which one collection holds different different documents. Number of fields, content and size of the document can be differ from one document to another.
  • Structure of a single object is clear
  • No complex joins
  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL
  • Tuning
  • Ease of scale-out: MongoDB is easy to scale
  • Conversion / mapping of application objects to database objects not needed
  • Uses internal memory for storing the (windowed) working set, enabling faster access of data


Why should use MongoDB


  • Document Oriented Storage : Data is stored in the form of JSON style documents
  • Index on any attribute
  • Replication & High Availability
  • Auto-Sharding
  • Rich Queries
  • Fast In-Place Updates
  • Professional Support By MongoDB


Where should use MongoDB?


  • Big Data
  • Content Management and Delivery
  • Mobile and Social Infrastructure
  • User Data Management
  • Data Hub



Monday, 7 October 2013

InfoSphere DataStage


Integrate all types of data on distributed and mainframe platforms

IBM® InfoSphere® DataStage® integrates data across multiple systems using a high performance parallel framework, and it supports extended metadata management and enterprise connectivity. The scalable platform provides more flexible integration of all types of data, including big data at rest (Hadoop-based) or in motion (stream-based), on distributed and mainframe platforms.

InfoSphere DataStage provides these features and benefits:

·         Powerful, scalable ETL platform—supports the collection, integration and transformation of large volumes of data, with data structures ranging from simple to complex.
·         Support for big data and Hadoop—enables you to directly access big data on a distributed file system, and helps clients more efficiently leverage new data sources by providing JSON support and a new JDBC connector.

·         Near real-time data integration—as well as connectivity between data sources and applications.

·         Workload and business rules management—helps you optimize hardware utilization and prioritize mission-critical tasks.
·         Ease of use—helps improve speed, flexibility and effectiveness to build, deploy, update and manage your data integration infrastructure.

·         Rich support for DB2Z and DB2 for z/OS—including data load optimization for DB2Z and balanced optimization for DB2 on z/OS

Thursday, 3 October 2013

Diff b/w Rest and Soap

  • SOAP stands for Simple Object Access Protocol. REST stands for REpresentational State Transfer.
  • SOAP is a XML based messaging protocol and REST is not a protocol but an architectural style.
  • SOAP has a standard specification but there is none for REST.
  • Whole of the web works based on REST style architecture. Consider a shared resource repository and consumers access the resources.
  • Even SOAP based Web service can be implemented in RESTful style. REST is a concept that does not tie with any protocols.
  • SOAP is distributed computing style and REST is web style (web is also a distributed computing model).
  • REST messages should be self-contained and should help consumer in controlling the interaction between provider and consumer(example, links in message to decide the next course of action). But SOAP doesn’t has any such requirements.
  • REST does not enforces message format as XML or JSON or etc. But SOAP is XML based message protocol.
  • REST follows stateless model. SOAP has specifications for stateful implementation as well.
  • SOAP is strongly typed, has strict specification for every part of implementation. But REST gives the concept and less restrictive about the implementation.
  • Therefore REST based implementation is simple compared to SOAP and consumer understanding.
  • SOAP uses interfaces and named operations to expose business logic. REST uses (generally) URI and methods like (GET, PUT, POST, DELETE) to expose resources.
  • SOAP has a set of standard specifications. WS-Security is the specification for security in the implementation. It is a detailed standard providing rules for security in application implementation. Like this we have separate specifications for messaging, transactions, etc. Unlike SOAP, REST does not has dedicated concepts for each of these. REST predominantly relies on HTTPS.
  • Above all both SOAP and REST depends on design and implementation of the application.

Web Service : Rest vs Soap (Detailed)

Web services overview

A Web service, in very broad terms, is a method of communication between two applications or electronic devices over the World Wide Web (WWW). Web services are of two kinds: Simple Object Access Protocol (SOAP) and Representational State Transfer (REST).

SOAP defines a standard communication protocol (set of rules) specification for XML-based message exchange. SOAP uses different transport protocols, such as HTTP, JMS and SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxies without any modifications to the SOAP protocol. SOAP can sometimes be slower than middleware technologies like CORBA or ICE due to its verbose XML format.

REST describes a set of architectural principles by which data can be transmitted over a standardized interface (such as HTTP). REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource.

REST vs. SOAP

Multiple factors need to be considered when choosing a particular type of Web service, that is between REST and SOAP. The table below breaks down the features of each Web service based on personal experience.

REST

The RESTful Web services are completely stateless. This can be tested by restarting the server and checking if the interactions are able to survive.
Restful services provide a good caching infrastructure over HTTP GET method (for most servers). This can improve the performance, if the data the Web service returns is not altered frequently and not dynamic in nature.
The service producer and service consumer need to have a common understanding of the context as well as the content being passed along as there is no standard set of rules to describe the REST Web services interface.
REST is particularly useful for restricted-profile devices such as mobile and PDAs for which the overhead of additional parameters like headers and other SOAP elements are less.
REST services are easy to integrate with the existing websites and are exposed with XML so the HTML pages can consume the same with ease. There is hardly any need to refactor the existing website architecture. This makes developers more productive and comfortable as they will not have to rewrite everything from scratch and just need to add on the existing functionality.
REST-based implementation is simple compared to SOAP.


SOAP

The Web Services Description Language (WSDL) contains and describes the common set of rules to define the messages, bindings, operations and location of the Web service. WSDL is a sort of formal contract to define the interface that the Web service offers.
SOAP requires less plumbing code than REST services design, (i.e., transactions, security, coordination, addressing, trust, etc.) Most real-world applications are not simple and support complex operations, which require conversational state and contextual information to be maintained. With the SOAP approach, developers need not worry about writing this plumbing code into the application layer themselves.
SOAP Web services (such as JAX-WS) are useful in handling asynchronous processing and invocation.
SOAP supports several protocols and technologies, including WSDL, XSDs, SOAP, WS-Addressing


In a nutshell, when you're publishing a complex application program interface (API) to the outside world, SOAP will be more useful. But when something with a lower learning curve, and with lightweight and faster results and simple transactions (i.e., CRUD operations) is needed, goes to REST.


Foe example web service creation:
http://javapapers.com/web-service/soap-web-service-introduction/

Web Service : Rest vs Soap

A Web service is a method of communication between two electronic devices over World Wide Web.

Web services are of two kinds: Simple Object Access Protocol (SOAP) and Representational State Transfer (REST).


REST is almost always going to be faster. The main advantage of SOAP is that it provides a mechanism for services to describe themselves to clients, and to advertise their existence.

REST is much more lightweight and can be implemented using almost any tool, leading to lower bandwidth and shorter learning curve. However, the clients have to know what to send and what to expect.

In general, When you're publishing an API to the outside world that is either complex or likely to change, SOAP will be more useful. Other than that, REST is usually the better option.

Thursday, 5 September 2013

Storage Tools Typically used in Big- Data


What is Big data!! It’s nothing but a collection of complex data which is difficult to process with the existing tools. The size of data ranges forms few dozen terabytes to many petabytes of data in a single data set. This data can be posts to social media sites, digital pictures and videos or any other information

Apache Hadoop is a very popular solution Big Data .For the storage of Big data we use different kind of storage like S3, Hadoop Distributed File System (HDFS)
Amazon S3 filesystem.

Amazon S3 filesystem


What is S3??

Amazon S3 (Simple Storage Service) is an online file storage web service (Internet hosting service specifically designed to host user files.) offered by Amazon Web Services. Apache Hadoop file systems can be hosted on S3, alsoTumblr, Formspring, Pinterest, and Posterous images are hosted on the S3 servers.

S3 stores arbitrary objects (computer files,) up to 5 terabytes in size. This are stored in the form of buckets. It can store data from web applications to media files and we can retrieve from anywhere in Web.


Hadoop Distributed File System


The Hadoop Distributed File System (HDFS) is a portable file system built for the Hadoop framework.
HDFS is to store very large amount of data by sharing the storage and computation across many servers. HDFS stores large files with ideal file size is a multiple of 64 MB
Below are some of the organizations that are using Hadoop.

Facebook
Yahoo
Amazon.com
LinkedIn
StumbleUpon
Twitter
Google and many more companies…

Monday, 12 August 2013

Tuesday, 9 July 2013

Oracle: Cursors

A cursor is a mechanism by which you can assign a name to a "select statement" and manipulate the information within that SQL statement.

Oracle/PLSQL: Declare a Cursor

A cursor is a SELECT statement that is defined within the declaration section of your PLSQL code. We'll take a look at three different syntaxes for cursors.

Cursor without parameters (simplest)

The basic syntax for a cursor without parameters is:

CURSOR cursor_name
IS
  SELECT_statement;

Cursor with parameters

The basic syntax for a cursor with parameters is:

CURSOR cursor_name (parameter_list)
IS
  SELECT_statement;

Oracle/PLSQL: OPEN Statement

Once you've declared your cursor, the next step is to open the cursor.

The basic syntax to OPEN the cursor is:

OPEN cursor_name;

Oracle/PLSQL: FETCH Statement

The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that some type of operation can be performed on the data. After declaring and opening your cursor, the next step is to FETCH the rows from your cursor.

The basic syntax for a FETCH statement is:

FETCH cursor_name INTO <list of variables>;

Oracle/PLSQL: CLOSE Statement

The final step of working with cursors is to close the cursor once you have finished using it.

The basic syntax to CLOSE the cursor is:

CLOSE cursor_name;

Oracle: Transactions

We've divided Transactions into the following topics:

Commit
Rollback
Set Transaction
Lock Table


Oracle/PLSQL: Commit

The syntax for the COMMIT statement is:

COMMIT [WORK] [COMMENT text];

The Commit statement commits all changes for the current session. Once a commit is issued, other users will be able to see your changes.

Oracle/PLSQL: Rollback

The syntax for the ROLLBACK statement is:

ROLLBACK [WORK] [TO [SAVEPOINT] savepoint_name];

The Rollback statement undoes all changes for the current session up to the savepoint specified. If no savepoint is specified, then all changes are undone.

Thursday, 4 July 2013

Oracle: Grant/Revoke Privileges example

You can grant users various privileges to tables. These privileges can be any combination of select, insert, update, delete, references, alter, and index

To view the grant permission of all tables:

select *from user_tab_privs;

Grant permission:

grant select, insert on sales to test with grant option;

here.,
tiara-Grantor
sales-table name
test-Grantee

Revoke Permission:

revoke all on sales from test;

Login in as "test" user:

To view the grantor tables:

select *from tiara.sales;

Insert values in grantor tables:

insert into tiara.sales values(41411,'Ganesh','Chennai','Tamilnadu',444);

Tuesday, 2 July 2013

Oracle: Function

Table Creation:

create table ebbill(cusno number,cus_name varchar2(20),init_read number(5),cur_read number(5),category varchar2(20));

alter table ebbill add total number(5);

Creating Function

create or replace function fun(i number,j number)
return number is s number;
begin
s:=i-j;
return s;
end;

Calling a function

declare
tno ebbill.cusno%type;
tname ebbill.cus_name%type;
initial ebbill.init_read%type;
current ebbill.cur_read%type;
category ebbill.category%type;
t number(6,2);
cursor cc is 
select cusno,cus_name,init_read,cur_read,category from ebbill;
begin
open cc;
if  cc%isopen then
loop
fetch cc into tno,tname,initial,current,category;
exit when cc%notfound;
if cc%found then
t:=fun(current,initial);

update ebbill set total=t where tno=ebbill.cusno;
end if;
end loop;
end if;
close cc;
end;
/

Monday, 1 July 2013

Oracle: Stored Procedure

Before executing a procedure in "Run SQL Command Line" we must execute the below query to display the server result in screen.
                                                 SQL> set serveroutput on; 

Example 1:

Stored Procedure

create procedure addn(a in number,b in number,c in out number)
is
begin
c:=a+b;
end;
/

Calls from PL/SQL

declare
a integer:=10;
b integer:=10;
c integer;
begin
addn(a,b,c);
dbms_output.put_line(c);
end;
/

Example 2:

Stored Procedure

create or replace procedure findmax(a in number,b in number,c in out number)
is
begin
if a>b then
c:=a;
else
c:=b;
end if;
end;
/

Calls from PL/SQL

declare
a integer:=10;
b integer:=21;
c integer;
begin
findmax(a,b,c);
dbms_output.put_line(c);
end;
/

Example 3:

Table SQL

CREATE TABLE DBUSER ( 
  USER_ID       NUMBER (5)    NOT NULL, 
  USERNAME      VARCHAR2 (20)  NOT NULL, 
  CREATED_BY    VARCHAR2 (20)  NOT NULL, 
  CREATED_DATE  DATE          NOT NULL, 
  PRIMARY KEY ( USER_ID ) 
 )

Insert Query

INSERT INTO DBUSER VALUES(11145,'Manoj','Admin',sysdate);

Stored Procedure

CREATE OR REPLACE PROCEDURE getDBUSERByUserId(
  p_userid IN DBUSER.USER_ID%TYPE,
  o_username OUT DBUSER.USERNAME%TYPE,
  o_createdby OUT  DBUSER.CREATED_BY%TYPE,
  o_date OUT DBUSER.CREATED_DATE%TYPE)
IS
BEGIN
  SELECT USERNAME , CREATED_BY, CREATED_DATE
  INTO o_username, o_createdby,  o_date 
  FROM  DBUSER WHERE USER_ID = p_userid;
END;
/

Calls from PL/SQL
DECLARE
   o_username DBUSER.USERNAME%TYPE;
   o_createdby DBUSER.CREATED_BY%TYPE;
   o_date DBUSER.CREATED_DATE%TYPE;
BEGIN
   getDBUSERByUserId(11144,o_username,o_createdby,o_date);
   DBMS_OUTPUT.PUT_LINE('username :  ' || o_username);
   DBMS_OUTPUT.PUT_LINE('createdby :  ' || o_createdby);
   DBMS_OUTPUT.PUT_LINE('createddate :  ' || o_date);
END;
/

Oracle: Sequences (Autonumber)

In Oracle, you can create an autonumber field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key.

The syntax for a sequence is:

CREATE SEQUENCE sequence_name
  MINVALUE value
  MAXVALUE value
  START WITH value
  INCREMENT BY value
  CACHE value;

For example:

CREATE SEQUENCE supplier_seq
  MINVALUE 1
  MAXVALUE 999999999999999999999999999
  START WITH 1
  INCREMENT BY 1
  CACHE 20;

This would create a sequence object called supplier_seq. The first sequence number that it would use is 1 and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cache up to 20 values for performance.

If you omit the MAXVALUE option, your sequence will automatically default to:

MAXVALUE 999999999999999999999999999

So you can simplify your CREATE SEQUENCE command as follows:

CREATE SEQUENCE supplier_seq
  MINVALUE 1
  START WITH 1
  INCREMENT BY 1
  CACHE 20;

Now that you've created a sequence object to simulate an autonumber field, we'll cover how to retrieve a value from this sequence object. To retrieve the next value in the sequence order, you need to use nextval.

For example:

supplier_seq.nextval

This would retrieve the next value from supplier_seq. The nextval statement needs to be used in an SQL statement. For example:

INSERT INTO suppliers
(supplier_id, supplier_name)
VALUES
(supplier_seq.nextval, 'Kraft Foods');

This insert statement would insert a new record into the suppliers table. The supplier_id field would be assigned the next number from the supplier_seq sequence. The supplier_name field would be set to Kraft Foods.


Note:

The CACHE option specifies how many sequence values will be stored in memory for faster access.

The downside of creating a sequence with a cache is that if a system failure occurs, all cached sequence values that have not be used, will be "lost". This results in a "gap" in the assigned sequence values. When the system comes back up, Oracle will cache new numbers from where it left off in the sequence, ignoring the so called "lost" sequence values.

NOCACHE means that none of the sequence values are stored in memory. This option may sacrifice some performance, however, you should not encounter a gap in the assigned sequence values.

Oracle: Change a user's password

To change a user's password in Oracle, you need to execute the alter user command.

The syntax for changing a password is:

alter user user_name identified by new_password;


  • user_name is the user whose password you wish to change.
  • new_password is the new password to assign.


For Example

If you wanted to reset the password for a user named smithj, and you wanted to set the new password to autumn, you would run the following command:

alter user smithj identified by autumn;

Oracle: Grant/Revoke Privileges

Grant Privileges on Tables

You can grant users various privileges to tables. These privileges can be any combination of select, insert, update, delete, references, alter, and index. Below is an explanation of what each privilege means.

Description


  1. Select Ability to query the table with a select statement.
  2. Insert Ability to add new rows to the table with the insert statement.
  3. Update Ability to update rows in the table with the update statement.
  4. Delete Ability to delete rows from the table with the delete statement.
  5. References Ability to create a constraint that refers to the table.
  6. Alter         Ability to change the table definition with the alter table statement.
  7. Index Ability to create an index on the table with the create index statement.

The syntax for granting privileges on a table is:

grant privileges on object to user;

For example, if you wanted to grant select, insert, update, and delete privileges on a table called suppliers to a user name smithj, you would execute the following statement:

grant select, insert, update, delete on suppliers to smithj;

You can also use the all keyword to indicate that you wish all permissions to be granted. For example:

grant all on suppliers to smithj;

If you wanted to grant select access on your table to all users, you could grant the privileges to the public keyword. For example:

grant select on suppliers to public;

Revoke Privileges on Tables

Once you have granted privileges, you may need to revoke some or all of these privileges. To do this, you can execute a revoke command. You can revoke any combination of select, insert, update, delete, references, alter, and index.

The syntax for revoking privileges on a table is:

revoke privileges on object from user;

For example, if you wanted to revoke delete privileges on a table called suppliers from a user named anderson, you would execute the following statement:

revoke delete on suppliers from anderson;

If you wanted to revoke all privileges on a table, you could use the all keyword. For example:

revoke all on suppliers from anderson;

If you had granted privileges to public (all users) and you wanted to revoke these privileges, you could execute the following statement:

revoke all on suppliers from public;

Grant Privileges on Functions/Procedures

When dealing with functions and procedures, you can grant users the ability to execute these functions and procedures. The Execute privilege is explained below:

Description

Execute
      1. Ability to compile the function/procedure.
      2. Ability to execute the function/procedure directly.

The syntax for granting execute privileges on a function/procedure is:

grant execute on object to user;

For example, if you had a function called Find_Value and you wanted to grant execute access to the user named smithj, you would execute the following statement:

grant execute on Find_Value to smithj;

If you wanted to grant all users the ability to execute this function, you would execute the following:

grant execute on Find_Value to public;


Revoke Privileges on Functions/Procedures

Once you have granted execute privileges on a function or procedure, you may need to revoke these privileges from a user. To do this, you can execute a revoke command.

The syntax for the revoking privileges on a function or procedure is:

revoke execute on object from user;

If you wanted to revoke execute privileges on a function called Find_Value from a user named anderson, you would execute the following statement:

revoke execute on Find_Value from anderson;

If you had granted privileges to public (all users) and you wanted to revoke these privileges, you could execute the following statement:

revoke execute on Find_Value from public;

Thursday, 27 June 2013

Oracle Useful Queries

SQL: UNION Query

The SQL UNION query allows you to combine the result sets of 2 or more SQL SELECT statements. It removes duplicate rows between the various SELECT statements.
Each SQL SELECT statement within the UNION query must have the same number of fields in the result sets with similar data types.

The syntax for the SQL UNION query is:

select field1, field2, . field_n from tables
UNION
select field1, field2, . field_n from tables;

SQL UNION Query - Returns single field example
The following is an example of the SQL UNION query that returns one field from multiple SELECT statements (and both fields have the same data type):

select supplier_id from suppliers
UNION
select supplier_id from orders;

In this SQL UNION query example, if a supplier_id appeared in both the suppliers and orders table, it would appear once in your result set. The SQL UNION query removes duplicates. If you do notwish to remove duplicates, try using the SQL UNION ALL query.


SQL: UNION ALL Query

The SQL UNION ALL query allows you to combine the result sets of 2 or more SELECT statements. It returns all rows from the query (even if the row exists in more than one of the SELECT statements).
Each SQL SELECT statement within the SQL UNION ALL query must have the same number of fields in the result sets with similar data types.

The syntax for the SQL UNION ALL query is:

select field1, field2, ... field_n from tables
UNION ALL
select field1, field2, ... field_n from tables;

SQL UNION ALL Query - Returns single field example
The following is an example of the SQL UNION ALL query that returns one field from multiple SELECT statements (and both fields have the same data type):

select supplier_id from suppliers
UNION ALL
select supplier_id from orders;

This SQL UNION ALL query would return a supplier_id multiple times in your result set if the supplier_id appeared in both the suppliers and orders table. The SQL UNION ALL query does not remove duplicates. If you wish to remove duplicates, try using the SQL UNION query.


SQL: INTERSECT Query

The SQL INTERSECT query allows you to return the results of 2 or more "select" queries. However, it only returns the rows selected by all queries. If a record exists in one query and not in the other, it will be omitted from the INTERSECT results.
Each SQL statement within the SQL INTERSECT query must have the same number of fields in the result sets with similar data types.

The syntax for the SQL INTERSECT query is:

select field1, field2, . field_n from tables
INTERSECT
select field1, field2, . field_n from tables;

SQL INTERSECT Query - Single field example
The following is an example of an SQL INTERSECT query that has one field with the same data type:

select supplier_id from suppliers
INTERSECT
select supplier_id from orders;

In this SQL INTERSECT query example, if a supplier_id appeared in both the suppliers and orders table, it would appear in your result set.



SQL: MINUS Query

The SQL MINUS query returns all rows in the first SQL SELECT statement that are not returned in the second SQL SELECT statement.
Each SQL SELECT statement within the SQL MINUS query must have the same number of fields in the result sets with similar data types.

The syntax for the SQL MINUS query is:

select field1, field2, ... field_n from tables
MINUS
select field1, field2, ... field_n from tables;

SQL MINUS Query - Single field example
The following is an example of an SQL MINUS query that has one field with the same data type:

select supplier_id from suppliers
MINUS
select supplier_id from orders;

This SQL Minus query example returns all supplier_id values that are in the suppliers table and not in the orders table. What this means is that if a supplier_id value existed in the suppliers table and also existed in the orders table, the supplier_id value would not appear in this result set.

Tuesday, 25 June 2013

Oracle: DUAL Table


The Oracle DUAL table

dual is a table which is created by oracle along with the data dictionary. It consists of exactly one column whose name is dummy and one record. The value of that record is X.


SQL> desc dual
 Name                    Null?    Type
 ----------------------- -------- ----------------
 DUMMY                            VARCHAR2(1)

SQL> select * from dual;

D
-
X


The owner of dual is SYS but dual can be accessed by every user.

As dual contains exactly one row (unless someone fiddled with it), it is guaranteed to return exactly one row in select statements. Therefor, dual is the prefered table to select a pseudo column (such as sysdate
select sysdate from dual

Although it is possible to delete the one record, or insert additional records, one really should not do that!.

Sunday, 23 June 2013

SOAP UI and Groovy Script

SoapUI is an open source web service testing application for service-oriented architectures (SOA). Its functionality covers web serviceinspection, invoking, development, simulation and mocking, functional testing, load and compliance testing.

Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of PythonRuby,Perl, and Smalltalk.It can be used as a scripting language for the Java Platform, is dynamically compiled to Java Virtual Machine (JVM) bytecode, and interoperates with other Java code and libraries


DBT - Models

Models are where your developers spend most of their time within a dbt environment. Models are primarily written as a select statement and ...