0% found this document useful (0 votes)
14 views33 pages

Unit III SQL (RDBMS)

The document provides an overview of Structured Query Language (SQL), detailing basic data types, commands, and operations for managing database tables. It covers data definition, manipulation, control, and transaction commands, along with examples for creating, modifying, and querying tables. Additionally, it explains operators and functions for filtering and aggregating data, as well as the use of special operators and clauses in SQL queries.

Uploaded by

saikumarvibes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views33 pages

Unit III SQL (RDBMS)

The document provides an overview of Structured Query Language (SQL), detailing basic data types, commands, and operations for managing database tables. It covers data definition, manipulation, control, and transaction commands, along with examples for creating, modifying, and querying tables. Additionally, it explains operators and functions for filtering and aggregating data, as well as the use of special operators and clauses in SQL queries.

Uploaded by

saikumarvibes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Structured Query Language (SQL)

Basic Data Types

Data types come in several forms and sizes, allowing the programmer to create
tables suited to the scope of the project.

A table is database object that holds user data. Table is made up of rows and
columns.
The columns in the table are called as the fields and the rows in the tables are
called as the records.

Each column of the table will have a specific data type bound to it.

Data Type Description


Char (size) It is used to store character strings values of fixed
length. Size in brackets determines the number of
characters the cell can hold. The maximum no. of
characters it can hold is 255.
Varchar(size)/ It is used to store variable length alphanumeric data. It
Varchar2(size) can hold up to maximum of 4000 characters.
Date It is used to represent date and time. Standard format is
dd-mon-yy. DateTime stores date in the 24 hour format.
Number(P,S)/ It is used to store the numbers. Valid values are 0,
Integer positive and negative numbers. Numbers can be
expressed in the scientific notation also. P-Precision and
S-Scale e.g number(7,2) is a number that has 5 digits
before the decimal and two digits after the decimal.

Introduction to SQL:
A database language allows one to create database and table
structures to perform basic data management operations and to perform
complex queries designed to transform raw data into useful information. SQL
functions categories:

Data Definition Language: (DDL)


SQL includes commands to create database objects such as tables,
indexes and views as well as commands to define access rights to those database
objects.

Data Definition Commands


o Create Table
o Create Index
o Create View
o Alter Table
o Drop Table
o Drop Index
o Drop View

Data Manipulation Language (DML):


SQL includes commands to insert, update delete and retrieve data
within the database tables.
Data Manipulation Commands
o Insert
o Select
o Delete
o Update
Data Control Language (DCL)
DCL commands are used to grant and take back authority from any database
user.
o Grant
o Revoke
Transaction Control Language (TCL)
TCL commands can only use with DML commands like INSERT, DELETE and
UPDATE only.
These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them.
o Commit
o Rollback

SQL Commands

CREATE Table Command

o It defines each column of the table uniquely.


o Each column has a minimum of 3 attributes a name, data type and size.
o Table column definition is separated from the other by a comma.
o SQL statement is terminated by a semicolon.

Rules:

o Name can have max. 30 characters


o A-Z, a-z and 0-9 are allowed
o Name should begin with an alphabet.
o SQL reserved words are not allowed.

Syntax:

Create table <tablename>


( <column name1> <data type>(<size>), <column name2> <data
type>(<size>));
Example:

SQL> create table student


2 (htno number(4), sname varchar2(20), scourse varchar(10))
3 ;

Table Created

INSERT Table Command

o This command inserts the data in to a table


o When inserting single row of data into the table
 It creates a new row in the database table
 Loads the values passed in to the columns specified.
o INSERT INTO sql sentence table names and values have one-one
relationship
o If the column names and values are arranged in sequence and ordered
data type the column name need not be specified.
Syntax:

insert into <table name> (<column name1>, <column name2>)


values (<expression1>, <expression2>) ;

Example:

SQL> insert into student


2 (htno,sname,scourse)
3 values
4 (101,'Anitha',’Bcom’)
5 ;

SQL> insert into ex1


2 values (102,'Beena',’BA’);

1 row created

Modifying the Structure of the table:

ALTER Table Command:

o It is used in changing the structure of the existing table.


