Sunteți pe pagina 1din 26

Basic Queries:

DDL :
1. create
2. Alter
3. drop

DML :
1. insert
2. select
3. delete
4. update

Table Creation:
Create table persons (p_id number(2),
LastName varchar(20),
FirstName varchar(20),
Address varchar(20),
City varchar(2));

To Display Table Structure:


Desc persons;

To insert record in Table:


Insert into persons values(1,’Hansen’,’Ola’,’ ‘Timoteivn 10’,’ Sandnes’);
Insert into persons values(2,’ Svendson’,’ Tove’,’ ‘Borgvn 23,’ Sandnes’);
Insert into persons values(3,’pettersen’,’Kari’,’ ‘Storgt 20’,’ Stavanger’);
Insert into persons values (&p_id,’&LastName’,’&FirstName’, ‘&Address’,’&City’);
To display Table:
Select * from persons;

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Select p_id, Address, city from persons;

Select distinct city from persons;

Select all city from persons;

Select * from persons where p_id<=2;

Inserting Rows with null values:

Insert into persons values(4,’Patil’,’Nilam’,null,’Pune’);

Inserting Rows with optional Attributes:

Insert into persons(p_id,city) values(5,’Mumbai’);

To delete record:
Delete from persons where p_Id=2;

To delete all records:


Truncate table persons;

To modify/update Record:
Update persons set p_id=10 where p_id=3;
To delete complete Table:
Drop table persons;

To display List of Tables:


Select * from tab;

ALTER :

To Add new attribute :


Alter table persons add(contact number(10));

To delete attribute:
Alter table persons drop(contact);

To modify Attribute :
Alter table persons modify(contact number(15));

Alter table persons add primary key(pid);

Alter table persons drop primary key(pid);

Adding Constraints:

1. Entity Integrity Constraint (PK):


Create table persons (p_id number(2) primary key,
LastName varchar(20),
FirstName varchar(20),
Address varchar(20),
City varchar(2));

2. Referential Integrity Constraint (FK):


Create table employee (e_id number(2) primary key,
p_id number(2),
LastName varchar(20),
FirstName varchar(20),
City varchar(2),
foreign key (p_id) references persons(p_id)) ;

Create table employee (e_id number(2) primary key,


p_id number(2),
LastName varchar(20),
FirstName varchar(20),
City varchar(2),
foreign key (p_id) references
persons(p_id) on delete cascade, on update cascade) ;

cascade: no action , set null, set default

3. Domain Constraint:
i. not null
ii. unique
iii. default
iv. check

Create table employee (e_id number(2) unique,


LastName varchar(20) not null,
FirstName varchar(20) not null,
City varchar(2));
Create table employee (e_id number(2),
LastName varchar(20),
FirstName varchar(20),
City varchar(2) default ‘pune’);

Create table employee (e_id number(2) check(e_id in(1,2,3,4,5)),


LastName varchar(20),
FirstName varchar(20),
City varchar(2));

Saving Work:

1. commit; - to save changes.


2. rollback; - to undo changes.
3. savepoint s1; - creating breakpoint.
4. rollback to s1; - undo operations upto s1.

Logical Operators : (AND,OR,NOT)

1. Select price,code from product where pcode=123 OR pcode=234;

2. Select price,code from product where pcode>123 AND pcode<=234;

3. Select * from product where NOT (pcode=123);

Special Operators:

1. BETWEEN / NOT BETWEEN


2. IS NULL / IS NOT NULL
3. LIKE
4. IN / NOT IN
5. EXISTS / NOT EXISTS

1. select * from product where price BETWEEN 1000 and 2500;

2. select * from product where price NOT BETWEEN 1000 and 2500;

3. select * from product where price IS NULL;

LIKE :

1. % - Any number of characters.


2. _ Exactly matching character
select pname,pcode from product where pname like ‘pen’;

select pname,pcode from product where pname like ‘p%’;

select pname,pcode from product where pname like ‘%k’;

select pname,pcode from product where pname like ‘%p%’;

select pname,pcode from product where pname like ‘%pe%’;

select pname,pcode from product where pname like ‘p__’;

