MY mENU


Showing posts with label Oracle. Show all posts
Showing posts with label Oracle. Show all posts

Tuesday, 29 January 2013

Oracle InterViewQusetions 11-15

11. what is null value?
Null Value is neither zero nor it is a blank space. It is some unknown value which occupies 4 bytes of space of memory in SQL.

12. Define transaction?
A transaction is a sequence of SQL statements that Oracle Database treats as a single unit.

13. what is the difference between sql&oracle?
SQL is Stuctured Query Language.Oracle is a Database.SQL is used to write queries against Oracle DB.

14. What are different Oracle database objects?
TABLES
VIEWS
INDEXES
SYNONYMS
SEQUENCES
TABLESPACES

15. What is hash cluster?
A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk.

Oracle InterView Questions 6-10

6. What is the difference between clustered and a non-clustered index?
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
A Non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk.

7. What is a Table-space?
A database is divided into Logical Storage Unit called tablespace. A tablespace is used to grouped related logical structures together.

8. Why use materialized view instead of a table?
Materialized views are basically used to increase query performance since it contains results of a query. They should be used for reporting instead of a table for a faster execution.

9. What does ROLLBACK do?
ROLLBACK retracts any of the changes resulting from the SQL statements in the transaction.

10. Compare and contrast TRUNCATE and DELETE for a table?
Both the truncate and delete command have the desired outcome of getting rid of all the rows in a table. The difference between the two is that the truncate command is a DDL operation and just moves the high water mark and produces a now rollback. The delete command, on the other hand, is a DML operation, which will produce a rollback and thus take longer to complete.

Oracle InterView Questions

1.what is Oracle Table?
A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

2. What are Clusters?
Clusters are groups of one or more tables physically stores together to share common columns and are often used together.

3. What is an Index?
An Index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

4. What are the advantages of views?

  • Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.
  • Hide data complexity.
  • Simplify commands for the user.
  • Present the data in a different perspective from that of the base table
  • Store complex queries.

5. What are the various types of queries?
The types of queries are :

  • Normal Queries
  • Sub Queries
  • Co-related queries
  • Nested queries
  • Compound queries






Monday, 16 April 2012

Display Odd/ Even number of records


Odd number of records:


select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5


Even number of records:


select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6

Sunday, 15 April 2012

Display the number value in Words


SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp;


the output like,


SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty


If you want to add some text like, Rs. Three Thousand only.


SQL> select sal "Salary ",(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) "Sal in Words" from emp 
/


Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.

Saturday, 14 April 2012

Oracle cursor : Implicit & Explicit cursors


Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly declared.


Explicit Cursor attributes There are four cursor attributes used in Oracle
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN


Implicit Cursor attributes
Same as explicit cursor but prefixed by the word SQL: SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN


Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after executing SQL statements.


 2. All are Boolean attributes.

Friday, 13 April 2012

Display the records between two range


select rownum, empno, ename from emp where rowid in(select rowid from emp where rownum <=&upto minus select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7
ROWNUM EMPNO ENAME
--------- --------- ----------
1 7782 CLARK
2 7788 SCOTT
3 7839 KING
4 7844 TURNER

Thursday, 12 April 2012

How do I display row number with records?


To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum, ename from emp;
Output:
1 Scott
2 Millor
3 Jiyo
4 Smith

Wednesday, 11 April 2012

How do I eliminate the duplicate rows ?


SQL> delete from table_name where rowid not in (select max(rowid) from table group by
duplicate_values_field_name);
or
SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from
table_name tb where ta.dv=tb.dv);
Example.
Table Emp
Empno Ename
101      Scott
102       Jiyo
103      Millor
104      Jiyo
105      Smith
delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename = b.ename);
The output like,
Empno Ename
101      Scott
102      Millor
103      Jiyo
104     Smith

Friday, 16 March 2012

DataBase Interview Questions?

