Computer Programs
Computer Programs
Data
Manipulation
Language
Data
Retrieval
Language
Transition
Control
Language(Three)
Data Control
Language(Double)
INSERT
DELETE
UPDATE
SELECT
COMMIT
ROLLBACK
SAVEPOINT
GRANT
REVOKE
NUMBER(SIZE): This data type allows us to enter only integer values student roll
numbers employee numbers e.t.c., Here size represents no of digits.
Alphabets: The data type allows us to enter character values such as student names
employee names e.t.c., this data type is further divided into three types 1. Char(Size)
2. Varchar(Size), 3. Varchar2(Size)
Char(Size): This data type allows us to enter character values the maximum length of this data
type is 1 to 2000 bytes of characters this data type always allocates the memory in a static
fashion.
EX:Ename char(15)
Varchar(Size)/Varchar2(Size): This data type also allows us to enter character values such as
student names, employee names e.t.c., The maximum length of this data type is 1 to 4000
characters or bytes. It always allocates the memory in a dynamic fashion.
Note: The difference between varchar data type and varchar2 data type is Varchar data type is
developed along with SQL where as varchar2 data type developed by Oracle corporation
varchardata type always allocates the memory in a dynamic fashion where as varchar2 data type
supports garbage values.
DATE: The data type allows us to enter date values such as student joining date employee
hiring data e.t.c., the default date format is Oracle is DD/MM/.YYYY.
Ex:Jdate date
Timestamp: The data type allows to enter both date and time values. The default format of
timestamp is DD/MM/YYYY HH/MM/SS.
EX:Logintime timestamp
Miscelluniousdatatypes: These data types are further divided into three types CLOB, BLOB,
Bfile.
i)
1. Table name should start with alphabets which contains minimum 1 and maximum 30
characters it should not allows any spaces or any special characters such as except _# and
0 to 9.
2. A table can have minimum 1 column maximum thousand columns.
3. A table can have 0 no of records and maximum n no of records up tohard disk capacity.
4. Oracle reserved keywords and words should not be used column names or table names.
5. The rules which we are following for table name the same rules are applicable for column
names.
6. The numeric precision for column must be 1 to 38.
I)
ALTER: This command is used to modify the structure of the table. Using this
command we can perform four different operations. This command contains four
subprograms those are
ALTER Modify
ALTER ADD
ALTER RENAME
ALTER DROP
ALTER Modify: This command is used to increase or decrease the size of the data type and
also we can use the data type from all data type to new data type.
Syntax: ALTER TABLE <Table name> MODIFY <Column name> data type(size)
EX:ALTER TABLE EMP MODIFY ENAMEVARCHAR2(20);
Syntax for modify more than one column:
ALTER TABLE <Table name> MODIFY (col1 data type(size), col2 data type(size)----,coln data
type(size))
EX: Alter table emp modify (eidnumber(5), ename char(10));
ALTER ADD: This command is used to add a new column to the existing table.
Syn: ALTER TABLE<Table name>add column name datatype(size)
EX: ALTER TABLE EMP ADD DEPTNO NUMBER(3)
Syntax to add more than one column:
ALTER TABLE<table name> add (col1 datatype(size), col2
datatype(size)----,colndatatype(size))
4
RENAME: This command is used to change the table name from old table name to
new table name.
TRUNCATE: This command is use delete records permanently from the existing
table.
ALIASES: Alias is duplicate name or an alternative name for the original column name or table
name or expression name. Whenever we need to submit meaningful or understanding reports
then we need to use alias names.
We can provide the alias names in two levels i) Column level ii) Expression level.
7
i)
Column level Alias: Providing the alias name for the columns is called column level
alias.
ii)
Providing the alias names for expressions is known as expression level alias.
EX: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL SALARY, SAL*12
ANNUALSALARY FROM EMP;
EX:SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL ANNUALSALARY,
SAL*12 ANNUALSALARY FROM EMP WHERE ANNUALSALARY>150000
O/P: ANNUAL SALARY in valid identifier because Alias names are not identifiers. Identifier
means column name.
Note: The above example the fallowing error message- Annual salary invalid identifier. So we
cant check the conditions of Alias names.
EX: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL SALARY, SAL*12
ANNUALSALARY FROM EMP WHERE SAL*12>150000
8
The SQL IN condition (sometimes called the IN operator) allows you to easily test if an
expression matches any value in a list of values.
The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition
in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.
The SQL BETWEEN condition allows you to easily test if an expression is within a range of
values (inclusive). It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
The Oracle SQL TO_DATE function converts a string to a date.
The SQL LIKE condition allows you to use wildcards to perform pattern matching in a query.
The LIKE condition is used in the WHERE clause of a SELECT, INSERT, UPDATE, or
DELETE statement.
Wildcard
Explanation
Allows you to match any string of any length (including zero length)
SQL 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.
Ex:
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
The SQL EXISTS condition is used in combination with a subquery and is considered to be
met, if the subquery returns at least one row. It can be used in a SELECT, INSERT,
UPDATE, or DELETE statement.
10
Q) Write a query to increase the employees salaries 1000 who are having more than 10 years.
A) updateemp set sal = sal+1000 where (sysdate-hiredate)/365>10;
Q) Write a query change the employees salaries as 7000 who are having commission.
A) updateemp set sal=sal+7000 where comm>=0;
Q) Write a query change the employees salary 10000 who are not working under anybody.
A) updateemp set sal = sal+10000 where mgr is null;
Q) Write a query change employee name as Srinivas and Salary 9000 whose empno=7566.
A) update emp set ename = 'SRINIVAS' and sal = 9000 where empno =7566;
Q) Write a query change the employees salary 5000 whose name contain more than 6 Character.
A) updateemp set sal = 5000 where length(ename)>6;
Q) Change employee salary 2344 where employee name ending with K.
A) updateemp set sal = 2344 where ename like '%K';
Q) Change employee salary 4000 whose hiredate is 23rd MAY 87.
A) updateemp set sal =4000 where hiredate = 23-MAY-87
Q) Change the employee salary as 6000 whose joining month in start with M.
A) Update emp set sal=6000 where hiredate like ___M%;
Q) Change employee salary 1234 where hiredate is in the month MAY or which starts with M
and ends with Y
A) update employee2 set salary=1234 where hiredate like '___M%';
Q)Change the employee salary 4567 where hiredate is 23rd.
A) updateemp set sal=4567 where hiredate like '2%3%';
12
Q) Write a query delete employee details who are working under 10th DEPT.
A) delete from emp where deptno in (10);
Q) Write a query delete the employee details who are working under 10th and 20th DEPT.
A) delete from emp where deptno =10 or deptno =20;
NOTE: Here we didnt use and because an employee doesnt work in two departments. So we
can write this query two ways.
deleteemp where deptno in(10,20);
Q) Write a query delete the employee who joined in the month april?
A) delete from emp where hiredate like '%APR%';
(OR)
delete from emp where hiredate like '___A%P%';
Q) Write a query to delete the emp details whose salary not in range of 2000 and 3000
A) delete from emp where sal not between 20000 and 30000;
Q) find all of the records from the customers table where there is at least one record in
the orders table with the same customer_id
A) select *from customers where exists(select *from order1 where customers.id=cusid)
Order By:
This clause is used to arrange the data either ascending or descending order. By default order
by clause will arrange the data in ascending order.
If we want to arrange the data in descending order then we use an option called DESC stands
for descending order.
We use order by clause on character columns then it will arrange the data in alphabetic order.
We can apply the order by clause on more than one column in the same table.
We can apply the order by clause only with the select command.
Syntax by applying order by clause
SEELCT * FROM EMP ORDER BY <Column name><ASCE><DESC>
EX: Select * from xyz order by ename salary desc;
13
Functions:
i.
MAX
MIN
SUM
AVG
COUNT
Tables: It can be defined as collection of columns and rows tables are divided into two types.
i) Database Tables ii) NON database tables.
i.
Database Tables: A database table is a table which contains actual information.
14
ii.
Non Database Tables: A non database table is a table which doesnt contain any
information.
9. RTRIM(): This function allows us to remove the blank spaces from the right hand side
of the string.
EX: select rtrim('BAHRGAV
ifrom indian
11. REPLACE(): This function is used to replaces more than a one character.
EX: select replace('jaack and jaar','ja','bl') from dual;
12. REVERSE(): This function allows us to reverse a word.
EX: select reverse('bhargav') from dual;
13. SUBSTR(): This function is use to returns the path of the string from the main string.
EX: select substr('Sathya technologies','7') from dual;
Math functions:
1. ABS( ): This function is used to convert VE values into +VE values.
EX: select abs(-9.5) from dual;
2. CEIL( ):This function is used to round the given number to highest number.
EX: select ceil(9.4) from dual;
1. Greatest( ): This function is used to returns the maximum value from list of numbers.
EX: select greatest(5,6,7,8) from dual;
2. Least():This function is used to returns the minimum value from list of numbers.
EX: select least(5,6,7,8) from dual;
3. MOD(): this function returns reminder value from given number.
EX: select mod(10,2) from dual;
4. ROUND(): This function round converts given number to nearest number.
EX: Select round(-9.4) from dual;
EX: Select round(-9.5) from dual;
The above example shows the output -10 because round treats 9.5 as 10.
16
MONTHS_BETWEEN
ADD_MONTHS
LAST_DAY
NEXT_DAY
MONTHS BETWEEN(): This function is used to find out months between two dates.
17
Count(exp): This function is used to count the no of records in the given table
including duplicate values but excluding null values.
TO_NUMBER('10')
--------------10
TO_CHAR
This will be used to extract various date formats.
The available date formats as follows.
18
--
No of days in week
DD
--
No of days in month
DDD
--
No of days in year
MM
--
No of month
MON
--
MONTH
--
DY
--
DAY
--
--
YY
--
YYY
--
YYYY
--
19
from dual;
SUM(SAL)
---------- ---------10
8750
20
10875
30
9400
SUM(SAL)
---------- ---------
----------
20
10
CLERK
1300
10
MANAGER
10
PRESIDENT
5000
20
ANALYST
6000
20
CLERK
1900
20
MANAGER
30
CLERK
30
MANAGER
2850
30
SALESMAN
5600
2450
2975
950
HAVING
This will work as where clause which can
NAME
ADDRESS
---------- --------200
300
SHAM
HYD
MOHAN
BANG
21
COUNT
----------
-----3
2
DEPTNO
JOB
TSAL
---------- ---------
20
----------
ANALYST
6000
10
PRESIDENT
5000
30
SALESMAN
5600
ORDER OF EXECUTION
First apply grouping mechanism and do the required calculations on the
group then apply having on group values not on individual values
Group the rows together based on group by clause.
Calculate the group functions for each group.
Choose and eliminate the groups based on the having clause.
Order the groups based on the specified column.
22
Set Operators
23
3INTERSECT
This will give the common records of multiple tables having the same
structure.
Ex:
SQL> select * from student1 intersect select * from student2;
4MINUS
This will give the records of a table whose records are not in other tables
having the same structure.
Ex:
SQL> select * from student1 minus select * from student2;
3
Constraints
TABLE LEVEL
Alter level
While adding constraints you need not specify the name but we should
specify the type
oracle will internally name the constraint.
If you want to give a name to the constraint, you have to use the constraint
clause.
1NOT NULL
This is used to avoid null values.
We can add this constraint in column level only.
Ex:
SQL> create table student(no number(2) not null, name varchar(10),
marks
number(3));
25
TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10), marks
number(3), check
ALTER LEVEL
SQL> alter table student add check(marks>300);
SQL> alter table student add constraint ch check(marks>300);
3UNIQUE
This is used to avoid duplicates but it allow nulls.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL
SQL> create table student(no number(2) unique, name varchar(10),
marks number(3));
SQL> create table student(no number(2) constraint un unique, name
varchar(10),
marks number(3));
26
TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10),
marks number(3),
unique(no));
constraint un unique(no));
ALTER LEVEL
SQL> alter table student add unique(no);
SQL> alter table student add constraint un unique(no);
4PRIMARY KEY
This is used to avoid duplicates and nulls. This will work as
combination of unique and not null.
Primary key always attached to the parent table.
Primary key will create Unique index by default.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL
SQL> create table student(no number(2) primary key, name
varchar(10), marks
number(3));
SQL> create table student(no number(2) constraint abc primary key, name
varchar(10),
marks number(3));
TABLE LEVEL
SQL> create table student(cno number(2) , name varchar(10), marks
number(3),
primary key(no));
27
ALTER LEVEL
SQL> alter table student add primary key(cno);
SQL> alter table student add constraint pk primary key(no);
5FOREIGN KEY
This is used to reference the parent table primary key column which
allows duplicates.
Foreign key always attached to the child table.
We can add this constraint in table and alter levels only.
Ex:
TABLE LEVEL
SQL> create table emp(empno number(2), ename varchar(10), deptno
number(2),
Primary
key(empno),
foreign
key(deptno)
references
dept(deptno));
SQL> create table emp(empno number(2), ename varchar(10), deptno
number(2),
key(deptno) references
dept(deptno));
ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references
dept(deptno);
SQL> alter table emp add constraint fk foreign key(deptno)
references dept(deptno);
28
Once the primary key and foreign key relationship has been created then
you can not remove any parent record if the dependent childs exists.
29
primary
dept(deptno) on delete
key(empno),
foreign
key(deptno)
references
cascade);
key(deptno) references
ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references dept(deptno)
on delete
cascade;
delete cascade;
JOINS:
SQL JOINS
SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based
on a common field between them.
30
The most common type of join is: SQL INNER JOIN (simple join). An SQL
INNER JOIN returns all rows from multiple tables where the join condition is
met.
INNER JOIN
31
JOIN Syntax:
select c.id,name,date1,amount from customers c,orders o where c.id=o.id;
select c.id,name,date1,amount from customers c join orders o on c.id=o.id;
Returns all rows from the left table, even if there are no matches in the right table.
Now, let us join these two tables using LEFT JOIN as follows:
33
.id;
Right Outer Join:
The SQL RIGHT JOIN returns all rows from the right table, even if there are no
matches in the left table. This means that if the ON clause matches 0 (zero) records
in left table, the join will still return a row in the result, but with NULL in each column
from left table.
Returns all rows from the right table, even if there are no matches in the left table.
This means that a right join returns all the values from the right table, plus matched
values from the left table or NULL in case of no matching join predicate.
34
35
JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn 10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
OrderNo
P_Id
77895
44678
22456
24562
34764
15
Now we want to list all the persons and their orders, and all the orders with their persons.
36
FirstName
OrderNo
Hansen
Ola
22456
Hansen
Ola
24562
Pettersen
Kari
77895
Pettersen
Kari
44678
Svendson
Tove
34764
The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right table (Orders). If there are
rows in "Persons" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Persons", those
rows will be listed as well.
1.
join:
The SQL JOIN clause is used whenever we have to select data
from 2 or more tables.
To be able to use SQL JOIN clause to extract data from 2
(or more) tables, we need a relationship between certain
columns in these tables.
union:
The purpose of the SQL UNION command is to combine the
results of two queries together. In this respect, UNION is
somewhat similar to JOIN in that they are both used to
related information from multiple tables. One restriction
of UNION is that all corresponding columns need to be of
the same data type. Also, when using UNION, only distinct
values are selected (similar to SELECT DISTINCT).
37