Monday, 11 September 2017

INTERVIEW QUESTIONS- RESTRICTING AND SORTING DATA


What are all the operators available in oracle?

AND , OR , NOT , < , <= , >, >=  

Difference between IN and EXISTS ? Which one is more Faster? Why?

IN OPERATOR

The IN ( ... ) is actually translated by Oracle server to a set of OR conditions: a = value1 OR a = value2 OR a = value3. So using IN ( ... ) has no performance benefits, and it is used for logical simplicity. 

EXISTS OPERATOR

The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns true if the subquery returns one or more records.

EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.

Which operator is used for pattern matching or to do wildcard search?

LIKE  operator is used to pattern matching or wildcard search

Write a query to display all the name which starts with S.

Select first_name from employees where first_name like 'S%';

Write a query to display all the name starts with S and ends with character n.

Select first_name from employees where first_name like 'S%n';

Write a query to display all the employees who are all working for department 90 and their name must starts with S.

Select first_name from employees where department_id=90 and first_name like 'S%';

Display all the job id which contain _ (underscore) as 3rd character.

Select first_name ,job_id from employees where job_id like '__/_%' escape '/';

Write a query to print all the first_name which contains five characters.

Select first_name from employees where length(first_name)=5;

Write a query to display all the employees who are all working in department 10,20,50 and 90.

Select * from employees where department_id in(10,20,50,90);

Write a query to display first name, salary and department id of the employees who are all not working for 10,20,50 and 90.

Select first_name,salary,department_id from employees where department_id not in(10,20,50,90);

Display all the employees who are all hired in year 1994.

Select * from employees where substr(hire_date,-2,2) = '94'

Write a query to display who are all getting salary between 5000 and 7000.

Select * from employees where salary between 5000 and 7000;
Select first_name, Salary from employees where salary between 5000 and 7000;

Display First_name, salary, department_id and manager_id of the employee who don't have manager.

Select first_name, salary, department_id,manager_id from employees where manager_id is null;

Display all the records in employees table and sort the first name in ascending order.

Select * from employees order by first_name asc;

Display first name, department id and salary from employees table and sort the records ( sort department id in ascending order and salary in descending order)    

Select First_name, department_id,salary from employees order by department_id asc, salary desc;

What is the default ordering of an ORDER BY clause in a SELECT statement .

FROM
WHERE
SELECT 
ORDER BY 

Create a query to display the last name and salary of employees earning more than $12,000. Place your SQL statement in a text file named lab2_1.sql. Run your query.

SELECT Last_name, Salary from employees where salary >12000;

Create a query to display the employee last name and department number for employee number 176.

Select last_name, department_id from employees where employee_id = 176;

Modify lab2_1.sql to display the last name and salary for all employees whose salary is not in the range of $5,000 and $12,000. Place your SQL statement in a text file named

Select last_name,salary from employees where salary not between 5000 and 12000;

Display the employee last name, job ID, and start date of employees hired between February 20, 1998, and May 1, 1998. Order the query in ascending order by start date.

Select last_name, job_id, hire_date from employees where hire_date between '02/20/1998' and '06/01/1998' order by hire_date asc;

Display the last name and department number of all employees in departments 20 and 50 in alphabetical order by name.

Select last_name,department_id from employees where department_id in (20,50) order by last_name;

Modify lab2_3.sql to list the last name and salary of employees who earn between $5,000 and $12,000, and are in department 20 or 50. Label the columns Employee and Monthly Salary, respectively. Resave lab2_3.sql as lab2_6.sql. Run the statement in lab2_6.sql.

select Last_name " Employee", salary "Monthly Salary"  from employees where salary between 5000 and 12000 and (department_id=20 or department_id=50);

Display the last name and hire date of every employee who was hired in 1994.

Select last_name,hire_date from employees where substr(hire_date,-2,2)=94;

Display the last name and job title of all employees who do not have a manager.

select *from employees;
Select last_name,job_id,manager_id from employees where manager_id is null;

Display the last name, salary, and commission for all employees who earn commissions. Sort data in descending order of salary and commissions.

Select last_name,salary, commission_pct from employees where commission_pct<>0 order by salary desc; 

Display the last names of all employees where the third letter of the name is an a.

Select last_name from employees where last_name like '__a%';

Display the last name of all employees who have an a and an e in their last name.

Select last_name from employees where last_name like '%a%e%';