select pname,pcode from product where pname like ‘%p____’;

IN / NOT IN:

Select * from product where pcode in(231,345);

select pname,pcode from product where pname in(‘pen’,’pencil’);

Select * from product where pcode not in(231,345);

EXISTS:

Select * from vendor where exists(select * from product where pid<5);

Adding / Deleting Primary key / Foreign Key:

Alter table product add primary key(pid);

Alter table product drop primary key(pid);

ORDERING A LISTING :

Select attributelist from tabname [where condition] order by attribute


ASC/DESC

Select pid,pname from product order by pid;


Select pid,pname from product order by pid desc;

Select pid,pname from product where pid>3 order by pid;

AGGREGATE FUNCTIONS:

FUNCTION OUTPUT
COUNT The number of rows containing non null values
MIN The minimum value for given attribute
MAX The maximum value for given attribute
SUM The sum of all values for given attribute
AVG The arithmetic mean for given attribute values

Select count(*) from product;

Select count(pid) from product;

Select count(*) from product where pid<8;

Select max(pid) from product;

Select * from product where pid=max(pid);

Select min(pid) from product;

Select * from product where pid=min(pid);

Select sum(pid) as TOTAL from product;

Select sum(pid*price) as TOTALVALUE from product;

Select avg(price) from product;

ARITHMETIC OPERATORS:

Select (pid+5) from product;

Select (price*5) as TOTALPRICE from product;

Select price “TOTAL” from product;

Select (price-3) from product;


Select (pid/2) from product;
GROUPING DATA: (GROUP BY)

GROUP BY clause is valid only when used in conjunction with


one of the aggregate function.

Select pname,min(pid) from product group by pname;

Select pname,avg(price) from product group by pname;

HAVING CLAUSE :

Used to specify condition, as where clause can not be used with


group by.

Select pname,avg(price) from product group by pname having


avg(price)<10;
CARTESIAN PRODUCT:

student11;

ROLLNO NAME CITY


---------- ---------- ------------
1 Nikhil Pune
2 Rucha Mumbai
3 Poorvi Nagpur
4 Ayush Pune
3 Nirja Nasik
5 Sohel Mumbai

Student12

ROLLNO CONTACT AGE


---------- ---------- ----------
10 98766545 18
12 987665545 19
13 344545465 20
2 878766665 17
3 9876655 19

SQL> select * from student11,student12;

ROLLNO NAME CITY ROLLNO CONTACT AGE


---------- ---------- ------------ ---------- ---------- ----------
1 Nikhil Pune 10 98766545 18
2 Rucha Mumbai 10 98766545 18
3 Poorvi Nagpur 10 98766545 18
4 Ayush Pune 10 98766545 18
3 Nirja Nasik 10 98766545 18
5 Sohel Mumbai 10 98766545 18
1 Nikhil Pune 12 987665545 19
2 Rucha Mumbai 12 987665545 19
3 Poorvi Nagpur 12 987665545 19
4 Ayush Pune 12 987665545 19
3 Nirja Nasik 12 987665545 19
5 Sohel Mumbai 12 987665545 19
1 Nikhil Pune 13 344545465 20
2 Rucha Mumbai 13 344545465 20
3 Poorvi Nagpur 13 344545465 20
4 Ayush Pune 13 344545465 20
3 Nirja Nasik 13 344545465 20
5 Sohel Mumbai 13 344545465 20
1 Nikhil Pune 2 878766665 17
2 Rucha Mumbai 2 878766665 17
3 Poorvi Nagpur 2 878766665 17
4 Ayush Pune 2 878766665 17
3 Nirja Nasik 2 878766665 17
5 Sohel Mumbai 2 878766665 17
1 Nikhil Pune 3 9876655 19
2 Rucha Mumbai 3 9876655 19
3 Poorvi Nagpur 3 9876655 19
4 Ayush Pune 3 9876655 19
3 Nirja Nasik 3 9876655 19
5 Sohel Mumbai 3 9876655 19

30 rows selected.

SQL> select * from student11,student12 where


student11.rollno=student12.rollno;

ROLLNO NAME CITY ROLLNO CONTACT AGE


