Sie sind auf Seite 1von 25

Basics:

1. create table emp1 ( ID number(10),name varchar(20),salary number(10));

2. insert into emp1(ID,name,salary) values(100,'Mastan',10000);

3. insert into emp1(name,salary) values('Mastan',10000);

4. insert into emp1(name,salary,id) values('mohan',25000,120);

Dynamic insert:

1. insert into emp1 values(&id,'&name',&salary);

2. insert into emp1 values(130,'sanjay',20000)

3. insert into emp1 values(null,'moshin',130000)

4. insert into emp1(id,name,salary) values(180,'priya',17500);

Data retrieving:

1. select * from &tablename;

2. Specific record:

3. select * from emp1 where id=110;


4. select name from emp1 where id=100;

5. select name from emp1 where id=&id;

6. select * from &table where id=&id;

7. select * from &table where &coloumn=&value;

How to insert data into table from existing table:

1. create table emp3(id number(10),name varchar(25),salary number(10));

2. insert into emp3(name,salary) select name,salary from emp1;

3. how to create a table from existing table with data:

4. insert into emp1(select * from emp6 where id=160);

5. create table emp4 as select * from emp1;

6. create table emp5 as select * from emp2 where dept='apps';

7. how can we create/copy structure of a table from existing table:

8. create table emp4 as select * from emp2 where name='hello'; \\we need copy structure then
give any false coloumn data
Data modification:

1. update emp1 set salary=salary+500 where id=120;

2. update emp1 set salary=&addsalary where id=&id;

3. update emp1 set name='nagurmastan',salary=salary+200 where id=160;

4. Delete-- delete rows from the table :

5. delete emp1 where id=220;

6. delete emp1 where salary<2000;

Alter
1.command is used to add new coloumn for existing table.

alter table emp1 add(phone number(10));

2.it is used to remove existing coloumn from table.

alter table emp1 drop column phone;


3.it is used to increase size/length of the column.

alter table emp1 modify(name varchar(50));

4.it is used to renaming the column.

alter table emp1 rename column id to emp_id;

DROP:

 It is used to remove table from database.

drop table emp2;

TRUNCATE:
 It is used to delete all rows from table,much faster than delete,release storage,can't remove
specific rows without changing the structure of the table

truncate table emp4;

RENAME:
 It is used to renaming the table

Ex: rename emp4 to emp2;

Ex:create table emp6 as select employee,emp_name,phone,salary from emp;


How can we check the database name:

 select ora_database_name from dual;

 select * from global_name;

 select table_name from user_tables;

script:

 save droptable.sql;

 @droptable;

 host vi droptable.sql;

 press i---> to insert data

 press esc---> to close then press wq

wq- means write and quit

now @filename---> automatically exicute the query in that file

Date: 10-08-2016
Today

 While entering the data type for anything u doesn’t mention the range then it will take range 38
as default.

DATA TYPES:
Number:

 It holds numeric value up to 38 digits

Ex: number(10),varchar(25)

Ex2: number ---- By default it will take range as 38

 Number(5,2) ----- in this 5 means precession 2 means scope length after decimal
 If number(2,3) --- means .00999 first 2 zeros and then values 3

CHAR:-

 It holds characters up to 2000.

Ex: Gender char; ----- it means it holds only one character.

Ex: Gender varchar(1); NOT ALLOWED

 We always use varchar when length of the column value is not fixed.

Ex: Columns like Name,Address

1. CHAR allocates memory static memory, and used for fixed length
2. VARCHAR allocates memory dynamically , used for dynamic length max size 2000;
3. VARCHAR2 allocates memory dynamically, used for dynamic length max size 4000;
4. Char,varchar,varchar2 have different max size earlier means before 10g
5. But now char max limit 2000 and varchar,varchar2 max limit 4000;

DATE:

 It holds date In ‘DD-MON-YY’ (10-AUG-16) format.

Ex: hire_date date;

Ex: hire_date date(100); - NOT ALLOWED

‘SYSDATE’ Is used to generate current date;

Ex: insert into emp values(100,’10-AUG-16’);


Ex: insert into emp values(100,sysdate) ----- don’t put semicolon

TIMESTAMP:

 It holds date and time in ‘DD-MON-YY HH:MI:SS:MS’ (10-AUG-16 14:55:01:00111)

