+ All Categories
Home > Documents > Oracle sql material

Oracle sql material

Date post: 07-Aug-2015
Category:
Upload: prathap-kumar
View: 117 times
Download: 13 times
Share this document with a friend
31
SQL What is SQL SQL stands for Structured Query Language SQL lets you access and manipulate databases According to ANSI (American National Standards Institute), it is the standard language for relational database management systems What Can SQL do? SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views SQL Commands: SQL commands are instructions used to communicate with the database to perform specific task that work with data. SQL commands can be used not only for searching the database but also to perform various other functions like, for example, you can create tables, add data to tables, or modify data, drop the table, set permissions for users. SQL commands are grouped into four major categories depending on their functionality: Data Definition Language (DDL) CREATE, ALTER, DROP, RENAME, and TRUNCATE
Transcript

SQLWhat is SQL

SQL stands for Structured Query Language

SQL lets you access and manipulate databases

According to ANSI (American National Standards Institute), it is the standard language for relational database management systems

What Can SQL do?

SQL can execute queries against a database

SQL can retrieve data from a database

SQL can insert records in a database

SQL can update records in a database

SQL can delete records from a database

SQL can create new databases

SQL can create new tables in a database

SQL can create stored procedures in a database

SQL can create views in a database

SQL can set permissions on tables, procedures, and views

SQL Commands:

SQL commands are instructions used to communicate with the database to perform specific task that work with data. SQL commands can be used not only for searching the database but also to perform various other functions like, for example, you can create tables, add data to tables, or modify data, drop the table, set permissions for users. SQL commands are grouped into four major categories depending on their functionality:

Data Definition Language (DDL)

CREATE, ALTER, DROP, RENAME, and TRUNCATE

Data Manipulation Language (DML)

SELECT, INSERT, UPDATE, and DELETE

Transaction Control Language (TCL) 

COMMIT, ROLLBACK, and SAVEPOINT

Data Control Language (DCL)

GRANT and REVOKE

Data Definition Language (DDL):-

CREATE

The CREATE TABLE Statement is used to create tables to store data.

Syntax: -

CREATE TABLE table_name (column_name1 datatype, column_name2 datatype, ... column_nameN datatype);

table_name - is the name of the table. column_name1, column_name2.... - is the name of the columns datatype - is the datatype for the column like

For Example: If you want to create the employee table, the statement would be like,

CREATE TABLE employee ( id number(5), name char(20), dept char(10), age number(2), salary number(10), location char(10) );

In the below statement, temp_employee table is created with the same number of columns and datatype as employee table.

CREATE TABLE temp_employee SELECT * FROM employee; 

ALTER TABLE

Once a table is created in the database, there are many occasions where one may wish to change the structure of the table. In general, the SQL syntax for ALTER TABLE is,

Syntax :- ALTER TABLE "table_name“ [alter specification];

Add Column :- ALTER TABLE employee ADD gender char(1);

Modify Column :- ALTER TABLE employee MODIFY Location char(30);

Rename Column :- ALTER TABLE employee RENAME COLUMN id TO emp_id;

Drop Column :- ALTER TABLE employee DROP COLUMN age;

Drop Table

The drop table command is used to delete a table and all rows in the table.

Syntax:- drop table "tablename“

Eg:- drop table temp_employee;

Rename Table

The Rename table command is used to rename table name

Syntax:- RENAME TABLE “tbl_name” TO “new_tbl_name”;

Eg:- RENAME table employee TO employee_details;

Truncate Table

TRUNCATE TABLE statement to remove all rows from a table

Syntax:- TRUNCATE TABLE “tbl_name”

Eg:- TRUNCATE TABLE employee_details

Data Manipulation Language (DML):-

SELECT

SQL SELECT statement is used to query or retrieve data from a table in the database. A query may retrieve information from specified columns or from all of the columns in the table. To create a simple SQL SELECT Statement, you must specify the column(s) name and the table name. The whole query is called SQL SELECT Statement.

Syntax of SQL SELECT Statement:

SELECT column_list FROM table-name [WHERE Clause][GROUP BY clause][HAVING clause][ORDER BY clause];

table-name is the name of the table from which the information is retrieved.

column_list includes one or more columns from which data is retrieved.

The code within the brackets is optional.