---------- ---------- ------------ ---------- ---------- ----------
2 Rucha Mumbai 2 878766665 17
3 Poorvi Nagpur 3 9876655 19
3 Nirja Nasik 3 9876655 19
JOIN :

Natural Join:

SQL> select * from student11 natural join student12;

ROLLNO NAME CITY CONTACT AGE


---------- ---------- ------------ ---------- ----------
2 Rucha Mumbai 878766665 17
3 Poorvi Nagpur 9876655 19
3 Nirja Nasik 9876655 19

Inner Join:

SQL> select * from student11 inner join student12 on


student11.rollno=student12.rollno;

ROLLNO NAME CITY ROLLNO CONTACT AGE


---------- ---------- ------------ ---------- ---------- ----------
2 Rucha Mumbai 2 878766665 17
3 Poorvi Nagpur 3 9876655 19
3 Nirja Nasik 3 9876655 19

CROSS JOIN:

SQL> select * from student11 cross join student12;

ROLLNO NAME CITY ROLLNO CONTACT AGE


---------- ---------- ------------ ---------- ---------- ----------
1 Nikhil Pune 10 98766545 18
2 Rucha Mumbai 10 98766545 18
3 Poorvi Nagpur 10 98766545 18
4 Ayush Pune 10 98766545 18
3 Nirja Nasik 10 98766545 18
5 Sohel Mumbai 10 98766545 18
1 Nikhil Pune 12 987665545 19
2 Rucha Mumbai 12 987665545 19
3 Poorvi Nagpur 12 987665545 19
4 Ayush Pune 12 987665545 19
3 Nirja Nasik 12 987665545 19
5 Sohel Mumbai 12 987665545 19
1 Nikhil Pune 13 344545465 20
2 Rucha Mumbai 13 344545465 20
3 Poorvi Nagpur 13 344545465 20
4 Ayush Pune 13 344545465 20
3 Nirja Nasik 13 344545465 20
5 Sohel Mumbai 13 344545465 20
1 Nikhil Pune 2 878766665 17
2 Rucha Mumbai 2 878766665 17
3 Poorvi Nagpur 2 878766665 17
4 Ayush Pune 2 878766665 17
3 Nirja Nasik 2 878766665 17
5 Sohel Mumbai 2 878766665 17
1 Nikhil Pune 3 9876655 19
2 Rucha Mumbai 3 9876655 19
3 Poorvi Nagpur 3 9876655 19
4 Ayush Pune 3 9876655 19
3 Nirja Nasik 3 9876655 19
5 Sohel Mumbai 3 9876655 19

30 rows selected.
SELF JOIN:

SQL> select s.rollno,r.rollno from student11 r,student11 s where


r.rollno=s.rollno;

ROLLNO ROLLNO
---------- ----------
1 1
2 2
3 3
3 3
4 4
3 3
3 3
5 5

SQL> select s.rollno,r.rollno NEW_ROLL from student11 r,


student11 s where r.rollno=s.rollno;

ROLLNO NEW_ROLL
---------- ----------
1 1
2 2
3 3
3 3
4 4
3 3
3 3
5 5

Outer Join:
1. Left Outer Join
2. Right outer Join
3. Full Outer Join
1. Left Outer Join:

SQL> select * from student11 left outer join student12 on


student11.rollno=student12.rollno;

ROLLNO NAME CITY ROLLNO CONTACT AGE


---------- ---------- ------------ ---------- ---------- ----------
2 Rucha Mumbai 2 878766665 17
3 Nirja Nasik 3 9876655 19
3 Poorvi Nagpur 3 9876655 19
5 Sohel Mumbai
4 Ayush Pune
1 Nikhil Pune

6 rows selected.

2. Right Outer Join:

SQL> select * from student11 right outer join student12 on


student11.rollno=student12.rollno;

ROLLNO NAME CITY ROLLNO CONTACT AGE


---------- ---------- ------------ ---------- ---------- ----------
2 Rucha Mumbai 2 878766665 17
3 Poorvi Nagpur 3 9876655 19
3 Nirja Nasik 3 9876655 19
13 344545465 20
12 987665545 19
10 98766545 18