o With this command it is possible to add or delete columns
o It is also possible to change the data type of the column
Restrictions on the Alter Table

The following cannot be performed


o Changing the name of the table
o Changing the name of the column
o Decreasing the size of a column if table data exists

Adding New Columns:

Syntax:

Alter Table <table name>


Add ( <New column name> <Data type>(<Size>),
<New column name <Data type>(<Size>)…);
Example:

SQL> alter table ex1


2 add (phno number(10),
3 emailid varchar(30))
4 ;

Table altered.

Dropping a column from a Table:

Syntax:

Alter table <table name> Drop column <column name>;

Example:

SQL> alter table ex1


2 drop column phno
3 ;

Table altered.

Modifying Existing Columns:

Syntax:

Alter Table <table name>


Modify (<column name> <new data type>(<New Size>));

Example:
SQL> alter table ex1
2 modify(emailid varchar(25))
3 ;

Table altered.

Renaming Tables:

The rename operation is done atomically, which means that no other thread can
access any of the tables while the rename process is running.

Syntax:

Rename <table name> To <new table name>

Example:

SQL> rename student to stu;

Table renamed.

Displaying the Table Structure:

o It is used to display information about the columns defined in a table.


o This command displays the column names, the data types and the special
attributes connected to the table.

Syntax:

Describe <table name>;


Or
Desc <table name>; desc student_academic;

Example:

SQL> describe ex1;

Name Null? Type


----------------------------------------- -------- -------------
htno NUMBER(4)
sname VARCHAR2(10)
phno number(10)
Semailid varchar(25)
Scourse varchar(10)
COMMIT:
A Commit ends the current transaction and makes permanent any
changes made during the transaction.

Syntax:
Commit;

ROLLBACK:
A Rollback does exactly the opposite of Commit. It ends the transaction
but undoes any changes made during the transaction.

Syntax:
Rollback;

Grant
SQL Grant command is specifically used to provide privileges to database
objects for an user.

Syntax:
grant privilege_name on object_name to {user_name | public | role_name}

Example
grant delete, select on student to Anita

Revoke
Revoke command withdraw user privileges on database objects if any granted.

Syntax:
revoke privilege_name on object_namefrom {user_name | public | role_name}

Example
revoke delete, select on student from Anita

Viewing Data in the Tables:

SELECT Command

o Once data is inserted in to the table, the next logical operation would be
to view what has been entered
o The Select sql statement is used.
o It is used to retrieve rows selected from one or more tables

Syntax:
Select * from <Table Name>;

Example:

SQL> select * from student;

Shtno Sname Semailid Scourse


100 Anita [email protected] Bcom
101 Beena [email protected] Bsc
102 Divya [email protected] Bsc

Sql provides a method of filtering table data using Select queries


The ways of filtering table data are:
o Selected columns and all rows
o Selected rows and all columns
o Selected columns and selected rows

Selected columns and all rows

The retrieval of specific columns from a table

Syntax:
Select <columnname1>, <columnname2> from <tablename>;

Example:
SQL> select shtno, name from student;

Shtno Sname
100 Anita
101 Beena
102 Divya

Selected rows and all columns

A Where clause in a sql query is used to retrieve particular rows.

Syntax:
Select * from <table name> where <condition>;

Example:
SQL> select * from student where htno = 102;
Shtno Sname Semailid Scourse
102 Divya [email protected] Bsc

Selected columns and selected rows

To view a specific set of rows and columns from a table

Syntax:
Select <columnname1>, <columnname2> from <table name>
Where <condition>;
Example:
SQL> select shtno,name from student where htno=102;

Shtno Sname
102 Divya

Operators in SQL

Comparison Operators can be used along with Select query to restrict


output:

The comparison operators available are:

Symbol Meaning
= Equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<> or != Not Equal to

Select * from stu where stno < 104;


Shtno Sname Semailid Scourse
100 Anita [email protected] Bcom
101 Beena [email protected] Bsc
102 Divya [email protected] Bsc
103 Esha [email protected] Bcom

Arithmetic Operators:
Arithmetic Description
Operator
+ Add
- Subtract
* Multiply
/ Divide
^ Power