Example: - SELECT name FROM employee;

SELECT * FROM employee;

INSERT

The INSERT Statement is used to add new rows of data to a table.We can insert data to a table in two ways,

1) Inserting specific column data directly to a table.

Syntax of SQL Insert Statement:

INSERT INTO TABLE_NAME [ (col1, col2, col3,...colN)] VALUES (value1, value2, value3,...valueN); 

Example of SQL Insert Statement

INSERT INTO employee (id, name, dept, age, salary location) VALUES (105, 'Sai', 'Aeronautics', 27, 33000);

2) Inserting All columns data directly to a table.

Syntax:-

INSERT INTO TABLE_NAME VALUES (value1, value2, value3,...valueN); 

Example

INSERT INTO employee VALUES (105, ‘Sai', ‘Kiran', 27, 33000);

3) Inserting specific column data to a table through a select statement .

Syntax:-

INSERT INTO table_name [(column1, column2, ... columnN)] SELECT column1, column2, ...columnN FROM table_name [WHERE condition]; 

Example:

INSERT INTO employee (id, name, dept, age, salary location) SELECT emp_id, emp_name, dept, age, salary, location FROM temp_employee;

4) Inserting specific column data to a table through a select statement .

Syntax:-

INSERT INTO table_name SELECT * FROM table_name

Example:

INSERT INTO employee SELECT * FROM temp_employee;

NOTE: When adding a new row, you should ensure the datatype of the value and the column matches

UPDATE

The UPDATE Statement is used to modify the existing rows in a table

Syntax:-

UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... [WHERE condition] 

table_name - the table name which has to be updated.column_name1, column_name2.. - the columns that gets changed.value1, value2... - are the new values.

Example:-

UPDATE employee SET location ='Mysore' WHERE id = 101; 

DELETE

The DELETE Statement is used to delete rows from a table.

The Syntax of a SQL DELETE statement is:

DELETE FROM table_name [WHERE condition];

The Example of a SQL DELETE statement is

DELETE FROM employee WHERE id = 100;

Transaction Control Language (TCL)

Transaction control statements manage changes made by DML statements.

To control transactions Oracle does not made permanent any DML statements unless you commit it. If you don’t commit the transaction and power goes off or system crashes then the transaction is roll backed.

 COMMIT

Make changes done in  transaction permanent.

insert into employee (emp_id,ename,sal) values (101,’Abid’,2300);

commit;

ROLLBACK

To rollback the changes done in a transaction give rollback statement. Rollback restore the state of the database to the last commit point.

Example :

delete from emp;

rollback;          /* undo the changes */

SAVEPOINT

Specify a point in a transaction to which later you can roll back.

Example

 insert into emp (empno,ename,sal) values (109,’Sami’,3000);savepoint a;insert into dept values (10,’Sales’,’Hyd’);savepoint b;insert into salgrade values (‘III’,9000,12000);

Now if you give 

rollback to a; 

Then  row from salgrade table and dept will be roll backed. Now you can commit the row inserted into emp table or rollback the transaction.

 If you give 

rollback to b; 

Then row inserted into salgrade table will be roll backed. Now you can commit the row inserted into dept table and emp table or rollback to savepoint a or completely roll backed the transaction.

 If you give 

rollback; 

Then the whole transactions is roll backed.

 If you give 

commit;

 Then the whole transaction is committed and all savepoints are removed.

Data Control Language (DCL)DCL commands are used to enforce database security in a multiple user database environment. Two types of DCL commands are GRANT and REVOKE. Only Database Administrator's or owner's of the database object can provide/remove privileges on a database object.

SQL GRANT Command

SQL GRANT is a command used to provide access or privileges on the database objects to the users.

GRANT privilege_name ON object_name TO {user_name |PUBLIC |role_name} [WITH GRANT OPTION]; 

privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE, and SELECT.

object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE.

user_name is the name of the user to whom an access right is being granted.

user_name is the name of the user to whom an access right is being granted.

PUBLIC is used to grant access rights to all users.

ROLES are a set of privileges grouped together.

WITH GRANT OPTION - allows a user to grant access rights to other users.

For Example: GRANT SELECT ON employee TO user1; This command grants a SELECT permission on employee table to user1.You should use the WITH GRANT option carefully because for example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2 etc. Later, if you REVOKE the SELECT privilege on employee from user1, still user2 will have SELECT privilege on employee table.