Display the last name, job, and salary for all employees whose job is sales representative or stock clerk and whose salary is not equal to $2,500, $3,500, or $7,000.

Select last_name,job_id, salary from employees;
Select last_name,job_id, salary from employees where job_id in ('SA_REP','ST_CLERK');
Select last_name,job_id, salary from employees where job_id in ('SA_REP','ST_CLERK') and Salary not in (2500,3500,7000); 

Modify lab2_6.sql to display the last name, salary, and commission for all employees whose commission amount is 20%. Resave lab2_6.sql as lab2_13.sql. Rerun the statement in lab2_13.sql.

select last_name, salary,commission_pct from  employees where commission_pct = .2;

Sunday, 10 September 2017

RESTRICTING AND SORTING DATA


RESTRICTING AND SORTING DATA

SELECT
FROM
WHERE
ORDER BY

NOTE : Without SELECT and FROM Clause there is no query will be executed.

Where Clause: 

SELECT * FROM Employees;

SELECT Department_id,First_Name,Last_Name, Salary FROM Employees where department_id=90 ;

SELECT First_Name, Salary FROM Employees WHERE First_Name= 'lex';

No Data Found -- CASE SENSITIVE IN DATA IS MANDOTORY

SELECT First_Name, Salary FROM Employees WHERE First_Name= 'Lex';

SELECT First_Name,Hire_Date, Salary FROM Employees WHERE Hire_Date = '05/21/2007';

SELECT First_Name,Hire_Date, Salary FROM Employees WHERE Hire_Date = '05-21-2007';

LOGICAL OPERATORS:

Both AND/OR are used in where class only

AND -- TWO OR MORE CONDITIONS SATISFY
OR  -- EITHER ONE CONDITION IS SATISFIED 

SELECT First_name,Salary FROM Employees Where First_name='Lex' and salary>10000; 

SELECT First_name,Salary FROM Employees Where First_name='Lex' or salary>10000;

RELATIONAL OPERATOR

= < > >= =< |= 

IN        ,  NOT IN
LIKE      ,  NOT LIKE
BETWEEN   ,  NOT BETWEEN 
IS NULL   ,  IS NOT NULL 
ALL 
ANY 

NOTE 

=    Denotes to get only one value
in   Multiple values 

SELECT First_name, Salary from employees where first_name in ('Steven', 'Lex');  

SELECT First_name, Salary from employees where first_name = 'Steven', 'Lex'; 

--ORA-00933: SQL command not properly ended

SELECT First_name, Salary from employees where first_name = 'Steven' and 'Lex'; 

--ORA-00920: invalid relational operator

SELECT First_name, Salary from employees where first_name = 'Steven';

SELECT First_name, Salary from employees where first_name not in ('Steven', 'Lex');  

SELECT First_name, Salary FROM Employees where first_name not in ('Steven', 'Lex');  

SELECT First_name, Salary FROM Employees where first_name like ('Steven', 'Lex');  

ORA-00907: missing right parenthesis

SELECT First_name, Salary FROM Employees where first_name like ('Steven');  

LIKE is used to pattern matching search

% denotes to Something or Nothing

SELECT First_name, Salary FROM Employees where first_name like '%a';  

The Query Shows the ending letter of a;

SELECT First_name, Salary FROM Employees where first_name like '%a%';

The above Query shows the who are all the name having a;  

SELECT First_name, Salary FROM Employees where first_name like '%_a%'; -- 2nd letter of a

SELECT First_name, Salary FROM Employees where first_name like '%_a_i%';-- 2nd letter of a and 4th letter of i

SELECT First_name, Salary FROM Employees where first_name like '%A%r';-- Starts from A and Ends with r  

SELECT First_name, Salary FROM Employees where first_name like 'Ne%'; -- Starts with Ne 

Not Like:

Its opposite of the like operator. 

SELECT First_name, Salary FROM Employees where first_name not like '%_a%'; -- Except 2nd letter of a
SELECT First_name, Salary FROM Employees where first_name not like '%_a_i%';-- Except 2nd letter of a and 4th letter of i
SELECT First_name, Salary FROM Employees where first_name not like '%A%r';-- Except Starts from A and Ends with r  
SELECT First_name, Salary FROM Employees where first_name not like 'Ne%'; -- Except Starts with Ne 

Escape Concepts

Select first_name, email_id from t1 where email_id like '___%' escape'%';

In mail id having underscore.It is represented as  a character suppose we want to search the before the underscore value using escape keyword.