Select shtno+5 from stu where shtno=100;


Shtno
105

Logical Operators: AND, OR and NOT

SQL allows one to have multiple conditions in a query through the use of
logical operators.

Select * from stu where shtno = 100 or 113;


Shtno Sname Semailid Scourse
100 Anita [email protected] Bcom

Select * from stu where shtno = 100 and 103;


Shtno Sname Semailid Scourse
100 Anita [email protected] Bcom
103 Esha [email protected] Bcom

Select * from stu where not (shtno =103);


Shtno Sname Semailid Scourse
100 Anita [email protected] Bcom
101 Beena [email protected] Bsc
102 Divya [email protected] Bsc
104 Sandhya [email protected] BA
105 Veda [email protected] BA
106 Bavya [email protected] Bsc

Special Operators

The BETWEEN Special Operator:


It is used to check whether an attribute value is within a range.

Select * from stu where shtno between 101 and 103


Shtno Sname Semailid Scourse
101 Beena [email protected] Bsc
102 Divya [email protected] Bsc
103 Esha [email protected] Bcom

The IN Special Operator


Queries that would require the use of logical OR can be more easily handled by
IN operator.

Select * from stu where shtno in (101,102,110,120,135);


Shtno Sname Semailid Scourse
101 Beena [email protected] Bsc
102 Divya [email protected] Bsc

The LIKE Special Operator:


It is used to check whether an attribute value matches a given string pattern. It
is used in conjunction with wildcards to find patterns within string attributes.

% means any and all following or preceding characters are eligible.


Eg: ‘J%’ includes James, June, Jack
‘%n’ includes John, Johnson
_ means any one character may be substituted for the underscore
Eg: ‘_23-456-6789’ includes 123-456-6789 13_ di_ya

Set operators

SQL supports few Set operations which can be performed on the table data.
These are used to get meaningful results from data stored in the table, under
different special conditions.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

UNION is used to combine the results of two or more SELECT statements.


However it will eliminate duplicate rows from its resultset.

SELECT * FROM student


UNION
SELECT * FROM Stumarks;

Union All is similar to Union. But it also shows the duplicate rows.

SELECT * FROM First


UNION ALL
SELECT * FROM Second;

Intersect operation is used to combine two SELECT statements, but it only


retuns the records which are common from both SELECT statements.
SELECT * FROM First
INTERSECT
SELECT * FROM Second;

Minus operation combines results of two SELECT statements and return only
those in the final result, which belongs to the first set of the result.

SELECT * FROM t2
MINUS
SELECT * FROM t1;

Updating the contents of a table

The UPDATE command is used to change or modify the data values in a table.

It updates
a) All the rows from a table
b) A select set of rows from a table.

Update statement updates columns in the existing table’s rows with new values.
The SET clause indicates which column data should be modified and the new
values that they should hold.
The Where clause specifies which rows should be updated, otherwise all table
rows are updated.

Syntax:
Update <table name>
Set <column name1> = <Expression1>, <column name2> =
<Expression2>;

Example:
SQL> Update stu set scourse =’Bcom’;

Update stu set scourse = ‘B.Com’;

Update stu set scourse =’bcom’ where shtno between 110 and 120

DELETE Operations

The Delete is used to remove


a) All the rows from a table
b) A set of rows from a table
Syntax:
Delete from <table name>;
Delete from <tablename> where condition;

Example:
Delete from stu;
Delete from stu where htno=103;

Destroying Tables

Tables within a particular database become obsolete and need to be


discarded. Drop Table statement with the table name can destroy a specific
table.

Syntax:
Drop table <table name>;

Example:
Drop table student;

DISTINCT Clause:
Sql’s Distinct clause produces a list of only those values that are different
from one other.
Example:
Select distinct scourse from stu;
Scourse
Bcom
Bsc
BA

Aggregate Functions
SQL performs various mathematical functions.

COUNT
Returns the number of rows where expression is not null. Count can be
used in conjunction with the DISTINCT clause.
Syntax:
Count([<Distinct>] <expr>)
Example:
SQL> select count(htno) from student;

htno
----------------
6