What do you understand by the terms clustered index and non-clustered index?
          When you create a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage space separate from the table data storage. Clustered and non-clustered indexes are stored as binary search tree (i.e. keep data sorted and has the average performance of O(log n) for delete, inserts, and search) structures with the leaf level nodes having the index key and it's row locator for a faster retrieval.

What is the difference between primary key and unique key?
    Both primary key and unique key enforce uniqueness of the column on which they are defined. But by default, a primary key creates a clustered index on the column, whereas a unique key creates a non clustered index by default. Another major difference is that, a primary key doesn't allow NULL values, but unique key allows a single NULL.

What are the pros and cons of an index?
PROS: If an index does not exist on a table, a table scan must be performed for each table referenced in a database query. The larger the table, the longer a table scan takes because a table scan requires each table row to be accessed sequentially. So, indexes can improve search performance, especially for the reporting requirements.

CONS: Excessive non-clustered indexes can consume additional storage space. Excessive non-clustered indexes can adversely impact performance of the INSERT, UPDATE, and DELETE statements as the indexes need to recreated after each of the above operation.So, it is essential to have a right balance based on the usage pattern.

What are the pros and cons of stored procedures?
PROS:pre-compiled and less network trips for faster performance,less susceptible to SQL injection attacks,more precise control over transactions and locking,can abstract complex data processing from application by acting as a facade layer.

CONS: There are chances of larger chunks of business logic and duplications creeping into stored procedures and causing maintenance issues. Writing and maintaining stored procedures is most often a specialized skill set that not all developers possess. This situation may introduce bottlenecks in the project development schedule.
  • Less portable.The stored procedures are specific to a particular database.
  • Scaling a database is much harder than scaling an application.
  • The application performance can be improved by caching the relevant data to reduce the network trips
when should stored procedures be used ?
Stored procedures are ideal when there is a complex piece of business logic that needs complex data logic to be performed involving a lot of database operations. If this logic is required in many different places, then store procedure makes even more sense. For example, batch jobs and complex report generation that performs lots of database operations.

when shouldn't stored procedures be used ?
When you are performing basic CRUD (Create, Read, Update, and Delete) operations. For example, in a Web application a user creates some data, read the created data, and then updates or deletes some of the created data. 

 How would you go about writing a stored procedure that needs to loop through a number of selected rows?
  You need to use a cursor. A cursor is basically a pointer to row by operation. For example, you can create a cursor by selecting a number of records into it. Then, you can fetch each row at a time and perform some operations like invoking another stored proc by passing the selected row value as an argument, etc. Once uou have looped through all the records, you need to close and deallocate the cursor. For example, the stored procedure below written in Sybase demonstrates the use of a cursor.

Drop the stored procedure if it already exists

IF OBJECT_ID('dbo.temp_sp') IS NOT NULL
BEGIN 
    DROP PROCEDURE dbo.temp_sp
IF OBJECT_ID('dbo.temp_sp') IS NOT NULL
PRINT '<<< FAILED DROPPING PROCEDURE dbo.temp_sp >>>'
ELSE
PRINT '<<< DROPPED PROCEDURE dbo.temp_sp >>>'
END

 Create the stored procedure that uses cursor
 
create proc temp_sp  as DECLARE @ADVISERID char(10) DECLARE advisers_cur cursor  for select adviser_id FROM tbl_advisers where adviser_id like 'Z%' -- select adviser_ids starting with 'Z' for read only 
open advisers_cur -- open the cursor
FETCH advisers_cur INTO @ADVISERID -- store value(s) from the cursor into declared variables
--@@sqlstatus is a sybase implcit variable that returns success/failure status of previous statement execution
WHILE (@@sqlstatus = 0)
BEGIN
SELECT @ADVISERID -- select the adviser_id stored into @ADVISERID
FETCH advisers_cur INTO @ADVISERID --store value(s) from the cursor into declared variables
END
close advisers_cur
deallocate cursor advisers_cur
go

Execute the stored procedure that uses a cursor