SQL REVOKE CommandThe REVOKE command removes user access rights or privileges to the database objects.

The Syntax for the REVOKE command is:

REVOKE privilege_name ON object_name FROM {user_name |PUBLIC |role_name}

For Example: REVOKE SELECT ON employee FROM user1;This command will REVOKE a SELECT privilege on employee table from user1.When you REVOKE SELECT privilege on a table from a user, the user will not be able to SELECT data from that table anymore. However, if the user has received SELECT privileges on that table from more than one users, he/she can SELECT from that table until everyone who granted the permission revokes it. You cannot REVOKE privileges if they were not initially granted by you.

Privileges and Roles:

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. 

Operators

An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.

Arithmetic operators (+, -, * ,/ and %)

Comparison operators (=, <, >, <>, !=, >=, <=, !> and !<)

Logical operators (ALL, AND, OR, ANY, BETWEEN, EXISTS, IN, LIKE, NOT, OR, IS NULL and UNIQUE)

Operators used to negate conditions.

LIKE Clause

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator:

The percent sign (%)

The underscore (_)

Note:- The percent sign(%) represents zero, one, or multiple characters. The underscore (_) represents a single number or character. The symbols can be used in combinations.

Syntax

SELECT FROM table_name WHERE column LIKE 'XXXX%‘

SELECT FROM table_name WHERE column LIKE '%XXXX%‘

SELECT FROM table_name WHERE column LIKE 'XXXX_‘

SELECT FROM table_name WHERE column LIKE '_XXXX’

SELECT FROM table_name WHERE column LIKE '_XXXX_’

Alias   Names:

You can rename a table or a column temporarily by giving another name known as alias.

The use of table aliases means to rename a table in a particular SQL statement. The renaming is a temporary change and the actual table name does not change in the database.

The column aliases are used to rename a table's columns for the purpose of a particular SQL query.

Syntax for table alias

SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];

ExampleSELECT ename, sal, job,dname FROM emp e, dept d WHERE e.deptno = d.deptno

Syntax for column alias

SELECT column_name AS alias_name

FROM table_name WHERE [condition];

Example

SELECT ename AS employee_name FROM emp WHERE deptno = 10;

IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

Syntax

SELECT column_name(s)FROM table_nameWHERE column_name IN(value1,value2,...);

Example

SELECT enameFROM emp WHERE deptno in (10,20);

IS Operator

IS operator will handle the NULL and NOT NULL Conditions

Syntax

SELECT column_name(s)FROM table_nameWHERE column_name IS(NULL or NOT NULL);

Example

SELECT enameFROM emp WHERE comm IS NULL;

Group By

The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.

The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax

The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1, column2 ORDER BY column1, column2

Example

SELECT ename, SUM(sal) FROM employee

GROUP BY ename;

Order By

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sorts query results in ascending order by default.

Syntax:

SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC];

Example

SELECT * FROM employee ORDER BY name, salaray;

Having CLAUSE

The HAVING clause enables you to specify conditions that filter which group results appear in the final results.

The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause.

Syntax

SELECT column1, column2 FROM table1, table2 WHERE [ conditions ] GROUP BY column1, column2 HAVING [ conditions ] ORDER BY column1, column2

Example

Following is the example, which would display record for which similar age count would be more than or equal to 2:

SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS GROUP BY age HAVING COUNT(age) >= 2;

UNION and UNION ALL

UNION CLAUSE

The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.

To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be the same length.

Syntax

SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNIONSELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]

Example

SELECT empid,ename,job,sal FROM emp UNION SELECT id,name,job,sal FROM employee

UNION ALL CLAUSE

The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows.

The same rules that apply to UNION apply to the UNION ALL operator.

Syntax

SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION ALLSELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]

Example

SELECT empid,ename,job,sal FROM emp UNION ALLSELECT id,name,job,sal FROM employee

Functions

SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Do not confuse SQL functions with user-defined functions written in PL/SQL.

Single Row Functions

Numerical Function :- Numeric functions accept numeric input and return numeric values. Most numeric functions that return NUMBER values that are accurate to 38 decimal digits. 