Between

Its belong to range of the two values.

Select first_name, salary from employees where salary between 11000 and 12000;

It will display the range of the salary between the 11000 and 12000.

Select first_name, salary from employees where salary not between 11000 and 12000;

It will display except the  range of the salary between the 11000 and 12000.

Note : the % is not working in the between, not between, in, not in operator

> all

Greater than the greatest value

Select first_name, salary from employees where Salary>15000;

Select first_name, salary from employees where Salary>15000,20000;

ORA-00933: SQL command not properly ended

The greater than compares only one values

Select first_name, salary from employees where Salary>all(15000,20000);

If we need to compare multiples of values use greater than all

>any 

Greater than the lowest value

Select first_name, salary from employees where Salary>any (15000,20000,10000);

It will display the above 10000 salary because Its the lowest value.


Is NULL

Select first_name, salary, commission_pct from employees where commission_pct is null;

ORDER BY 

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Select * from employees order by first_name; -- The query retrieves order by using the first_name column

Select * from employees order by 3;-- 3 denotes to last column 

Select * from employees order by first_name desc;

DESC - Descending Unknown values having high priority 
ASC  - Ascending

Select * from employees order by commission_pct desc; 

if not mention the DESC or ASC.  Ascending  will taken as  default.

Thursday, 7 September 2017

BASIC INTERVIEW QUESTION ON SELECT STATEMENT



Which Version of Oracle are you using? 

Oracle 10 g version or  Oracle 11 g version.

What is the meaning of i, g and c in oracle version? 

I - Stands For Internet
G - Stands For Grid
C - Stands For Cloud

What is Schema in Oracle?

Schema is a logical structures of data or schema objects.

What is Schema Objects?

Schema means user, schema objects means when the object is created by the user it means the schema object like table,view,synonym,sequence, index etc.

What is dual table in oracle?

  • Dual table is a dummy table in database
  • Its used to process our own data.
  • The owner of the dual table is sys
  • Data type is varchar2
  • Default Colomn name is Dummy
  • Data Name is X.

What are all the Schema objects available in oracle?

Oracle having many Schema objects Some of them are table, view, synonym, sequence, index etc

What is SQL?

  • SQL Stands for Structuted Query Language
  • SQL is comment line Its used to interact with the database

What is Data Dictionary table in oracle?

  • Its Contains all information about the Structure and object of the database 
  • Its created and maintained by database
  • The Data  Stored in data dictionary table are also called as meta Data.

How to select data from other schema?

SELECT * From Schema_name.user_tables;
Now Schema Name is HR Means
SELECT * FROM HR.user_tables;

How to Select Unique Records from the particular column? or How To select distinct records from the particular column.

To SELECT the unique or Distinct of particular records from the table means
SELECT DISTINCT column Name from table_name;

How to view the structure of the Table?

Describe Table_name;
Desc Table_name;

Which Data Dictionary table contain Table information?

User_tables Contains table information
Select * from user_tables; --Table_information

Which Data Dictionary Table contain information about all the objects in database?

All_objects Contains all the objects in database
Select * from all_objects; -- object_type

iSQL*Plus commands access the database

FALSE

The following SELECT statement executes successfully: SELECT last_name, job_id, salary AS Sal FROM   employees;

Yes The Query is successfully Executed.

The following SELECT statement executes successfully:
SELECT * FROM   job_grades;

There is no table in the name of job_grades. So its not executed.If the table name created named as job_grades means it will be executed.

There are four coding errors in this statement. Can you identify them? 
SELECT employee_id, last_name sal x 12  ANNUAL SALARY FROM employees;

1.After the last_name Comma is Missing.
2.There is no column name is sal.
3.The symbol of multiplication is *
4.Alias name having spaces without ""

Show the structure of the DEPARTMENTS table. Select all data from the table.

DESC DEPARTMENTS;
SELECT * FROM Departments;

Show the structure of the EMPLOYEES table. Create a query to display the last name, job code, hire date, and  employee number for each employee, with employee number appearing first.Provide an alias STARTDATE for the  HIRE_DATE column. Save your SQL statement to a file named lab1_7.sql.

DESC EMPLOYEES;
SELECT Employee_id, Last_name, Job_id, Hire_Date "STARTDATE" FROM Employees;

Create a query to display unique job codes from the EMPLOYEES table.

SELECT DISTINCT job_id FROM employees;