exec mydatabase..temp_sp

Why should you deallocate the cursors?
    You need deallocate the cursor to clear the memory space occupied by the cursor. This will enable the cleared space to be availble for other use.

 How would you go about copying bulk data in and out of a database? 
  The process is known as bulk copy, and the tools used for this are database specific. For example, in Sybase and SQLServer use a utility called "bcp", which allows you to export bulk data into comma delimited files, and then import the data in csv or any other delimited formats back into different database or table. In Oracle database, you achieve this via the SQLLoader. The DB2 database has IMPORT and LOAD command to achieve the same.

 What are triggers? what are the different types of triggers?
   Triggers are stored procedures that are stored in the database and implicitly run, or fired, when something like INSERT, UPDATE , or DELETE happens to that table. There are 3 types of DML triggers that happens before or after events like INSERT, UPDATE, or DELETE. There could be other database specific triggers.

When to not use a trigger, and when is it appropriate to use a trigger?
The database triggers need to be used very judiciously as they are executed every time an event like insert, update or delete occur. Don't use a trigger where database constraints like unique constraint, not null, primary key, check constraints, etc can be used to check for data validity.
triggers are recursive.

Where to use a trigger?
Maintaining complex integrity constraints (referential integrity) or business rules where other types of constraints cannot be used. Because triggers are executed as part of the SQL statement (and its containing transaction) causing the row change event, and because the trigger code has direct access to the changed row, you could in theory use them to correct or reject invalid data.
Auditing information in a table by recording the changes. Some tables are required to be audited as part of the non-functional requirement for changes.
Automatically signaling other programs that action needs to take place when changes are made to a table.
Collecting and maintaining aggregate or statistical data. 

 If one of your goals is to reduce network loads, how will you about achieving it?
you can use materialized views to distribute your load from a master site to other regional sites. Instead of the entire company accessing a single database server, user load is distributed across multiple database servers with the help of multi-tier materialized views. This enables you to distribute the load to materialized view sites instead of master sites. To decrease the amount of data that is replicated, a materialized view can be a subset of a master table or master materialized view. Write stored procedures to minimize network round trips.

Carefully crafting your SQL to return only required data. For example Don't do select * from tbl_mytable. Instead, specify the columns you are interested in. For example, select firstname, surname from tbl_mytable.

You can set the fetch size to an appropriate value to get the right balance between data size and number of network trips made. Q. What are the other uses of materialized views?
Materialized view is one of the key SQL tuning approaches to improve performance by allowing you to pre-join complex views and pre-compute summaries for super-fast response time.

Materialized views are schema objects that can be used to summarize, precompute, replicate, and distribute data. E.g. to construct a data warehouse, reporting, etc. A materialized view can be either read-only, updatable, or writable. Users cannot perform data manipulation language (DML) statements on read-only materialized views, but they can perform DML on updatable and writable materialized views.

A materialized view provides indirect access to table data by storing the results of a query in a separate schema object. Unlike an ordinary view, which does not take up any storage space or contain any data. You can define a materialized view on a base table, partitioned table or view and you can define indexes on a materialized view.

 If you are working with a legacy application, and some of the database tables are not properly designed with the appropriate constraints, how will you go about rectifying the situation?
  One possible solution is to write triggers to perform the appropriate validation. Here is an example of an insert trigger.
CREATE TRIGGER TableA_itrig
ON TableA FOR INSERT
AS
BEGIN
IF @@rowcount = 0
RETURN
IF NOT EXISTS
(
SELECT *
FROM inserted ins, TableB ol
WHERE ins.code = ol.code
)
BEGIN
RAISERROR 20001, "The associated object is not found"
ROLLBACK TRAN
RETURN
END
END