Count(*) – Returns the number of rows in the table, including duplicates and
those with nulls.

MAX and MIN


Returns the maximum and minimum value of an expression respectively.
Syntax:
Max([Distinct] <expr>)
Min([Distinct] <expr>)
Example:
SQL> select max(marks) "Maximum" from student;

Maximum
----------
106 90

SQL> select min(marks) "Minimum" from student;

Minimum
----------
100 12

SUM
The SUM function computes the total sum for any specified attribute.
Example:
SQL> select sum(marks) "TotalPay" from student;

TOTALPAY
----------
721

AVG
Returns an average value of ‘n’ ignoring null values in a column.
Example:
SQL> select avg(htno) "Average" from student;

Average
----------
103

Dual Table:
Dual table is created by oracle along with the data dictionary. It consists
of exactly one column whose name is dummy and one record of value X. It is
the pseudo table of oracle.

SQL> desc dual;


Name Null? Type
----------------------------------------------------- -------- -------------
DUMMY VARCHAR2(1)

SQL> select * from dual;

D
-
X

Ordering a listing
Using Order By clause

The Order By clause is especially useful when the listing order is important

Syntax:
Select <column name>, <column name> from <table name>
[where condition] [order by <column name>[Asc|Desc]];

Default order is Ascending Order

Example:
SQL> select sno,name,price from test1
2 order by price asc;

SNO NAME PRICE


---------- ---------- ----------
100 Anitha 2000
101 Beena 3000
111 Sandhya 5000
120 Kripa 8000
115 Deepa 9000

SQL> select sno,name,price from test1


2 order by price desc;

SNO NAME PRICE


---------- ---------- ----------
115 Deepa 9000
120 Kripa 8000
111 Sandhya 5000
101 Beena 3000
100 Anitha 2000

Multilevel ordered sequence is known as a cascading order sequence and it can


be created easily by listing several attributes separated by commas, after the
order by clause.

Example:
SQL> select sno,name,price from test1
2 order by name,price;

SNO NAME PRICE


---------- ---------- ----------
100 Anitha 2000
101 Beena 3000
115 Deepa 9000
120 Kripa 8000
111 Sandhya 5000

Grouping Data

Group By Clause

It is another section of select statement. This option clause tells oracle to


group rows based on distinct values that exist for specified columns. The Group
By clause creates a data set, containing several sets of records grouped together
based on a condition. The Group By clause is generally used with the aggregate
functions. It is valid only when used in conjunction with one of the SQL aggregate
functions.

Syntax:

Select <column name1>, <column name2>


From <table name> where condition
Group by <column name1>, <column name2>
Select name, sum(salary) from employee group by name;

Having Clause
The Having clause can be used in conjunction with the Group By clause.
Having imposes a condition on the group by clause, which further filters the
groups created by the Group By clause. Having clause is applied to the output
of Group By clause operation.

Example:

Select name, sum(salary) from employee group by name;

Select name, sum(salary) from employee group by name having


sum(salary)>3000;
Constraints
Primary Key constraint
A primary key is one or more column in a table used to uniquely identify
each row in a table. Primary key column cannot contain a null value. A table can
have only one primary key. Primary key will not allow null and duplicate values.
Unique index is created automatically if there is a primary key.

A single column primary key is called a Simple key. A multicolumn primary key
is called a composite key. A primary key can be defined in either a Create table
statement or an Alter table statement.

Primary Key constraint defined at column level


Syntax:
<Column name> <data type> (<size>) primary key
Example:
SQL> create table cust_mstr
2 (
3 custno varchar2(5) primary key,fname varchar2(20),
4 mname varchar2(15),lname varchar2(10),doj date
5 );

Table created.
SQL> insert into cust_mstr
2 values('c1','suresh','ravi','kumar','07-may-2009');

1 row created.

SQL> /
insert into cust_mstr
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C008084) violated

Foreign Key constraint

Foreign keys represent relationships between tables. A foreign key is a column


whose values are derived from the primary key or unique key of some other table.
The table in which the foreign key is defined is called the foreign or detail table.