Copy the statement from lab1_7.sql into the iSQL*Plus Edit window. Name the column headings Emp #, Employee, Job, and  Hire Date, respectively. Run your query again. 

SELECT employee_id "EMP # ",First_name "Employee", job_id "Job", Hire_Date FROM employees;

Display the last name concatenated with the job ID, separated by a comma and space, and name the column Employee and Title.

SELECT last_name || ',' || job_id "Employee and Title" FROM employees;

Create a query to display all the data from the EMPLOYEES table. Separate each column by a comma. Name the column THE_OUTPUT. 

SELECT  Employee_id || ',' || First_Name || ',' ||Last_name || ',' ||Email || ',' ||Phone_number || ',' ||Hire_date || ',' ||job_id || ',' ||salary || ',' ||Commission_pct || ',' ||Manager_id || ',' ||Department_id "THE OUTPUT" FROM Employees;


Wednesday, 6 September 2017

BASIC SQL SELECT STATEMENT


BASIC SQL SELECT STATEMENT

  • A SELECT Statement just  projection of the data from the base or master table.
  • The SQL SELECT statement returns a result set of records from one or more tables. A SELECT statement retrieves zero or more rows from one or more database tables or database views.
SELECT STATEMENT SYNTAX

SELECT * FROM TABLE_NAME;

SELECT/ FROM    : CLAUSE 
*               : All Column

SELECT * FROM Employees;

SELECT/FROM  : CLAUSE
*            : ALL COLUMN
Employees    : TABLE NAME.

It Means all column from employees table.Its just a projection of the data with arithmetic operation, Alias Name, NULL, Distinct, Unique etc.

Example 

SELECT First_Name FROM Employees;

Its Show the First_Name column from the employees table.

Arithmetic Operation in select Statement:

SELECT First_Name,Last_Name,Salary, Salary+1000 FROM Employees;

The above Query shows the following output.




Here there is one new column added into the table but its only projection of the data. The data of the new column not stored in the database. 
    
Note: By Using arithmetic operation in the SELECT Statement BODMOS Rule automatically applied by the operator precedence.

Operator Precedence Rule 
() / * + - 

Example: Consider the current salary is 1000 now increment the salary 100 for every month what is the annual salary for the employee?

Select 12*1000+100 from dual;

if the above query result shows 12100 because of BODMOS Rule.

Select 12*(1000+100) from dual;


Its shows the correct output 13200.

ALIAS NAME: 

  • Column Renaming 
  • Mostly Used with Expressions
  • AS is optional
  • Double Quote is optional(When Space between the Alias Name Double Quote is Mandatory)
  • With in the Double Quotes the text can display with  format given  by the user. Eg:"Name","NAME" , "NaMe"

select first_name AS "NAME" from employees; 
-- The Columns name changed into NAME

select first_name "Name" from employees;
-- The Columns name changed into Name With in the quotes case sensitive

select first_name name from employees; 
-- The Columns name changed into NAME

select first_name Employee_Name from employees;
-- The Columns name changed into EMPLOYEE_NAME

select first_name Employee Name the employees;

-- ORA-00923: FROM keyword not found where expected Quote is mandatory when space between the alias name  


SELECT First_Name,Last_Name,Salary, Salary+1000 "UPDATED SALARY" FROM Employees;



Here the Column name change into the alias name Updated Salary.

NULL:

Null Values represents unknown or unavailable values

Condition 

NULL |= NULL
NULL |= SPACE
NULL |= SPECIAL CHARACTER
NULL |= NULL [Each Null is Unique]
NULL with(=,+,-,*,/) arithmetic values also null.

Arithmetic Operation with NULL 

Example Query : 

select first_name, Salary,Commission_pct,Commission_pct+5 from employees; 




Here the Commission_pct+5 COLUMNS represents adding only if commission is a value else the value is null only.

DISTINCT OR UNIQUE:

To eliminate the duplicate of records or data in the table.  

SELECT First_Name FROM Employees;

After running this queries it returns 107 rows

SELECT DISTINCT First_Name FROM Employees;

After running this queries it returns 91  rows. Remaining Rows or duplicate. i.e some names are repeated. 

CONCATENATION :

Its used to merge the two or more column data into a single one in the select statement.

SELECT First_name || Salary "Name & Salary" from employees;


Similarly



SELECT First_name ||' Salary is '|| Salary "Name & Salary" from employees;