If you are working on a new application that requires stringent auditing requirements, how would you go about achieving it?
Since it is a new application, there are a number of options as listed below. The application is designed from the beginning so that all changes are logged either synchronously or asynchronously. Asynchronously means publishing the auditing messages to a queue or topic, and a separate process will receive these messages and write a database or flat file. All data changes go through a data access layer of the application which logs all changes. The database is constructed in such a way that logging information is included in each table, perhaps set via a trigger. This approach may adversely impact performance when inserts and updates are very frequent.

What if you have to work with an existing legacy application?
 Use triggers.

Wednesday, 7 March 2012

Constraints in Oracle

Constraints:
Data integrity of the database must be maintained. In order to ensure data has integrity we have to implement certain rules or constraints. As these constraints are used to maintain integrity they are called as integrity constraints.
Constraints can be given at two different levels. If the constraint is related to a single column the constraint is given at the column level otherwise constraint is to be given at the table level. Base on the where a constraint is given, constraint are of two types:
  1. Column Constraints
  2. Table Constraints
Column Constraint:
A constraint given at the column level is called as Column Constraint. It defines a rule for a single column. It cannot refer to column other than the column at which it is defined. A typical example is PRIMARY KEY constraint when a single column is the primary key of the table.

Table Constraint:
A constraint given at the table level is called as Table Constraint. It may refer to more than one column of the table. A typical example is PRIMARY KEY constraint that is used to define composite primary key. A column level constraint can be given even at the table level, but a constraint that deals with more than one column must be given only at the table level. The following is the syntax of CONSTRAINT clause used with CREATE TABLE and ALTER TABLE commands.

[CONSTRAINT constraint] { [NOT] NULL | {UNIQUE | PRIMARY KEY} | REFERENCES [schema.] table [(column)] [ON DELETE CASCADE] | CHECK (condition) }

The following is the syntax of table constraint.

[CONSTRAINT constraint] { {UNIQUE | PRIMARY KEY} (column [,column] ...) | FOREIGN KEY (column [,column] ...) REFERENCES [schema.] table [(column [,column] ...)] [ON DELETE CASCADE] | CHECK (condition) }

The main difference between column constraint and table constraint is that in table constraint we have to specify the name of the column for which the constraint is defined whereas in column constraint it is not required as constraint is given on immediately after the column.



Creating Integrity Constraints
In the following few sections we will see how to integrity constraints.
NOT NULL Constraint:
Used to prevent any null value from entering into column. This is automatically defined forcolumn with PRIMARY KEY constraint.
CREATE TABLE COURSES( ...,name varchar2(20) CONSTRAINT courses_name_nn NOT NULL,.. );
CONSTRAINT option is used to given a name to constraint. The convention followed here is TABLENAME_COLUMN_TYPE.


PRIMARY KEY Constraint This constraint is used to define the primary key of the table. A primary key is used to uniquely identify rows in a table. There can be only one primary key in a table. It may consist of more than one column. If primary key is consisting of only one column, it can be given as column constraints otherwise it is to be given as table constraint. 
Note: You have to use table constraint to define composite primary key. Oracle does the following for the column that has PRIMARY KEY constraint .Creates a unique index to enforce uniqueness. 
CREATE TABLE COURSES( ccode varchar2(5) CONSTRAINT courses_pk PRIMARY KEY,... );
The following example shows how to define composite primary key using PRIMARY KEY constraint at the table level.
CREATE TABLE COURSE_FACULTY( ...,CONSTRAINT COURSE_FACULTY_PK PRIMARY KEY (ccode,faccode) );


UNIQUE Constraint Enforces uniqueness in the given column(s). Oracle automatically creates a unique index for this column.
CREATE TABLE courses ( ... ,name varchar2(20) CONSTRAINT courses_name_u UNIQUE, ... );
If two or more columns collective should be unique then UNIQUE constraint must be given at the table level.