The table that defines the primary or unique key is referenced by the foreign key
is called Primary table or Master table.
A foreign key can be defined in either a Create table statement or an Alter table
statement.
Records cannot be inserted in to a detail table if corresponding records in the
master table do not exist
Records of the master table cannot be deleted if corresponding records in the
detail table actually exist

Insert or Update operation in the Foreign Key table


The existence of a foreign key implies that the table with the foreign key is
related to the master table from which the foreign key is derived. A foreign key
must have a corresponding primary key or unique key value in the master table.

Delete operation on the Primary Key table


Oracle displays an error message when a record in the master table is tried
to be deleted and corresponding records exists in a detail table and prevents the
delete operation from going through.

The default behavior of the foreign key can be changed using the ON DELETE
CASCADE option. When the On Delete Cascade option is specified in the foreign
key definition, if a record is deleted in the master table, all corresponding records
in the detail table along with the record in the master table will be deleted.

Foreign Key constraint defined at column level


Syntax:
<column name> <data type>(<size>)
References <table name> [(<column name>)]
[on delete cascade]
Example:
SQL> create table cust_acct
2 (
3 depeid varchar2(10) primary key,
4 caccname varchar2(10),accdet varchar2(15),
5 empid varchar2(5) references emp(empid)
6 );

Table created.

SQL> delete from cust_mstr where custno='c1';


ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys

Foreign Key constraint defined with On Delete Cascade


Example:
SQL> drop table cust_acct;

Table dropped.
SQL> create table cust_acct
2 (
3 custacc varchar2(10) primary key,
4 caccname varchar2(10),
5 accdet varchar2(15),
6 custno varchar2(5) references cust_mstr(custno) on delete cascade
7 );

SQL> insert into cust_acct


2 values('r2345','current','active','c1');

1 row created.

SQL> commit;
Commit complete.

SQL> select * from cust_acct;

CUSTACC CACCNAME ACCDET CUSTN


---------- ---------- --------------- -----
r2345 current active c1

SQL> delete from cust_mstr where custno='c1';

1 row deleted.

SQL> select * from cust_acct;

no rows selected

Dropping Integrity Constraints


For Primary Key
Alter table <table name> drop primary key;
For Foreign Key
Alter table <table name> drop constraint <constraint_name>.
Joins
Joining Multiple Tables
Sometimes it is necessary to work with multiple tables as though they were a
single entity. Joins are used to achieve this. Tables are joined on columns that
have the same data type and data width in the tables.
A primary key is a column with a unique value for each row. The purpose is to
bind together across tables, without repeating all of the data in every table.
SQL Join statement is used to combine data or rows from two or more tables
based on a common field between them.

Types of Join
o Inner
o Outer (Left,Right,Full)
o Cross ===== X
Consider two tables’ students and student’s course
Student Table

Student Course Table

Inner Join
Inner Joins are also known as Equi Joins. The INNER JOIN keyword
selects all rows from both the tables as long as the condition is satisfied . In short
the Inner Join returns all rows from both tables where there is a match.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Example:
SQL> SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE FROM Student INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

Outer Join
Outer joins are similar to inner joins, but give flexibility when selecting
data from related tables. This type of join can be used in situations where it is
desired to select all rows from the table on the left (or right, or both) regardless
of whether the other table has values and enter Null where data is missing.
Left Join: This join returns all the rows of the table on the left side of the join
and matching rows for the table on the right side of join. The rows for which
there is no matching row on right side, the result-set will contain null. LEFT JOIN
is also known as LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,.... FROM table1
LEFT JOIN table2 ON table1.matching_column = table2.matching_column;
Example:
SELECT StudentCourse.COURSE_ID, Student.NAME FROM Student
LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Right Join: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows
of the table on the right side of the join and matching rows for the table on the
left side of join. The rows for which there is no matching row on left side, the
result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Example:
SELECT StudentCourse.COURSE_ID, Student.NAME
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Full Join: FULL JOIN creates the result-set by combining result of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from both the
tables. The rows for which there is no matching, the result-set will
contain NULL values
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....FROM table1
FULL JOIN table2 ON table1.matching_column = table2.matching_column;
Example
SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student
FULL JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Cross Join
A cross join returns what’s known as Cartesian product. This means that
the join combines every row from the left table with every row in the right table.