OPR_TIME TIMESTAMP -- it is a data_type

SYSTIMESTAMP -- default function

OPERATORS:
ARITHMATIC OPERATORS:

+,-,/,*

Select id,name,salary,salary+1000,salary*10/100 from emp;

Select id,name,salary,salary+1000,salary*10/100 from emp where id=130;

Select id,name,salary,sysdate,’hello hcl’,salary+1000,sysdate+3 from emp;

Select ‘Employee id is’ , id,name,’salary is’,salary from emp;

Identifier can be of three type:

1. Table’s column like id,name,salary etc


2. Operation like 500+500,salary+400 etc
3. Oracle default keyword like sysdate etc

Ex: select ‘hello hcl’ from emp;

Ex: select hello hcl from emp; --- it will show an error called invalid identifier.

Ex: select 5000*20/100 from emp;

Q: How to increase the salary of each employee by 10% in a table.?

A.Select salary,salary*1.1 from emp;

A.Select salary,salary+(salary*10/100) from emp;

RELATIONAL OPERATOR:
= , > , < , <= , >= ,!= .

Ex: Select * from emp where salary >=15000;

Ex: select * from emp where name = ‘nagur’;


LOGICAL OPERATOR:
Or, and, not
T AND T = T
T AND F = F
F AND F = F
Note: we always used with other oracle clauses/keywords.

Q:Retrieve information of all employees whose salary is >10000 but <20000 and
he is not living in delhi.

11-08-2016

SQL CLAUSES/KEYWORDS :
1.Between:

 It is used to search the data in user defined range.

Ex: select * from emp where salary between 10000 and 20000;

(or)

Ex: select * from emp where salary>=10000 and salary<=20000;

We can use between keyword for values like date also

2. IN :

 It is used to search the data for multiple conditions on single or multiple column.

Ex: select * from emp3 where id in (100,110,120,130,140);

(or)

Ex: select * from emp3 where id=100 or id=110 or id=120 or id=130 or id=140;

Ex: select * from emp3 where name='nagur' or name='mastan' or name='vali';


Ex: select * from emp3 where (id,name) in (100,’mastan’);

We can use multiple columns with in clause in sub query

3.ORDER BY:

 It is used for sorting of data in ascending or descending order, default order is ascending.

Ex: select * from emp3 order by salary asc;

Ex: select * from emp3 order by name desc;

Ex: select * from emp3 order by salary,name;

Here salary sorted with respect to name.

Ex: select * from emp3 order by id,salary desc;

Ex: select * from emp3 where name='mastan' order by salary;

Q: sort the data in ascending order for 1st column and then subgroup(column2) is sorted in descending
order?

A: select * from emp3 order by id asc,salary desc;

NOTE : If there are 3 columns in a table . we sorted 2 columns then 3rd column will automatically sorted

4.DISTINCT/UNIQUE:

 It is used to remove duplicate data from rows or columns in the table.

Ex: select distinct * from emp3;

Ex: select unique name from emp3;

Ex: select distinct id,name from emp3;

V.Q: How can we remove duplicate rows from table?

A. 1. create table emp4 as select distinct id,name,salary from emp3;

2. drop table emp3;

3. rename emp4 to emp3;


5.DEFAULT:

 It is used to set user defined default value to a column if value is not available for that column.
 We can use default keyword at table creation time;

Ex: 1.create table nid (id number default 0,name varchar(20),pan varchar(10) default 'N/A',passport
varchar(20) default 'Not Applicable',email varchar(30) default 'Not there');

Output:

Table created.

2. insert into nid values(310,'moshin',null,default,'moshin.a@hcl.com');

Output:

ID NAME PAN PASSPORT EMAIL


310 moshin AB7862M Not Applicable moshin.a@hcl.com

Q.How can we insert multiple rows with a single command?

SQL>insert all

2 into nid values(240,'mogal',default,null,'mogal.vali@hcl.com')

3 into nid values(250,'krish',null,default,'krish.m@hcl.com')

4 select * from dual;

TCL:
1.COMMIT:

 It is used to save any changes done by DB user.


 When DDL is performed then automatically data will be committed.
 When you performed exit/disconnect it will be commit and then exists.

Rollback:

It is used to undo last transaction until last commit or rollback, database connection is performed. and
ROLLBACK, CAN’T work simultaneously;