FOREIGN KEY Constraint A foreign key is used to join the child table with parent table. FOREIGN KEY constraint is used to provide referential integrity, which makes sure that the values of a foreign key are derived from parent key. It can be defined either at the table level or at the column level. If a foreign key is defined on the column in child table then Oracle does not allow the parent row to be deleted, if it contains any child rows. However, if ON DELETE CASCADE option is given at the time of defining foreign key, Oracle deletes all child rows while parent row is being deleted.
CREATE TABLE course_faculty (ccode varchar2(5) CONSTRAINT course_faculty_ccode_fk REFERENCES courses(ccode), ... );
Note: When the name of the column in the referenced table is same as the foreign key then column need not be given after the table name. It means REFERENCES courses in the above example will suffice.
Table level constraint is used when foreign key is a composite foreign key.


ON DELETE CASCADE option As mentioned earlier, after a foreign key is defined, Oracle will NOT allow any parent row to be deleted if it has dependent rows in the child table. For example, if CCODE in COURSE_FACULTY table is defined as foreign key referencing CCODE column of COURSES table then it is NOT possible to delete rows from COURSES table if dependent rows exists in COURSE_FACULTY table. However, by using ON DELETE CASCADE it is possible to delete all child rows while parent row is being deleted.
CREATE TABLE course_faculty (ccode varchar2(5)CONSTRAINT course_faculty_ccode_fk REFERENCES courses(ccode) ON DELETE CASCADE, ..  );


CHECK Constraint Defines the condition that should be satisfied before insertion or updation is done.The condition used in CHECK constraint may NOT contain: A reference to pseudo column SYSDATE Subquery If it is given as column constraint, it can refer only to current column. But if it is given as table constraint, it can refer to more than one column of the table. In neither case it can refer to a column of other tables. The following example shows how to create CHECK constraint to make sure GRADE column of COURSE_FACULTY contains letters A, B and C only.
CREATE TABLE course_faculty( ..., grade char(1) CONSTRAINT course_faculty_grade_chk CHECK ( grade in (‘A’,’B’,’C’) ), ... );
The above CHECK constraint does not allow any other characters other than A, B and C. It must be noted that character comparison is always case sensitive. So to ignore case differences you can convert GRADE to uppercase before comparison made as follows:
CREATE TABLE course_faculty ( ..., grade char(1) CONSTRAINT course_faculty_grade_chk
CHECK ( upper(grade) in (‘A’,’B’,’C’) ), ... );
The following is an example of CHECK constraint at table level. The constraint makes sure the starting date (STDATE) of a batch is less than or equal to ending date (ENDDATE) of the batch.
CREATE TABLE batches ( ..., CONSTRAINT batches_dates_chk CHECK ( stdate <= enddate), );

SQL Operators


SQL Operators:
Apart from standard relational operators (= and >), SQL has some other operators that can
be used in conditions.

BETWEEN value-1 AND value-2 Checks whether the value is in the given range including the min and max values. This supports DATE type data also.The range is inclusive of the given values.

IN(list) Checks whether the value is matching with any one of the values given in the list. List contains values separated by comma(,). If the value is matching with any of the values given in the list then condition is taken as true.

LIKE pattern Checks whether the given string is matching with the given pattern.This operator is used to search for values when the exact value is not known. It selects rows that match the given pattern. The pattern can contain the following special characters.

IS NULL and IS NOT NULL Checks whether the value is null or not null.

To display the list of course where DURATION is in the range 20 to 25 days, enter:

select name from courses where duration between 20 and 25;
NAME
--------------------
Oracle database
C programming
Java Language

Note: BETWEEN.. AND is alternative to using >= and <= operators.

The following command will retrieve all courses where duration is either 20 or 30 days.

select name from courses where duration in (20,30);
NAME
--------------------
VB.NET
C programming

The same condition can be formed even without IN operator using logical operator OR as follows:
Select name from courses where duration = 20 or duration = 30;

However, it will be more convenient to user IN operator compared with multiple conditions compared with OR operator.

% Zero or more characters can take the place of %. _ (underscore) Any single character can take the place of underscore. But there must be one letter. To select the courses where the course name contains pattern .NET, enter:

select name,duration, fee from courses where name like '%.NET%'
NAME DURATION FEE
-------------------- --------- ---------
VB.NET 30 5500
ASP.NET 25 5000

The following example selects courses where second letter in the course code is “b” and column PREREQUISITE contains word “programming”.

select * from courses where ccode like '_b%' and prerequisite like '%programming%';

CCODE NAME DURATION FEE PREREQUISITE
----- -------------------- --------- --------- ------------------------
vbnet VB.NET 30 5500 Windows and programming

Remember LIKE operator is case sensitive. 

For example the following SELECT command will select all the courses where the column FEE is null.
select * from courses where fee is null;

Though Oracle provides NULL keyword, it cannot be used to check whether the value of a column is null. For example, the following condition will always be false as Oracle treats two null values as two different values.
select * from courses where fee = null;

The above command does NOT work as fee though contains null value will not be equal to NULL. SO, we must use IS NULL operator.

Selecting distinct values:
DISTINCT clause of SELECT command specifies only distinct values of the specified column must be selected. The following SELECT command will display only distinct course fee values from COURSES
table.
select distinct fee from courses;
FEE
---------
3500
4000
4500
5000
5500
Whereas the same query without DISTINCT clause will select the following. 
select fee from courses;
FEE
---------
4500
5500
3500
5000
4500
4000

Select Statement in Oracle


Select Statement:  SELECT command of SQL is used to retrieve data from one or more tables. It implements operators of relational algebra such as projection, and selection. The following is the syntax of SELECT command.

Syntax:

SELECT [DISTINCT | ALL] {* | table.* | expr } [alias ] [ {table}.*| expr } [alias ] ] ... FROM [schema.]object [, [schema.]object ] ... [WHERE condition] [ORDER BY {expr|position} [ASC |DESC]
[, {expr|position} [ASC | DESC]] ...]

schema is the name of the user whose table is being accessed. Schema prefix is not required if the table is in the current account. Schema prefix is required while we are accessing a table of some other account and not ours.

The following is an example of a basic SELECT command.

select * from courses;

CCODE    NAME     DURATION    FEE     PREREQUISITE
----- -------------------- --------- --------- -------------------------
ora             Oracledatabas      25          4500       Windows
vbnet          VB.NET             30           5500         Windows and programming

The simplest SELECT command contains the following:

Columns to be displayed. If * is given, all columns are selected.  The name of the table from where rows are to be retrieved.

Projection:
Projection is the operation where we select only a few columns out of the available columns.

The following is an example of projection.

select name,fee from courses;

NAME                FEE
-------------------- ---------
Oracle database   4500
VB.NET              5500
C programming     3500

Using expressions in SELECT command:
It is also possible to include expressions in the list of columns. For example, the following SELECT will display discount to be given for each course.

select name,fee, fee * 0.15 from courses;

NAME             FEE       FEE*0.15
-------------------- --------- ---------
Oracle database 4500      675
VB.NET            5500      825
C programming 3500       525

Column Alias:
The column heading of an expression will be the expression itself. However, as it may not be meaningful to have expression as the result of column heading, we can give an alias to the column so that alias is displayed as the column heading. The following example will use alias DISCOUNT for the expression FEE * 0.15.

select name, fee, fee * 0.15 DISCOUNT from courses
NAME               FEE     DISCOUNT
-------------------- --------- ---------
Oracle database   4500    675
VB.NET             5500     825
C programming   3500     525

ORDER BY clause:
It is possible to display the rows of a table in the required order using ORDER BY clause. It is used to sort rows on the given column(s) and in the given order at the time of retrieving rows. Remember, sorting takes place on the row that are retrieved and in no way affects the rows in the table. That means the order of the rows will remain unchanged.

Note: ORDER BY must always be the last of all clauses used in the SELECT command.

The following SELECT command displays the rows after sorting rows on course fee.

select name, fee from courses order by fee;

NAME               FEE
-------------------- ---------
Oracle database     4500
Java Language       4500