Example:
SQL> select rollno, name from student cross join student course;
Subqueries or Nested Queries
A Subquery or Inner query or a Nested query is a query within another SQL
query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause
• An ORDER BY command cannot be used in a subquery
Consider a Customer Table
ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

Subqueries are most frequently used with the SELECT statement.


Syntax:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

Example
Sql> select * from customers where Name,address in
( select ID from customers where salary >= 4500);

| 4 | Chaitali | 25 | Mumbai | 6500.00

| 5 | Hardik | 27 | Bhopal | 8500.00


7 | Muffy | 24 | Indore | 10000.00

Exists Special Operator


The exists special operator can be used whenever there is a requirement to
execute a command based on the result of another query. That is if a subquery
returns any rows it runs the main query otherwise it does not.

INDEXES

Indexes are special lookup tables that the database search engine can use to
speed up data retrieval. Simply put, an index is a pointer to data in a table. An
index in a database is very similar to an index in the back of a book.

An index helps speed up SELECT queries and WHERE clauses.

Creating an index involves the CREATE INDEX statement, which allows you to
name the index, to specify the table and which column or columns to index, and
to indicate whether the index is in ascending or descending order.

When data is inserted in the table, the oracle engine automatically inserts the
data value in the index. For every data value held in the index the oracle engine
inserts a unique rowid value. This rowid indicates exactly where the record is
stored in the table.
Creating Simple Index
An index created on a single column of a table is called a simple index.
Syntax:
Create index <index name> on <table name> (<column name>);
Example:
SQL> create index i_empmstr on emp_mstr(fname);
Index created.
SQL> select rowid,empno,fname from emp_mstr;

ROWID EMPNO FNAME


------------------ ------------------------ ---------------------
AAAL07AABAAATTkAAA e1 Ramesh
AAAL07AABAAATTkAAB e2 Suresh
AAAL07AABAAATTkAAC e3 Vignesh
AAAL07AABAAATTkAAD e4 ujjval
AAAL07AABAAATTkAAE e5 venkat
AAAL07AABAAATTkAAF e6 manish
AAAL07AABAAATTkAAG e7 dinesh
7 rows selected.

Dropping Indexes
Indexes associated with the tables can be removed by using the drop index
command.
Syntax:
Drop index <index name>;
Example:
SQL> drop index i_empmstr;

Index dropped.

Views
After a table is created and populated with data, it may become necessary to
prevent all users from accessing all columns of a table, for data security reasons.
Oracle allows the creation of an object called a view.
A view is mapped, to a select sentence. The table on which the view is based is
described in the From clause of the select statement. The select clause consists
of a sub-set of the columns of the table. Thus a view which is mapped to a table
will in effect have a sub-set of the actual columns of the table.
Views can be used to insert, update and delete table data as well as view data it
is called the updateable views.
When view is used to only look at table data is called a read-only view.
Creating a View
Syntax:
Create view <view name> as
Select <column name1>,<column name2> from <table name>
Where <column name> = <expression list>
Example:
SQL> create view vw_empmstr as
2 select empno,fname,lname,desig from emp_mstr;

View created.

SQL> select * from vw_empmstr;


EMPNO FNAME LNAME DESIG
----- ---------- ---------- ----------
e1 Ramesh Kumar Manager
e2 Suresh Reddy clerk
e3 Vignesh Rao officer
e4 ujjval Kumar executive
e5 venkat raman executive
e6 manish patel officer

SQL> select empno,fname from vw_empmstr


2 where empno in('e1','e3','e5');

EMPNO FNAME
----- ----------
e5 venkat
e3 Vignesh
e1 Ramesh
Updateable Views

Views on which data manipulation can be done are called Updateable Views.
Example:
SQL> insert into vw_empmstr values('e8','Karthik','kumar','manager');
1 row created.

SQL> update vw_empmstr set lname='reddy' where lname='kumar';


1 row updated.

SQL> delete from vw_empmstr where fname='Karthik';


1 row deleted.