6 rows selected.
3. Full Outer Join :

SQL> select * from student11 full outer join student12 on


student11.rollno=student12.rollno;

ROLLNO NAME CITY ROLLNO CONTACT AGE


---------- ---------- ------------ ---------- ---------- ----------
2 Rucha Mumbai 2 878766665 17
3 Nirja Nasik 3 9876655 19
3 Poorvi Nagpur 3 9876655 19
5 Sohel Mumbai
4 Ayush Pune
1 Nikhil Pune
13 344545465 20
12 987665545 19
10 98766545 18

9 rows selected.

SET OPERATORS:

Operators Description
Union Displays all rows selected by either query
Union all Displays all rows selected by either query along with
the duplicates.
Intersect Displays all distinct rows selected by both queries.
Minus Displays all rows present in one table but not in
another.
1. Union :

SQL> select rollno from student11 union select rollno from


student12;

ROLLNO
----------
1
2
3
4
5
10
12
13

8 rows selected.

SQL> select rollno from student11 union all select rollno from
student12;

ROLLNO
----------
1
2
3
4
3
5
10
12
13
2
3

11 rows selected.
2. Intersect :

SQL> select rollno from student11 intersect select rollno from


student12;

ROLLNO
----------
2
3

3. Minus:

SQL> select rollno from student11 minus select rollno from


student12;

ROLLNO
----------
1
4
5

SQL> select rollno from student12 minus select rollno from


student11;

ROLLNO
----------
10
12
13
ARITHMETIC FUNCTIONS:

Arithmetic Description
Function
ABS(n) Returns the absolute values of numeric n.

EXP(n) Returns e raise to power n.

MOD(m,n) Returns the remainder of m divided by n.

POWER(m,n) Returns m raise to the power n.

ROUND(m,n) Rounds off the number m to n decimal places.

SQRT(n) Returns the square root of n.

TRUNC(m,n) Truncate the number m up to n decimal places.

FLOOR(n) Rounds off the number n to the next greater number.

SIN(n) Returns the sine value of n(n in angle value in radian)

COS(n) Returns the cosine value of n(n in angle value in


radian)
TAN(n) Returns the tangent value of n (n in angle value in
radian)

SQL> select * from dual;

D
-
X

SQL> desc dual;


Name Null? Type
----------------------------------------- -------- -------------------------
DUMMY VARCHAR2(1)
Select abs(-34) from dual;

34

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

TRUNC(5.67689,2)
----------------
5.67

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

ROUND(5.67689,2)
----------------
5.68

SQL> select floor(3.1234) from dual;

FLOOR(3.1234)
-------------
3

CHARACTER FUNCTIONS:

Character Description
Function
CHR(n) Returns the character that is binary
equivalent to n.
CONCAT(‘a’,’b’) Returns the concatenation of stirng ‘a’ with
string ‘b’
INITCAP(‘a’) Returns the first character of each word in
uppercase.
LOWER(‘a’) Returns all characters in upper case.

UPPER(‘a’) Returns all characters in lower case.


LPAD(‘a’,n,’b’) Returns the character ‘a’ left padded to length
‘n’ with the sequence of character ‘b’. The
default value of ‘b’ is blank space.
RPAD(‘a’,n,’b’) Returns the character ‘a’ right padded to
length ‘n’ with the sequence of character ‘b’.
The default value of ‘b’ is blank space.
LTRIM(‘a’,’b’) Removes the character or character string ‘b’
from the left of the character string ‘a’.
RTRIM(‘a’,’b’) Removes the character or character string ‘b’
from the right of the character string ‘a’.
SUBSTR(‘a’,n,m) Returns the substring of the string a starting
from the character at n position and ending at
the character at m position of string ‘a’
LENGTH Returns the length of string a

ASCII Returns the decimal equivalent to binary


value of the first character of character string
a.

SQL> select lpad('rupali',3,'c') from dual;

LPA
---
rup

SQL> select lpad('R',3,'C') from dual;

LPA
---
CCR
SQL> select rpad('rupali',3,'c') from dual;

RPA
---
rup

SQL> select rpad('R',3,'C') from dual;

RPA
---
RCC