Note: Null values are placed at the end in ascending order and at the beginning in descending order.
The default order for sorting is ascending. Use option DESC to sort in the descending order. It is also possible to sort on more than one column. To sort rows of COURSES table in the ascending order of DURATION and descending order of FEE, enter:
select name, duration, fee from courses order by duration , fee desc;
NAME             DURATION    FEE
-------------------- --------- -         --------
Oracle database       25           4500
Java Language         25           4500

First, all rows are sorted in the ascending order of DURATION column. Then the rows that have same value in DURATION column will be further sorted in the descending order of FEE column.

Using column position:
Instead of giving the name of the column, you can also give the position of the column on which you want to sort rows. For example, the following SELECT sorts rows based on discount to be given to each course.
select name, fee, fee * 0.15 from courses order by 3;

NAME               FEE     FEE*0.15
-------------------- --------- ---------
Oracle database    4500    675
Java Language      4500    675

Note: Column position refers to position of the column in the selected columns and not the position of the column in the table. The above command uses column position in ORDER BY clause. Alternatively you can use column alias in ORDER BY clause as follows:
select name, fee, fee * 0.15 discount from courses order by discount;

NAME              FEE       DISCOUNT
-------------------- --------- ---------
Oracle database   4500    675
Java Language     4500    675

Selection:
It is possible to select only the required rows using WHERE clause of SELECT command. It implements selection operator of relational algebra. WHERE clause specifies the condition that rows must satisfy in order to be selected. The following example select rows where FEE is more than or equal to 5000.

select name, fee from courses where fee >= 5000
NAME                FEE
-------------------- ---------
VB.NET             5500
ASP.NET           5000
The following relational and logical operators are used to form condition of WHERE clause. Logical operators – AND, OR – are used to combine conditions. NOT operator reverses the result of the condition. If condition returns true, NOT will make the overall condition false. The following SELECT command displays the courses where duration is more than 15 days and course fee is less than 4000.

select * from courses where duration > 15 and fee < 4000;
CCODE NAME DURATION FEE PREREQUISITE
----- -------------------- --------- --------- -------------------
c C programming 20 3500 Computer Awareness
The following SELECT command retrieves the details of course with code ORA.
select * from courses where ccode = 'ora';
CCODE NAME DURATION FEE PREREQUISITE
----- -------------------- --------- --------- ----------------
ora Oracle database 25 4500 Windows

Note: When comparing strings, the case of the string must match. Lowercase letters are not equivalent to uppercase letters. 

Insert Command in Oracle


Insert command:

Inserting rows into a table
 SQL command INSERT is used to insert new row into the table. While inserting rows, you may enter value for each column of the table or selected columns. The following command inserts a row into COURSES table.


Syntax: insert into courses values('ora','Oracle database',25,4500,'Knowledge of Windows');


Note: After inserting the required row, issues COMMIT command to make sure the changes are made permanent.  Without COMMIT, rows that are inserted might be lost if there is any power failure. During insertion, character values are enclosed in single quotes. Unless otherwise specified we have to supply a value for each column of the table. If the value of any column is not known or available then you can give NULL as the value of the column. For example, the following insert will insert a new row with null value for PREREQUISITE column.

insert into courses values('c','C Programming',25,3000,null);

Note: INSERT command can insert only one row at a time. For multiple row, INSERT command must be issued for multiple times. DATE type values must be in the format DD-MON-YY or DD-MON-YYYY, where MON is the first three letters of the month (Jan, Feb). If only two digits are given for year then current century is used. For example, if you give 99 for year, Oracle will take it as 2099 as the current century is 2000. So it is important to remember this and give four digits if required. The following is the complete syntax for INSERT command.

INSERT INTO tablename [(columns list)] {VALUES (value-1,...) | subquery }


Inserting a row with selected columns:
It is possible to insert a new row by giving values only for a few columns instead of giving values for all the available columns. The following INSERT command will insert a new row only two values.