Basic Interview Questions SQL and Select Statement: Click Here

INTRODUCTION AND SQL TOPICS


INTRODUCTION

SQL
  • SQL Stands for Structured Query Language
  • SQL is comment line Its used to interact with the database
SCHEMA(USER) 

Schema is a logical structures of data or schema objects.

TABLE: 
  • Tables are basic unit of storage in an oracle database.
  • Data's are stored in rows and column.
  • A row is a collection of column information corresponding to single record.
USER TABLE:
  • Its Contains the all information about the user data. 
  • Its created and maintained by a user.
  • SYNTAX : SELECT * FROM USER_TABLES 
DATA DICTIONARY TABLE

  • Its Contains all information about the Structure and object of the database 
  • Its created and maintained by database
  • The Data  Stored in data dictionary table are also called as meta Data.

SQL TOPICS:

Tuesday, 5 September 2017

GROUP FUNCTIONS


GROUP FUNCTIONS

Group functions are built-in SQL functions that operate on groups of rows and return one value for the entire group. 

These functions are: 

 COUNT()

 MAX()

 MIN()

 AVG()

 SUM()

 DISTINCT()

CONDITIONS
  1. Group Functions accept one arguments.
  2. Group Functions ignore null values.
  3. * Used only count functions.
  4. Conditions applied only in having Class.
MIN()
To Calculate minimum value of the data 
Ex : 
select min(salary) from employees;

MAX()
To Calculate maximum value of the data 
Ex : 
select max(salary) from employees;

AVG()
To Calculate average value of the data 
Ex : 
select avg(salary) from employees;

COUNT(*)
To Calculate total number of rows in the column 
Ex : 
select count(salary) from employees;
Select count(*) from employees;
Note : * is used only in count operation

SUM()
To Calculate total sum of the value  
Ex : 
select sum(salary) from employees;

It accepts only one arguments

Select Sum(salary,employee_id) from employees;
Select avg(10,6) from dual;

It Ignore null values

Select manager_id from employees;
Select count(manager_id) from employees;

Note : There are 107 records in the manager_id Colomn but count( manager_id ) directs only 106 records because it ignores null values.

GROUP BY

Select department_id, max(salary) from employees;

ORA-00937: not a single-group group function

In group function executes the group of records here department_id is one row so Its make an error. To overcome these type of error group by the department_id column

Select department_id, max(salary) from employees group by department_id ;

Now this query shows the department wise max salary. 

In the Group by Function where clause is replaced by having clause. All the conditions are mentioned by using having clause

Select department_id, max(salary) from employees group by department_id where department_id= 100;

ORA-00933: SQL command not properly ended

Select department_id, max(salary) from employees group by department_id having department_id= 100;


It shows the maximum number of salary

GENERAL FUNCTION OR NULL FUNCTION


GENERAL FUNCTION OR NULL FUNCTION

//Mainly these functions are used to process the null values.

NVL()
NVL2()
NULLIF()
COALESCE()

NVL() : Its accept two arguments if the first arguments is null and its display the second arguments else its display the first arguments.

consider one example

select first_name,commission_pct,nvl(commission_pct,1)from employees;


Note: Here nvl(commission_pct,1) there is two arguments passed if commission_pct is null means it Display 1 otherwise its display first arguments that means commission_pct value.


NVL2( ): Its accept three arguments if the first arguments is null and its display the third arguments else its display the second arguments.

select first_name,commission_pct,nvl2(commission_pct,1,3)from employees;



Note: Here nvl2(commission_pct,1,3) there is three arguments passed if commission_pct is null means it Display 3rd otherwise its display second arguments value.


Null If (): It accepts two arguments return null  if both arguments are equal else it will display the first arguments.


SQL> select nullif(5,10) from dual;

NULLIF(5,10)
------------
           5

SQL> select nullif(15,10) from dual;

NULLIF(15,10)
-------------
           15

SQL> select nullif(15,15) from dual;

NULLIF(15,15)
-------------
             -

COALESCE():  It accept N Number of arguments returns the first not null values from the expression list. and Instead of NVL() we can use the COALESCE() .

select first_name,commission_pct,coalesce(commission_pct,null,null,1,null)from employees;


select first_name,commission_pct,coalesce(commission_pct,null,null,1,null)from employees;

Note: ORA-00909: invalid number of arguments

NUMBER FUNCTIONS


NUMBER FUNCTIONS

ROUND()