SQL> select ltrim('dsfdfd','ds') from dual;

LTRI
----
fdfd

SQL> select ltrim('dsfdfd','d') from dual;

LTRI
----
sfdfd

SQL> select rtrim('dsfdfd','d') from dual;

RTRIM
-----
dsfdf
SQL> select substr('MMCOE',1,3) from dual;

SUB
---
MMC

DATE FUNCTIONS:

Date functions operate on the values of date data type.

Date Function Description


ADD_MONTH(d,n) Add n months to the date d specified
as parameter.
CURRENT_DATE Returns the current date. It is in the
value of the date data type
NEXT_DAY(d,c) Returns the date of next occurrence of
day c after date d type.
LAST_dAY(d) Returns the date of the last day of the
month that contains d(date)
SYSDATE Returns the current date and time. The
return type is date.
SYSTIMESTAMP Returns the system date and time with
the fractional seconds.
CURRENT_TIMESTAMP Returns the current time and date in
the session time zone.
DBTIMEZONE Returns the date and time of database
time zone.
SESSIONTIMEZINE Returns the time zone of the current
session.
NEW_TIME(d,f) Changes the date d into format f.
MONTHS_BETWEEN(d1,d2) Returns the month between date d1
and date d2.

VIEWS:
Creating Views:

Create view <viewname> as <select statement>;

Create view emp_info as select empname, empdept,salary from


emp where empno=123;

Select * from emp_info;

Select empname,empdept from emp_info;

To modify view definition:

Create or replace view emp_view as select ename,salary from emp


where dept=’purchase’ or city=’pune’;

Dropping view:

Drop view emp_view;

SEQUENCE :

A sequence is a database object that is used to generate sequential


numbers.

CREATE SEQUENCE <sequence name>


[INCREMENT BY <n>]
[START WITH <m>]
[MAXVALUE <max_val> | NOMAXVALUE]
[MINVALUE <min_val> | NOMINVALUE]
Sequence name: Specifies sequence name.

INCREMENT BY: specifies the value with which to increment the


next value of a sequence.

<n> : Specifies the increment value.

<START WITH>: specifies the numeric value with which sequence


begins.

MAXVALUE: Specifies the upper bound for sequence. Default value


is 10e27-1.

MINVALUE: Specifies the lower bound for sequence. Default value


is 1.

Sequence to generate supplier_id for s_id column of supplier table.

Create sequence sup_seq


increment by 1
start with 1000
nomaxvalue;

insert into supplier(s_id,sname) values(sup_seq.NEXTVAL,’Niraj’);

Alter sequence sup_seq increment by 2;

Drop sequence sup_seq;


Indexes

An index is an auxiliary persistent data structure


For Search tree (e.g., B+-tree), lookup table (e.g., hash table),
etc.
An index on R.A can speed up accesses of the form
R.A = value
R.A > value (sometimes; depending on the index type)
An index on { R.A1, …, R.An } can speed up
R.A1 = value1 ∧ … ∧ R.An = value n
Is an index on { R.A, R.B } equivalent to an index on R.A
plus another index on R.B?

• Examples of using indexes


SELECT * FROM Student WHERE name = ’Bart’;
Without an index on Student.name: must scan the entire table if
• we store Student as a flat file of unordered rows
• With index: go “directly” to rows with name = ’Bart’
• SELECT * FROM Student, Enroll
• WHERE Student.SID = Enroll.SID;
• Without any index: for each Student row, scan the entire
Enroll
• table for matching SID
• • Sorting could help
• With an index on Enroll.SID: for each Student row, directly
look up
• Enroll rows with matching SID

• Creating and dropping indexes in SQL


• CREATE INDEX index_name ON
• table_name(column_name1, …, column_namen);
• DROP INDEX index_name;
• Typically, the DBMS will automatically create
• indexes for PRIMARY KEY and UNIQUE constraint

About Indexes :
• More indexes = better performance?
• Indexes take space
• Indexes need to be maintained when data is updated
• Indexes have one more level of indirection.
• Perhaps not a problem for main memory, but can be
problematic for disk
• Automatic index selection is still an area of active
research

S-ar putea să vă placă și