1. ABS(n) :- ABS returns the absolute value of n.

Eg:- SELECT abs(-15) FROM DUAL; o/p= 15

2. CEIL(n) :- CEIL returns smallest integer greater than or equal to n.

Eg:- SELECT ceil(15356.987) FROM DUAL; o/p= 15357

3. FLOOR(n) :- FLOOR returns largest integer equal to or less than n.

Eg:- SELECT floor(15356.987) FROM DUAL; o/p= 15356

4. MOD(n2,n1) :- MOD returns the remainder of n2 divided by n1. Returns n2 if n1 is 0.

Eg:- SELECT mod(11,3) FROM DUAL; o/p= 4

5. POWER(n2,n1) :- POWER returns n2 raised to the n1 power. The base n2 and the exponent n1 can be any numbers, but if n2 is negative, then n1 must be an integer.

Eg:- SELECT mod(3,4) FROM DUAL; o/p= 81

6. ROUND (n,integer) :- ROUND returns n rounded to integer places to the right of the decimal point. If you omit integer, then n is rounded to 0 places. The argument integer can be negative to round off digits left of the decimal point.

Eg:- SELECT ROUND(15.193,1) "Round" FROM DUAL; o/p= 15.2

Eg:- SELECT ROUND(15.193,-1) "Round" FROM DUAL; o/p= 20

Eg:- SELECT ROUND(1.5) FROM DUAL; o/p= 2

7. SIGN(n):- SIGN returns the sign of n. This function takes as an argument any numeric datatype, or any nonnumeric datatype that can be implicitly converted to NUMBER, and returns NUMBER. For value of NUMBER type, the sign is:

-1 if n<0

0 if n=0

1 if n>0

Eg:- SELECT SIGN(-15) "Sign" FROM DUAL; o/p= -1

String or Character Function Returning Char/String Values :- Character functions that return character values return values of the following datatypes unless otherwise documented:

If the input argument is CHAR or VARCHAR2, then the value returned is VARCHAR2.

1. CHR(n,NCHAR_CS) :- CHR returns the character having the binary equivalent to n as a VARCHAR2 value in either the database character set or, if you specify USING NCHAR_CS, the national character set.

Eg:- SELECT CHR(65) FROM DUAL; o/p:- A

Eg1:- SELECT CHR (196 USING NCHAR_CS) FROM DUAL; o/p:- A

2. CONCAT(char1,char2) :- CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. 

Eg:- SELECT CONCAT('AB','CD') FROM DUAL; o/p:- ABCD

3. INITCAP(char):- INITCAP returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by white space or characters that are not alphanumeric.

Eg:- SELECT initcap('tHe housE') FROM DUAL; o/p:- The House

4. LOWER(char):- LOWER returns char, with all letters lowercase. char can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same datatype as char.

Eg:- SELECT lower('tHe housE') FROM DUAL; o/p:- the house

5. UPPER(char):- UPPER returns char, with all letters uppercase. char can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same datatype as char.

Eg:- SELECT upper('tHe housE') FROM DUAL; o/p:- THE HOUSE

6. LPAD(expr1,n,expr2):- LPAD returns expr1, left-padded to length n characters with the sequence of characters in expr2. This function is useful for formatting the output of a query. Eg:- SELECT LPAD('Page 1',13,'*.') "LPAD example" FROM DUAL; o/p:- *.*.*.*Page 1

7. RPAD(expr1,n,expr2):- RPAD returns expr1, right-padded to length n characters with expr2, replicated as many times as necessary. This function is useful for formatting the output of a query.

Eg:- SELECT RPAD('Page 1',15,'*.') "LPAD example" FROM DUAL;

o/p:- Page 1*.*.*.*.*

8. LTRIM(char, set):- LTRIM removes from the left end of char all of the characters contained in set. If you do not specify set, it defaults to a single blank. If char is a character literal, then you must enclose it in single quotes. Oracle Database begins scanning char from its first character and removes all characters that appear in setuntil reaching a character not in set and then returns the result.

Eg:- SELECT ltrim('xyzabc','xyz') FROM DUAL; o/p:- abc

9. RTRIM(char, set):- RTRIM removes from the right end of char all of the characters that appear in set. This function is useful for formatting the output of a query. If you do not specify set, then it defaults to a single blank. If char is a character literal, then you must enclose it in single quotes. RTRIM works similarly to LTRIM.