insert into courses(ccode,name) values ('odba','Oracle Database Administration');

The above command will create a new row in COURSES table with values for only two columns CCODE and NAME. The remaining columns will take NULL value or the default value, if the column is associated with default value.

DataTypes in Oracle


Datatypes:
Each column of the table contains the datatype and maximum length, if it is length is applicable. Datatype of the column specifies what type of data can be stored in the column. The datatype VARCHAR2 is to store strings that may have different number of characters, NUMBER is used to store numbers. The maximum length, which is given in parentheses after the datatype, specifies how many characters (or digits) the column can store at the most. For example, column VARCHAR2 (20) would mean it can store up to 20 characters.

Datatype Description:

VARCHAR2( len): Can store up to len number of characters. Each character would occupy one byte. Maximum width is 4000 characters.VARCHAR(len) Same as VARCHAR2. But use VARCHAR2 as Oracle might change the usage of VARCHAR in future releases. 

CHAR(len): Fixed length character data. If len is given then it can store up to len number of characters. Default width is 1. String is padded on the right with spaces until string is of len size. Maximum width is 2000.

NUMBER: Can store numbers up to 40 digits plus decimal point and sign. NUMBER (p ,s) P represents the maximum significant digits allowed. S is the number of digits on the right of the decimal point.

DATE: Can store dates in the range 1-1-4712 B.C to 31-12-4712AD.

LONG: Variable length character values up to 2 gigabytes. Only one LONG column is allowed per table. You cannot use LONG datatype in functions, WHERE clause of SELECT, in indexing and subqueries.
RAW and LONG RAW Equivalent to VARCHAR2 and LONG respectively, but used for storing byte-oriented or binary data such as digital sound or graphics images.

CLOB, BLOB, NCLOB Used to store large character and binary objects. Each can accommodate up to 4 gigabytes. 

BFILE Stores a pointer to an external file. The content of the file resides in the file system of the operation system. Only the name of the file is stored in the column.

ROWID Stores a unique number that is used by Oracle to uniquely identify each row of the table.

NCHAR (size) Same as CHAR, but supports national language.

NVARCHAR2 (size) Same as VARCHAR2, but supports national language.

Create Command IN DBMS


Creating a Table:
A Table is a collection of rows and columns. Data in relational model is stored in tables. Before a table is created the following factors of a table are to be finalized.

  1. What data table is supposed to store.
  2. The name of the table. It should depict the content of the table.
  3. What are the columns that table should contains
  4. The name, data type and maximum length of each column of the table.
  5. What are the rules to be implemented to main data integrity of the table.

The following is an example of creation of COURSES table.  The following CREATE TABLE command is used to create COURSES table.
SQL> create table COURSES ( ccode varchar2(5),name varchar2(30),duration number(3),fee number(5), prerequisite varchar2(100));
Table Created

Rules to be followed for names:
The following are the rules to be followed while naming an Oracle Object. These rulesare applicable for name of the table and column.

  1. The name must begin with a letter - A-Z or a-z.
  2. Letters, digits and special characters – underscore (_), $ and # are allowed.
  3. Maximum length of the name is 30 characters.
  4. It must not be an SQL reserved word.
  5. There should not be any other object with the same name in your account.
DESCRIBE:
You can display the structure of a table using SQL*PLUS command DESCRIBE. It displays then name, datatype and whether the column can store null value for each column of the table.

Syntax:  DESC[RIBE] objectname
Displays the column definitions for the specified object. The object may be a table, view,
synonym, function or procedure.
To display the structure of COURSES table, enter:

SQL> DESC COURSES
Name                           Null? Type
---------------------------------------------- -------- ----------
CCODE                    NOT NULL VARCHAR2(5)
NAME                       VARCHAR2(30)
DURATION                 NUMBER(3)
FEE                              NUMBER(5)
PREREQUISITE           VARCHAR2(100)

DESCRIBE is an SQL*Plus command and can be abbreviated to DESC.