Dropping a View
The drop view command is used to remove a view from the database.
Syntax:
Drop view <view name>;
Example:
SQL> drop view vw_empmstr;
View dropped.

Sequences
Oracle provides an object called a sequence that can generate numeric values.
The value generated can have a maximum of 38 digits. A sequence can be
defined to:
1. Generate numbers in ascending or descending order.
2. Provide intervals between numbers
3. Caching of sequence numbers in memory to speed up their availability.

A sequence is an independent object and can be used with any table that
requires its output.
Creating Sequences
The minimum information required for generating numbers using a sequence
is:
1. The starting number
2. The maximum number that can be generated by a sequence
3. The increment value for generating the next number.

Syntax:
Create sequence <sequence name>
[increment by <integer value>
Start with <integer value>
Maxvalue <integer value>
Minvalue <integer value>
Cache <integer value>/nocache]
Create table
Create index
Create view
Create sequence ===== DDL
Increment by
Specifies the interval between sequence numbers. It can be any positive
or negative value but not zero. The default value is 1.
Minvalue
Specifies the sequence minimum value.
Maxvalue
Specifies the maximum value that a sequence can generate.
Start With
Specifies the first sequence number to be generated.
Cache
Specifies how many values of a sequence oracle pre-allocates and keeps
in memory for faster access. The minimum value for this parameter is two.
NoCache
Specifies that values of a sequence are not pre-allocated.

Example:
SQL> create sequence s_empmstr increment by 10 start with 500
2 minvalue 500 maxvalue 1000;
Sequence created.
SQL> select * from user_sequences;
sequence_name min_value max_value increment_by c o cache_size last_number
------------------------------ ---------- ---------- ------------ - - ---------- ------------------------
s_empmstr 500 1000 10 n n 20
120

SQL> select * from emp_mstr;

EMPNO FNAME LNAME DEPT DESIG BRANCHNO


----- ---------- ---------- ---------- ---------- ----------
e1 Ramesh Kumar EEE Manager b1
e2 Suresh Reddy mech clerk b1
e3 Vignesh Rao csc officer b2
e4 ujjval Kumar ece executive b2
e5 venkat raman eee executive b3
e6 manish patel csc officer
e7 dinesh reddy eee manager
500 anitha rao eee officer b3

SQL> insert into emp_mstr


2 values(s_empmstr.nextval,'beena','mehta','csc','executive','b1');

SQL> select * from emp_mstr;


EMPNO FNAME LNAME DEPT DESIG BRANCHNO
----- ---------- ---------- ---------- ---------- ----------
e1 Ramesh Kumar EEE Manager b1
e2 Suresh Reddy mech clerk b1
e3 Vignesh Rao csc officer b2
e4 ujjval Kumar ece executive b2
e5 venkat raman eee executive b3
e6 manish patel csc officer
e7 dinesh reddy eee manager
500 anitha rao eee officer b3
510 beena mehta csc executive b1
520
1000
Dropping a Sequence
The drop sequence command is used to remove the sequence from the
database
Syntax:
Drop sequence <sequence name>;
Example:
SQL> drop sequence s_empmstr;
Sequence dropped.

Synonyms
A Synonym provides another name for database object, referred to as original
object that may exist on a local or another server. A synonym belongs to schema,
name of synonym should be unique. A synonym cannot be original object for an
additional synonym and synonym cannot refer to user-defined function.
select * from sys.synonyms ;
Synonyms are database dependent and cannot be accessed by other databases.
Syntax:
CREATE SYNONYM synonymname
FOR servername.databasename.schemaname.objectname;
GO
Schema
Database
Tables
Rows & colns
Example:
Let us assume stutable of kasturbadatabase, kgcwschema on server named
Server1. To reference this table from another server, Server2, an application would
have to use four-part named Server1.kasturba.kgcw.stutable. Also, if the location
of table were to change, for example, to another server, application would have to
be modified to reflect that change.
Now, let us create synonym for stutable table of kasturba database, kgcw schema
on server named Server1.
CREATE SYNONYM student
FOR Server1.kasturba.kgcw.stutable;
GO
Find the output in Server2 by using synonym.
SELECT ID, Name FROM stutable;

You might also like