SQL> select round(345.678) from dual;

ROUND(345.678)
--------------
           346

SQL> select round(345.578) from dual;

ROUND(345.578)
--------------
           346

SQL> select round(345.478) from dual;

ROUND(345.478)
--------------
           345

SQL> select round(345.478,1) from dual;

ROUND(345.478,1)
----------------
           345.5

SQL> select round(345.478,2) from dual;

ROUND(345.478,2)
----------------
          345.48

SQL> select round(345.478,-2) from dual;

ROUND(345.478,-2)
-----------------
              300

SQL> select round(345.478,-3) from dual;

ROUND(345.478,-3)
-----------------
                0

SQL> select round(345.478,-1) from dual;

ROUND(345.478,-1)
-----------------
              3

TRUNC() 

SQL> select trunc(345.456) from dual;

TRUNC(345.456)
--------------
           345

SQL> select trunc(345.656) from dual;

TRUNC(345.656)
--------------
           345

SQL> select trunc(345.656,2) from dual;

TRUNC(345.656,2)
----------------
          345.65

SQL> select trunc(345.656,1) from dual;

TRUNC(345.656,1)
----------------
           345.6

SQL> select trunc(345.656,0) from dual;

TRUNC(345.656,0)
----------------
             345

SQL> select trunc(345.656,2) from dual;

TRUNC(345.656,2)
----------------
          345.65

MOD()

SQL> select mod(10,2) from dual;

 MOD(10,2)
----------
         0

SQL> select mod(10,3) from dual;

 MOD(10,3)
----------
         1

POWER()

SQL> select power (10,3) from dual;

POWER(10,3)
-----------
       1000

SQL> select power (5,3) from dual;

POWER(5,3)
----------
       125
 
CEIL()

SQL> SELECT CEIL(2.1) FROM DUAL;

CEIL (2.1)
----------
      3

SQL> SELECT CEIL(2.9) FROM DUAL;

CEIL (2.9)
----------
      3

Monday, 4 September 2017

Character Manipulation Function


CHARACTER MANIPULATION FUNCTIONS

LENGTH()
CONCAT()
REVERSE()
SUBSTR()
INSTR()
LPAD()
RPAD()
LTRIM()
RTRIM()
REPLACE()
TRANSLATE()

LENGTH()

SQL> Select First_name, length(first_name) from employees;




SQL> Select First_name, length(first_name) from employees where length(first_name)=5;



REVERSE(): 

This function used to reverse the given input.

SQL> Select upper(reverse(first_name))"UPPER REVERSE" from employees;

UPPER REVERSE
------------
LEUNAM ESOJ
RETEP
ARALC
ATNAHS
ANALA
WEHTTAM
REFINNEJ
INELE

SQL> Select Reverse('12345') from dual;

Reverse
-------
54321

SUBSTR(): 

SUBSTR returns a specified portion of a string
Eg SUBSTR('BCDEF',4)
output BCDE


Select first_name
      ,substr(first_name,'1','3')"substr1"
      ,substr(first_name,'2','3')"substr2"
      ,substr(first_name,'6','3')"substr3"
      ,substr(first_name,'4')"substr4"
      ,substr(first_name,'-3','2')"substr5"
from employees;



Note: 
substr(first_name,'1','3')"substr1"
Here 1 is starting position
         3 is upto 3 char to starting position

substr(first_name,'4')"substr4"
Here 4 is starting position there is no ending position so it will display till the end.

substr(first_name,'-3','2')"substr5"
Here -3 denotes starting char from the last so -3(a) is starting position.

INSTR():

INSTR provides character position in which a pattern is found in a string.
Eg INSTR('ABC-DC-F','-',2)
output 7 (2nd occurence of '-')

SQL>  Select last_name
      ,Instr(last_name,'a')"instr1"
      ,Instr(last_name,'a',2,3)"instr2"
      ,Instr(last_name,'a',8,1)"instr3"
      ,Instr(last_name,'a',8,2)"instr4"
      ,Instr(last_name,'a',5)"instr5"
from employees where lower(last_name)=lower('pataballa')



Note: 
Instr(last_name,'a')"instr1"
Here a is the pattern Its defaultly search the first occurance position its 2

Instr(last_name,'a',2,3)"instr2"
Here a is the pattern 2 is starting position 3 is denoted as 3 occurance position 6

Instr(last_name,'a',8,1)"instr3"
Here a is pattern 8 is starting position 1 is 1st occurance position its 9