Ex: rollback;

Savepoint:
When a save point is used with rollback we a part of transaction wil be rollback. Because stand alone
rollback and do the entire transcation.

Rollbaclk to savepoint s1;


DCL:
DCL is commands are used to give the permissions and block the permissions from users through grant
and revoke command.

Grant: It is used to give the permission or privileges.

Types of privileges:

Object Privileges System Privileges


 Insert  Create table
 Update  Drop table
 Delete  Create user
 Select  Create view
 Alter table  We have more than 400
 Create Index system privileges
 All- contains all six privileges

Q: How to give data retrieving permission to HR user on emp1 table where table is owned by scott
user?

A. SQL> show user;

SQL> User is “Scott”

SQL> Grant select on emp1 to hr;

SQL> connect hr/pwd;

SQL> show user;

SQL> user is “HR”

SQL> select * from emp1;

SQL> gives information belongs to hr employees

SQL> select * from scott.emp1;

SQL> then it will show the information belongs to scott employees

Q: Give all data modification permissions to hr user on emp1 table where table owned by scott user:
(give permission through DBA) ?

A. . SQL> show user;

SQL> User is “sys”

SQL> Grant all on scott.emp1 to hr; \\ all means any operation can be perform

SQL> connect hr/pwd;


SQL> show user;

SQL> user is “HR”

SQL> select * from emp1;

SQL> gives information belongs to hr employees

SQL> select * from scott.emp1;

SQL> then it will show the information belongs to scott employees

REVOKE:

It is used to block the object or system privileges.

Ex: Block the data removing permission from hr user from emp1 table, Table is owned by scott user.

A. show user;

SQL> User is “scott”

SQL> revoke delete on scott.emp1 from hr cascade; \\ all means any operation can be perform

SQL> connect hr/pwd;

SQL> show user;

SQL> user is “HR”

SQL> delete from scott.emp1 where id=200;

SQL> Error : insufficient privileges

Rowid :

It is a address of a row in a database.

One fastest way to retrieve data of rows

Ex1.select name,id,rowid from emp3;

Q: How to delete 1 row from duplicate rows in a table ?

A. delete from nid where rowid not in(select min(rowid) from nid group by id,name,pan,passport,email);

Q: How to give permission to another user and that user also can give permission to anyother user?

A. SQL> grant all on emp1 to user1 with grant option;


18-08-2016

Constraints:

Integrity constraints:

Integrity constraints are the rules and regulations or restrictions applied on tables column

Types:

1. Entity constraints:

 Primary key:
1. It is used to uniquely identify a row or record.
2. It does not allow duplicate values.
3. It will not allow null values.
4. Only one primary key allow on a table.
5. We can create single primary key on single column or combination of multiple columns
(Known as composite primary key).

Ex: create table tb1(id number primary key,name varchar(25),salary number);


(or) create table tb1(id number,name varchar(25),salary number primary key(id));
(or) create table tb1(id number,name varchar(25),salary number primary key(id,name));
(or) create table tb1(id number,name varchar(25),salary number);
Alter table tb1 add primary key(id); \\ column must be empty for this.

Remove primary key:


SQL> Alter table tb1 drop primary key;

 Unique key:
1. It is used to uniquely identified a row same as primary key.
2. Unique column will not allow duplicate values.
3. Unique columns will allow null values.
4. We can have more than one unique column in a table.
5. We can create composite unit constraint up to 38 columns

Ex: create table tb2(acno number primary key,name varchar(25),atmno number unique, balance
number);

Ex: create table tb2(acno number primary key,name varchar(25),atmno number unique,id
number unique ,balance number);

Ex: alter table tb2 drop unique(atmno);


2. Referential constraints/integrity

 Foreign key
1. It is a column whose values are derived from primary key or unique column of some
other table.
2. Note : In foreign key column we can insert data that is available in referenced primary
key or unique column.
3. It will allow duplicate values.
4. Foreign key column value allow null values.
5. We can create composite foreign key up to 38 columns.

Ex: create table dept (dept_id number,dept_name varchar(50), location varchar(20) primary
key(dept_id));

2.Create table emp ( id number,name varchar(25),dept_id number,forien key(dept_id) reference


dept(dept_id));