Eg:- SELECT rtrim('xyzabc',‘abc') FROM DUAL; o/p:- xyz

10. TRIM(char):- TRIM removes from both sides (left and right)

Eg:- SELECT trim(' xyzabcxyz ') FROM DUAL; o/p:- xyzabcxyz

11. SOUNDEX(char):-SOUNDEX returns a character string containing the phonetic representation of char. This function lets you compare words that are spelled differently, but sound alike in English.

Eg:- SELECT soundex('SMYTHE') FROM DUAL; o/p:- S530

12. SUBSTR(char,position,substring_length):- The SUBSTR functions return a portion of char, beginning at character position, substring_length characters long. SUBSTR calculates lengths using characters as defined by the input character set.  If position is 0, then it is treated as 1.

Eg:- SELECT SUBSTR('ABCDEFG',3,4) "Substring" FROM DUAL; o/p:- CDEF

Eg:- SELECT SUBSTR('ABCDEFG',-5,4) "Substring" FROM DUAL; o/p:- CDEF

13. TRANSLATE(expr, from_string, to_string):- TRANSLATE function replaces a sequence of characters in a string with another set of characters. However, it replaces a single character at a time. For example, it will replace the 1st character in the string_to_replace with the 1st character in the replacement_string. Then it will replace the 2nd character in the string_to_replace with the 2nd character in the replacement_string, and so on.

Stntax:- TRANSLATE( string1, string_to_replace, replacement_string )

PARAMETERS OR ARGUMENTS

string1 is the string to replace a sequence of characters with another set of characters.

string_to_replace is the string that will be searched for in string1.

replacement_string - All characters in the string_to_replace will be replaced with the corresponding character in the replacement_string.

Eg:- select TRANSLATE('1tech23', '123', '456') from dual o/p:- 4tech56

Eg:- select TRANSLATE('1tech23', '123', '456') from dual o/p:- 4tech53

14. REPLACE(char, search_string, replacement_string) :- REPLACE returns char with every occurrence of search_string replaced with replacement_string. If replacement_string is omitted or null, then all occurrences of search_string are removed. If search_string is null, then char is returned.

Eg:- SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL;

o/p:- BLACK and BLUE

String or Character Function Returning Number Values :-1. ASCII(char) :- ASCII returns the decimal representation in the database character set of

the first character of char.

Eg:- SELECT ASCII('r') from dual o/p:- 114

2. LENGTH(char):-The LENGTH functions return the length of char.

Eg:-SELECT length(‘sai') from dual o/p:-3

3. INSTR(string, substring, position, occurrence) :- The INSTR functions search string for substring. The function returns an integer indicating the position of the character in string that is the first character of this occurrence. INSTR calculates strings using characters as defined by the input character set.

Eg:- SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL;

o/p:-14

Eg:- SELECT INSTR('CORPORATE FLOOR','OR', -3, 2) "Reversed Instring" FROM DUAL; o/p:-2

Date Functions :-

Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE ). Some of the datetime functions were designed for the Oracle DATE datatype (ADD_MONTHS, CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you provide a timestamp value as their argument, Oracle Database internally converts the input type to a DATE value and returns a DATE value. 

1. CURRENT_DATE :- CURRENT_DATE returns the current date in the session time zone, in a value in the Gregorian calendar of datatype DATE.

Eg:- SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;

2. SYSDATE:- SYSDATE returns the current date and time set for the operating system on which the database resides. The datatype of the returned value is DATE, and the format returned depends on the value of the NLS_DATE_FORMAT initialization parameter.

Eg:- SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW" FROM DUAL; o/p :- 04-13-2001 09:45:51

3. LAST_DAY(date):- LAST_DAY returns the date of the last day of the month that contains date. The return type is always DATE, regardless of the datatype of date.

Eg:- SELECT LAST_DAY(SYSDATE) FROM DUAL; o/p :- 31-JUL-2014

4. NEXT_DAY(date,char):- NEXT_DAY returns the date of the first weekday named by char that is later than the date date. The return type is always DATE, regardless of the datatype ofdate. The argument char must be a day of the week in the date language of your session, either the full name or the abbreviation. 

Eg:- SELECT NEXT_DAY('02-FEB-2001','TUESDAY') "NEXT DAY" FROM DUAL;

5. MONTHS_BETWEEN(date1,date2):- MONTHS_BETWEEN returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 is earlier thandate2, then the result is negative. If date1 and date2 are either the same days of the month or both last days of months, then the result is always an integer. Otherwise Oracle Database calculates the fractional portion of the result based on a 31-day month and considers the difference in time components date1 anddate2.

Eg:- SELECT MONTHS_BETWEEN (TO_DATE('02-02-1995','MM-DD-YYYY'), TO_DATE('01-01-1995','MM-DD-YYYY') ) "Months" FROM DUAL; o/p :- 1.03225806

6. ADD_MONTHS(date,integer) :- ADD_MONTHS returns the date date plus integer months. The date argument can be a datetime value or any value that can be implicitly converted to DATE. The integer argument can be an integer or any value that can be implicitly converted to an integer. The return type is always DATE, regardless of the datatype of date.

Eg:- SELECT ADD_MONTHS ('16-Sep-81', 3) FROM dual o/p :- 16-Dec-81

Aggregate Functions :- (AVG,COUNT, FIRST, LAST, MAX, MIN, COUNT(*), SUM)

Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups.

Conversion Functions :- (TO_CHAR, TO_DATE, TO_NUMBER)

Conversion functions convert a value from one datatype to another. Generally, the form of the function names follows the convention datatype TO datatype. The first datatype is the input datatype. The second datatype is the output datatype. 

1. TO_CHAR(x [,y]) :- Converts Numeric and Date values to a character string value. It cannot be used for calculations since it is a string value.

Eg:- SELECT TO_CHAR (3000, '$9999') FROM dual; o/p:- $3000 Eg:- SELECT TO_CHAR (SYSDATE, 'Day, Month YYYY') FROM dual o/p:- Thursday,

July,2014

2. TO_DATE (x [, date_format]) :- Converts a valid Numeric and Character values to a Date value. Date is formatted to the format specified by 'date_format'.

Eg:- Convert A String With Default Format To A Date

SELECT to_date('01-JAN-2014') FROM dual; o/p:- 1/1/2014

Eg:- Convert A String With A Non-Default Format To A Date

SELECT to_date('01/01/2014','mm/dd/yyyy') FROM dual o/p:- 1/1/2014

3. TO_NUMBER :- Converts a string to the NUMBER data type

CREATE TABLE test (testcol VARCHAR2(10));

INSERT INTO test values(‘245670.10’);

SELECT TO_NUMBER(testcol)/5 from dual; o/p:- 49134.02

NULL Functions :- (NVL, NVL2,NULLIF)

1. NVL ( string1, replace_with ) :- This function lets you substitute a value when a null value is encountered.

Syntax :- NVL( string1, replace_with )

PARAMETERS OR ARGUMENTS

string1 is the string to test for a null value.

replace_with is the value returned if string1 is null.

Eg:- SELECT NVL(COMM,10) FROM EMP;

2. NVL2(expr1,expr2,expr3):- NVL2 lets you determine the value returned by a query based on whether a specified expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1 is null, then NVL2 returns expr3. The argument expr1 can have any datatype. The arguments expr2 and expr3 can have any datatypes except LONG.

Eg:- SELECT NVL2(comm,sal+comm,sal) FROM dual;

3. NULLIF(expr1,expr2):- NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.

The NULLIF function is logically equivalent to the following CASE expression:

CASE WHEN expr1 = expr 2 THEN NULL ELSE expr1 END

Eg:- SELECT NULLIF(sal+nvl(comm,0),sal) FROM dual;

SubQuery Subquery or Inner query or Nested query is a query in a query. SQL subquery is usually

added in the WHERE Clause of the SQL statement. Most of the time, a subquery is used when you know how to search for a value using a SELECT statement, but do not know the exact value in the database.

Subqueries are an alternate way of returning data from multiple tables.

Subqueries can be used with the following SQL statements along with the comparison operators like =, <, >, >=, <= etc.

Eg:- SELECT * FROM emp WHERE deptno in (SELECT deptno FROM dept)

Correlated SubqueryA query is called correlated subquery when both the inner query and the outer query are

interdependent. For every row processed by the inner query, the outer query is processed as well. The inner query depends on the outer query before it can be processed.

Eg:- SELECT * FROM emp e WHERE deptno in (SELECT deptno d FROM dept d WHERE e.deptno = d.deptno)

Subquery Notes

Nested Subquery

You can nest as many queries you want but it is recommended not to nest more than 16 subqueries in oracle

Non-Corelated Subquery

If a subquery is not dependent on the outer query it is called a non-correlated subquery

Subquery Errors

Minimize subquery errors: Use drag and drop, copy and paste to avoid running subqueries with spelling and database typos. Watch your multiple field SELECT comma use, extra or to few getting SQL error message "Incorrect syntax".

JoinsSQL 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;

Note:- 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; 

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

ViewsView :- A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be seen. A view is stored as a SELECT statement in the database. DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original table upon which the view is based.

Syntax

CREATE VIEW view_name AS SELECT column_list FROM table_name [WHERE condition];

Example:

CREATE VIEW view_product AS SELECT product_id, product_name FROM product;

The WITH CHECK OPTION:

The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view .If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.

Example:

CREATE VIEW customers_view AS SELECT name, age FROM customers WHERE age IS NOT NULL WITH CHECK OPTION;

Drop SQL VIEW:

Syntax: DROP VIEW view_name;

Types of Views

Inline View :

An inline view is a statement in the FROM-clause of another SELECT statement. In-line views are commonly used simplify complex queries by removing join operations and condensing several separate queries into a single query

Eg: select max(age) from ( -- this part of the query is an inline view: select age from table )

Materialized Views:

A Materialized View is effectively a database table that contains the results of a query. Data in materialized views must be refreshed to keep it synchronized with its base table. Refreshing can either be done manually, as below, or automatically by Oracle in some cases.

Eg: create materialized view mv as select * from t ;

Eg: to refresh view -- execute dbms_mview.refresh( 'MV' );

Force View:

To create view even if the table does not exist. After creating a force view, if we create table and insert data. The view will automatically updated.

Syntax:

CREATE or REPLACE force view view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition

Sequence: A sequence is a database item that generates a sequence of integers.

Syntax:

CREATE SEQUENCE sequence_name[START WITH start_num][INCREMENT BY increment_num][ { MAXVALUE maximum_num | NOMAXVALUE } ][ { MINVALUE minimum_num | NOMINVALUE } ][ { CYCLE | NOCYCLE } ][ { CACHE cache_num | NOCACHE } ][ { ORDER | NOORDER } ];

Example:

CREATE SEQUENCE seq_personMINVALUE 1START WITH 1INCREMENT BY 1CACHE 10

Sequence used in SQL statements.

Examples:

select  seq_person.NEXTVAL from DUAL;

SELECT seq_person.CURRVAL FROM DUAL;

DROP Sequence

drop sequence seq_person;

Indexes Indexes are special lookup tables that the database search engine can use to speed up data

retrieval.

Index in sql is created on existing tables. Indexes can be created on a single column or a group of columns.

Syntax:

CREATE INDEX index_name ON table_name (column_name1,column_name2...);

Example:

CREATE INDEX PIndexON Persons (LastName)

We can create Unique index to avoid duplicates.

CREATE UNIQUE INDEX index_name ON table_name (column_name)

Types of Indexes:

1. Implicit Indexes: They are created when a column is explicity defined with PRIMARY KEY, UNIQUE KEY Constraint.

2.Explicit Indexes: They are created using the "create index.. " syntax.

ALTER/RENAME INDEX:

Syntax: ALTER INDEX index_name RENAME TO new_index_name;

DROP INDEX:

Syntax: DROP INDEX index_name;

SYNONYMS A synonym is an alternative name for objects such as tables, views, sequences, stored

procedures, and other database objects.

You generally use synonyms when you are granting access to an object from another schema

Create Synonym:

Syntax:

CREATE [ OR REPLACE ] [ PUBLIC ] SYNONYM

[ schema. ]synonym

FOR [ schema. ]object [ @ dblink ] ;

Example:

CREATE PUBLIC SYNONYM suppliers FOR app.suppliers;

Drop synonym:

Once a synonym has been created in Oracle, you might at some point need to drop the synonym.

Syntax:

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];


Recommended