Instr(last_name,'a',8,2)"instr4"
Here a is pattern 8 is starting position 2 is 2nd occurance after the starting point but

there is no a's in second occurance so its 0
   
Instr(last_name,'a',5)"instr5"
Here a is pattern 5 is starting position there is no occurance specified so it takes after

the 5 th position its 6

Example :

SQL>  Select last_name
      ,Instr(last_name,'e',2,1)"instr2"
      ,Instr(last_name,'e',2,2)"instr2"
      from employees
where Instr(last_name,'e',2,1)<>0
and Instr(last_name,'e',2,2)=0;

Here the where condition specifies the not equal to zero and equal to zero so the output is



LPAD and RPAD

LPAD : To adjust the left hand side padding of charecters,numbers.
RPAD : To adjust the right hand side padding of charecters, numbers.

Select first_name
     ,lpad(salary,8,'0') "Sal1"
     ,rpad(salary,8,'$') "Sal2"
from employees;

Here lpad(salary,8,'0')
8 denotes charecters or numbers we need so total length is 8.
0 denotes the remaining charcters filled with zeros in left hand side.
Here rpad(salary,8,'$')
8 denotes charecters or numbers we need so total length is 8.
$ denotes the remaining charcters filled with zeros in Right hand side.


LTRIM/RTRIM

LTRIM: Trim the charecters and numbers in left hand side.
RTRIM: Trim the charecters and numbers in Right hand side.

select '000001234500000' "Text"
       ,Ltrim( ' 000001234500000','0') "LTRIM"
       ,Rtrim( ' 000001234500000','0')  "RTRIM"
       ,trim ('0' from '000001234500000')"TRIM"
from dual;



REPLACE AND TRANSLATE

Both Replace and Translate are single row functions in Oracle 9i. The Replace Function
replaces single character with multiple characters. But in Translate Function replaces
single character with single character only.

select 'welcome' "Text"
     , replace('welcome','l','xyzcvb') "Replace"
     , translate('welcome','l','xymkij') "Translate"
from dual;



Here Replace l with multiple characters is changed but translate with  multiple characters
not changed because translate function work only one character at a time.

CASE MANIPULATION FUNCTION IN SQL


//CASE MANIPULATION FUNCTION

UPPER()
lOWER()

INITCAP()

Select Upper(First_name) ,Lower( Last_name) , Initcap(First_name) from Employees;

UPPER(FIRST_NAME)    LOWER(LAST_NAME)          INITCAP(FIRST_NAME)
--------------------                       -------------------------                      --------------------
ELLEN                                                     abel                                           Ellen
SUNDAR                                                 ande                                          Sundar
MOZHE                                                 atkinson                                      Mozhe
DAVID                                                    austin                                         David
HERMANN                                              baer                                         Hermann
SHELLI                                                    baida                                         Shelli


// The above query is the example of case manipulation function

SQL> Select Upper(First_name) ,Lower( Last_name) ,Initcap(First_name)  from Employees where First_name= 'ellen';

no rows selected

Here string is case sensitive in the SQL so  no data found is query result but the name ellen is in the employees table but its case sensitive.so we move to use the case manipulation function in the where clause.

SQL> Select Upper(First_name),Lower( Last_name), Initcap(First_name) from Employees
  where lower(First_name)= lower('ellen');

UPPER(FIRST_NAME)    LOWER(LAST_NAME)          INITCAP(FIRST_NAME)
--------------------                       -------------------------                   --------------------
ELLEN                                                  abel                                            Ellen

Sunday, 3 September 2017

Single Row Functions In SQL


SINGLE ROW FUNCTIONS IN SQL


Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists, where clauses, startwith and connect by clauses, and having clauses.

CASE MANIPULATION FUNCTIONS

 UPPER()
lOWER()
INITCAP()

CHARACTER MANIPULATION FUNCTION

LENGHT()
CONCAT()
REVERSE()
INSTR() SUBSTR()
LTRIM() RTRIM()
LPAD() RPAD()
REPlACE()
TRANSLATE()

NUMBER FUNCTIONS

ROUND()

TRUNC()
POWER()
MOD()

GENERAL FUNCTION 

NVL()
NVL2()
NULLIF()
COALESCE()

DATE FUNCTIONS

ADD_MONTHS()
MONTHS_BETWEEN()
NEXT_DAY()
LAST_DAY()