3.Create table emp ( id number,name varchar(25),dept_id number references dept(dept_id));

3. User Defined constraints :

 Check :
It’s a user defined constraint used to restrict data value of a column.
Ex: If we want mobile numbers must be in 10 digits , email must be in its standard format,
Employee_id must start with hcl etc.,
 Not Null :
Is used to create mandatory columns.

Naming conventions :
Naming conventions used to provide user defined name for a constraint

NOTE: Directly we can’t remove foreign key with alter drop command, Only when we mention
the constraint then only it will be remove

SQL> create table emp2(


SQL> 2 id number constraint id_FK references emp1(id),
SQL> 3 salary number);

Delete by this command: alter table emp2 drop constraint id_FK;


Options with foreign key:
On delete cascade:
When we create foreign key with this option and if we remove data or row from parent table
then all reference child rows will automatically removed from the child table.
Ex: create table emp2(
2 id number,
3 salary number,
4 foreign key(id) references emp1(id) on delete cascade);

On delete set null;


When we create foreign key with this option, and we want to remove data or row from parent
table, It will set foreign key columns data value as null. Rest of the column values for same row
will not be deleted.

Ex: create table emp2(


2 id number,
3 salary number,
4 depid number,
5 foreign key(id) references emp1(id) on delete set null);

Enable or Disable the constraint:

Ex: Alter table emp1 disable constraint primary key;


Ex: Alter table emp1 enable constraint primary key;

Set Operators :

LIKE:
It is used for string matching In user defined pattern.

Ex: create table emp3(


2 id number,
3 email varchar(30) check(email like '%@hcl.com'),
4 primary key(id));

Output:
ID EMAIL
---------- ------------------------------
100 nagur.vali@hcl.com
110 kadiyam.m-scholar@hcl.com
SoundEX:

It is used to search the data having same phonetic representation.

Ex: select * from emp1 where soundex(name)=soundex(‘suneel’);


Ex: select * from emp1 where soundex(name)=soundex(‘seeta’);

Union:
It is used to merge the data from multiple column from different tables in a single column.
Common values will be listed only ones.
Column name and data type must be same to perform the union.
Ex: select loc_name from loc1 union select loc_name from loc2 union select loc_name from
loc3;
Union all:
In this duplicate values will be listed out.
Ex: SELECT LOC_NAME FROM LOC1 UNION ALL SELECT LOC_NAME FROM LOC2;

Intersect:
It will return common values from the multiple columns of the different tables.
Ex: select loc_name from loc1 intersect select loc_name from loc2;

Minus :
It is used to return data values from column, those are not available in another column of
different table.
Ex: select loc_name from loc1 minus select loc_name from loc2;

Character Operators:
Concatenation:
It is used to combine multiple strings and generates single string.
With the help of || (vertical bars), we can perform string concatenation.
Ex: select ‘Hello’ || ‘ ‘ || ‘world’ from dual;

Q : How can we insert single quotes in tables column:

A. insert into emp4 values('PRODUCT'|| chr(39)||'S');


OR insert into emp4 values('product'''||'S');

Important interview questions:

1: What is the difference between delete, truncate and drop commands.?


2: Difference between varchar and varchar2 ?
3. How to remove duplicate rows from table ?
4. How to retrieve 4th row or Nth row from the table ?
5. How to drop a user?
6. How to retrieve second highest salary?
A. Select max(Salary) from emp1 where salary<(select max(salary) from emp1);
7. How to insert column in between two columns?
8. How to check version of Software?
A. select * from v$version;
9. What are the analytical functions in oracle?
10. How to retrieve all names from table where 1st and last character of the name are same ?
11. How to identify area or location from mobile number using 1st 4 digits?
12. Difference between inner and natural joins?
13.What are B-tree indexes bit map indexes? And their difference
14. Different between primary key and unique key?
15. Difference between join and union ?

SQL FUNCTIONS:
Function is a group of 1 or more statements that takes input from user, process it and returns
output/results.

Types of functions:

 Aggregate functions:
Also Known as Multi value function or multi row function.
1. SUM: we can add the value of entire column
2. Max : we can get max value of column
3. Min: we can get min value of column
4. AVG: we can get average value of column
5. COUNT: In this null values are not countable.
Options in Aggregate functions:
1. Group BY: It is used to grouping of data and apply aggregate functions on grouped data.
Ex: select dept,sum(salary) from emp1 group by dept;
Ex: select dept,count(*) from emp1 group by dept;
2. Roll up: It is used to generate subtotal and grand total of the grouped data.
Ex: select dept,sum(salary) from emp1 group by rollup(dept);
3. Having : It is used to filter grouped data as where clause is used to filter normal tables data.
Ex: Check maximum salary from each department, where no of employees in a department
must be greater than equal to 2.
A. select dept , max(salary) from emp1 group by dept having count(id) >1;

Dept Max(salary)
IT 45000
SALES 22000

 Numeric functions:
Round:
SQL> select round(54.44,1) from dual;
SQL> 54.4
SQL> select round(54.45,1) from dual;
SQL>54.5
SQL>select round(27848,-3) from dual;
SQL>28000
SQL> select round(27448,-3) from dual;
SQL>27000

TRUNC:

SQL> select trunc(99.9,-1) from dual;


SQL>90
SQL> select trunk(27484,-4) from dual;
SQL>27000

MOD:

SQL> select mod(34,5) from dual;


SQL> 4

Exercise:

1.Select last_name,salary ,mod(salary,5000) from employees where job_id =’SA_REP’;

 Character Functions:
SINGLE ROW FUNCTIONS:
SUBSTR:

Select substr(‘helloworld’,1,5) from dual;

SQL> hello
SQL> Select substr(‘helloworld’,-3,2) from dual;

SQL> rl

SQL> Select substr(‘helloworld’,-3,-2) from dual;

SQL> null

SQL> Select substr(‘helloworld’,2,0) from dual;

SQL> null

SQL> Select substr(‘helloworld’,1) from dual;

SQL> helloworld

LENGTH:

SQL> select length(‘nagur’) from dual;

INSTR:

SQL>select instr(‘hello’,’e’) from dual;

SQL>2

SQL> select instr(‘helloworld’,’l’,1,3) from dual;

SQL> 9

SQL> select instr(‘helloworldllll’,’l’,6,3) from dual;

SQL> 12

SQL> select instr(‘helloworldllll’,’l’,-5,3) from dual;

SQL> 3

LPAD:

SQL> select lpad(salary,10,’#’) from employees;

SQL>#####50000

RPAD:

SQL> select rpad(salary,10,’#’) from employees;

SQL>50000#####
REPLACE:

SQL> select replace(‘TCS’,’C’,’S’) from dual;

SQL> TSS

SQL> select replace(‘TCS’,’TC’,’I’) from dual;

SQL> IS

SQL> select replace(‘TCS’,’CT’,’I’) from dual;

SQL> TCS

SQL> select translate(‘TCS’,’CT’,’I’) from dual;

SQL> IS

SQL>select translate(‘Hello’,’He’,’g’) from dual;

SQL> gllo

SQL>select translate(‘Hello’,’He’,’g ’) from dual;

SQL> g llo

SQL> select translate(‘Hello’,’H’,’ab’) from dual;

SQL>aello

SQL> select replace(‘Hello’,’H’,’ab’) from dual;

SQL> abello

TRIM:

SQL> select trim (‘l’ from ‘local’) from dual;

SQL> oca

SQL> select trim(‘local’,’l’) from dual;

SQL>oca

SQL> select ltrim(‘local’,’l’) from dual;

SQL> ocal

(OR )
SQL> select trim(leading ’l’ from ‘local’) from dual;

SQL> ocal
SQL> select rtrim(‘local’,’l’) from dual;

SQL>loca

(OR)

SQL> select trim(trailing ‘l’ from ‘local’) from dual;

SQL>loca

 Date Functions:

Default format of date is ‘DD-MON-RR’


Difference between YY and RR:
1950-2049 : if you say 58 in palce of RR it will give date as 1958
2000-2099: if you say 58 in place of YY it will give date as 2058
1950-2049 : If you say 38 in place of RR it will give date as 2038
2000-2099: : If you say 38 in place of YY it will give date as 2038

Months_Between:

SQL>Select months_between(sysdate,hire_date) from employees;

Add_months:

SQL> select add_months(sysdate,6) from dual;

Next_day:

SQL: select next_day(sysdate,’friday’) from dual;

Last_day:

SQL> select last_day (sysdate) from dual; \\ it will gives the months last date

Functions:

To_char():

SQL> select to_char(to_date(’25-JUL-16’),’Day ddth “of” month year’) date_info from dual;

SQL> select to_char(to_date('25-jul-16'),'day ddspth "of" month yyyy') date_a from dual;

SQL> select to_char(to_date('25-jul-16'),'day ddspth "of" month yyyy HH12:MI:SS ') date_a
from dual;
SQL> select to_char(to_date('25-jul-16'),'day ddspth "of" month yyyy HH12:MI:SS AM')
format from dual;

NVL:

SQL> select last_name,nvl(commission_pct,0) from employees;

NVL2:

SQL>

SQL>Select last_name,hire_date from employees where hire_date=(select min(hire_date from


employees);

SQL>Select last_name,hire_date from employees where hire_date=(select max(hire_date from


employees);

In place of where we can use Having when we are using GROUP FUNCTIONS:

Escape:

SQL> SELECT LAST_NAME FROM EMP WHERE LAST_NAME LIKE ‘%\_%’ ESCAPE ‘\’;

QUOTATION OPERATOR:

SQL> SELECT LAST_NAME||Q’[‘S DEPARTMENT IS]’||DEPARTMENT_ID FROM EMPLOYEES;

We can use alias name With order by Clause:

SQL> select last_name name from employees order by name;

We can use column position(number) in order by clause;

SQL> select last_name,salary,department_id from employees order by 3,1;


JOINS:
Equijoin: also called as inner join or simple join or natural join

NATURAL JOINS:

When we want to join columns then datatype of column, position of the column, data also should match
value of the column, column name and everything should match in both tables.

If column name does not match with each other tables then it will do cross join(Cartesian product of the
two tables output—in this time natural join behaves like cross join);

Using clause:

Use the using clause to match only one column when more than one column matches

SQL> select l.city, d.department_name, from locations l join departments d using (location_id) where
location_id=1400;

SQL> select e.employee_id, e.last_name, e.location_id from employees e join departments d on


e.department_id=d.department_id;

SQL> select e.employee_id, e.last_name, e.location_id from employees e join departments d


using(department_id);

SQL> select * from employees natural join departments

Self join:

SQL> select c.last_name,c.employee_id, e.last_name "Mangager",e.employee_id, from employees e


join employees c on e.employee_id=c.manager_id;

SQL> select c.last_name,c.employee_id, e.last_name,e.employee_id from employees e join


employees c on e.manager_id=c.employee_id;

SQL> select c.last_name “Manager”,c.employee_id, e.last_name,e.employee_id from employees e


join employees c on e.manager_id=c.employee_id join locations l on d.location_id=l.location_id;

 3 way join is used to join more than 2 tables

Non-Equi Join:

SQL>
OUTER JOIN:

It will give the data whether matching or not.

Left outer join: it will give the data of the left side table columns(e) e.employee_id=d.employee_id.

Right outer join: it will give the data of the right side table columns(d) e.employee_id=d.employee_id.

Full Outer Join: Combination of left and right.

Cross join :

SQL> select employee_id,department_name from employees cross join departments;

SUB QUERIES:

Select e.last_name,e.salary from employees e where 1=(select count(distinct salary) from employees
m where e.salary<m.salary);

E M
4000 4000
6500 6500
5822 5822
9000 9000

select last_name,salary from employees where salary in ((select max(salary) from employees where
salary in(select distinct salary from employees where salary<(select salary from employees where
last_name='Abel'))), (select min(distinct salary) from employees where salary in(select distinct salary
from employees where salary>(select salary from employees where last_name='Abel'))),(select salary
from employees where last_name='Abel')) order by salary;

select last_name,salary from employees where salary in ((select max(salary) from employees where
salary in(select distinct salary from employees where salary<(select salary from employees where
last_name='Abel'))), (select min(distinct salary) from employees where salary in(select distinct salary
from employees where salary>(select salary from employees where last_name='Abel')))) or last_name
like ‘Abel’;

select last_name,salary from employees where salary = (select max(salary) from employees where
salary in(select distinct salary from employees where salary<(select salary from employees where
last_name='Abel')));
To Know the source code;
select text from user_source where name=’QUERY_EMPLOYEES’ order by line;

Das könnte Ihnen auch gefallen