Sql-Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Client-Server concepts

o The basic client/server architecture is used to deal with a large number of


PCs, web servers, database servers and other components that are connected
with networks.

o The client/server architecture consists of many PCs and a workstation(high


performance PC) which are connected via the network.

o DBMS architecture depends upon how users (clients) are connected to the
database to get their request done.

Types of DBMS Architecture

Database architecture can be seen as a single tier or multi-tier. But logically,


database architecture is of two types like: 2-tier architecture and 3-tier
architecture.

1-Tier Architecture

o In this architecture, the database is directly available to the user. It means


the user can directly sit on the DBMS and uses it.
o Any changes done here will directly be done on the database itself. It doesn't
provide a handy tool for end users.

o In 1-Tier architecture programmers can directly communicate with the


database for the quick response.

o EXAMPLE: students working in the oracle or any database environment

2-Tier Architecture

o The 2-Tier architecture is same as basic client-server.

In the two-tier architecture, applications on the client end can directly


communicate with the database at the server side.

For this interaction, API's like: ODBC(open database


connectivity), JDBC (Java Database Connectivity) are used.

o The user interfaces and application programs are run on the client-side.

o The server side is responsible to provide the functionalities like: query


processing and transaction management.

o To communicate with the DBMS, client-side application establishes a


connection with the server side.

o Example: Visual Basic application connected with oracle/sql server/mysql….

Fig: 2-tier Architecture


3-Tier Architecture

o The 3-Tier architecture contains another layer between the client and server.
In this architecture, client can't directly communicate with the server.

o The application on the client-end interacts with an application server which


further communicates with the database system.

o End user has no idea about the existence of the database beyond the
application server. The database also has no idea about any other user
beyond the application.

o The 3-Tier architecture is used in case of large web application.

Example:

Application created Using HTML,ASP.Net,ORACLE

Fig: 3-tier Architecture


Two-tier architecture

User Interface and Business Logic runs on end-user's computer (the client) .
As application became more complex and could be deployed to hundreds or
thousands of end-users ,Client machines results in overhead .(Fat clients)

Three-tier architecture

First tier.
 Responsibility for presentation and user interaction resides with the first-tier
components.
 These client components enable the user to interact with the second-tier
processes in a secure and intuitive manner.
 For example, a client component provides a form on which a customer orders
products. The client component submits this order to the second-tier
processes, which check the product databases and perform tasks that are
needed for billing and shipping.
Second tier.
 The second-tier processes are commonly referred to as the application logic
layer or business logic layer
 These processes manage the business logic of the application, and are
permitted access to the third-tier services.
 For Example, if several customers attempt to place an order for the same
item, of which only one remains, the application logic layer must determine
who has the claim to that item, update the database to reflect the purchase,
and inform the other customers that the item is no longer available
Third tier.
 Database Server .It is a DBMS, which stores the data required by the middle
tier. This tier may run on a separate server called the database server.
 The third-tier services are protected from direct access by the client
components..
 Interaction must occur through the second-tier processes.

Top 5 Java Application Servers

1. Tomcat
2. JBoss/WildFly
3. Weblogic
4. Jetty
5. GlassFish

A web server is a computer that stores web server software and a website's
component files. (for example, HTML documents, images, CSS stylesheets, and
JavaScript files)

A web server connects to the Internet and supports physical data interchange with
other devices connected to the web.

Web server – Apache webserver , Tomcat webserver , IIS webserver etc.,

The database server holds the Database Management System (DBMS) and
the databases.

Upon requests from the client machines, it searches the database for selected
records and passes them back over the network.
Database
A database is a collection of information that is organized so that it can be easily accessed,
managed and updated. Computer databases typically contain aggregations of data records
or files, containing information about sales transactions or interactions with specific
customers.

Most databases contain multiple tables, which may each include several different fields.
For example, a company database may include tables for products, employees, and
financial records.

Database management system(DBMS) is a software that is used to manage the


database. Oracle, MySQL and Microsoft SQL server are the top three DBMS software.

Database Objects in DBMS

 A database object is any defined object in a database that is used to


store or reference data.
 Anything which we make from create command is known as
Database Object.
 It can be used to hold and manipulate the data.
The database objects are :
 Table – Basic unit of storage; composed rows and columns
 View – Logically represents subsets of data from one or more tables
 Sequence – Generates primary key values
 Index – Improves the performance of some queries
 Synonym – Alternative name for an object

1. Table – This database object is used to create a table in database.


Syntax :
CREATE TABLE table_name
(column datatype [DEFAULT expr][, ...]);
Example :
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));
Output :
1. DESCRIBE dept;

2. View
 This database object is used to create a view in database.
 A view is a logical table based on a table or another view.
 A view contains no data of its own but is like a window through which
data from tables can be viewed or changed.
 The tables on which a view is based are called base tables.
 The view is stored as a SELECT statement in the data dictionary.
Syntax :
CREATE [OR REPLACE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT
constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
Example :
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY FROM employees
WHERE department_id = 50;
Output :
SELECT * FROM salvu50;

3. Sequence –
This database object is used to create a sequence in database.
A sequence is a user created database object that can be shared by
multiple users to generate unique integers.
A typical usage for sequences is to create a primary key value, which
must be unique for each row.
The sequence is generated and incremented (or decremented) by an
internal Oracle routine.
Syntax :
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
Example :
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
Check if sequence is created by :
SELECT sequence_name, min_value, max_value,
increment_by, last_number
FROM user_sequences;
4. Index – This database object is used to create a indexes in database.An
Oracle server index is a schema object that can speed up the retrieval of
rows by using a pointer.
Indexes can be created explicitly or automatically. If you do not have an
index on the column, then a full table scan occurs.
An index provides direct and fast access to rows in a table. Its purpose is
to reduce the necessity of disk I/O by using an indexed path to locate data
quickly.
The index is used and maintained automatically by the Oracle server.
Once an index is created, no direct activity is required by the user.Indexes
are logically and physically independent of the table they index. This
means that they can be created or dropped at any time and have no
effect on the base tables or other indexes.
Syntax :
CREATE INDEX index
ON table (column[, column]...);
Example :
CREATE INDEX emp_last_name_idx
ON employees(last_name);
5. Synonym – This database object is used to create a indexes in database.
It simplify access to objects by creating a synonym(another name for an
object). With synonyms, you can Ease referring to a table owned by
another user and shorten lengthy object names.

To refer to a table owned by another user, you need to prefix the table
name with the name of the user who created it followed by a period.
Creating a synonym eliminates the need to qualify the object name with
the schema and provides you with an alternative name for a table, view,
sequence, procedure, or other objects. This method can be especially
useful with lengthy object names, such as views.
In the syntax:

PUBLIC : creates a synonym accessible to all users


synonym : is the name of the synonym to be created
object : identifies the object for which the synonym is created
Syntax :
CREATE [PUBLIC] SYNONYM synonym FOR object;
Example :
CREATE SYNONYM d_sum FOR dept_sum_vu;
SQL commands are instructions, coded into SQL statements, which are used to
communicate with the database to perform specific tasks, work, functions and queries
with data.
SQL commands can be used not only for searching the database but also to perform
various other functions like, for example, we can create tables, add data to tables, or
modify data, drop the table, set permissions for users. SQL commands are grouped into
four major categories depending on their functionality:
 Data Definition Language (DDL) - These SQL commands are used for creating,
modifying, and dropping the structure of database objects. The commands are
CREATE, ALTER, DROP, RENAME, and TRUNCATE.
 Data Manipulation Language (DML) - These SQL commands are used for
storing, retrieving, modifying, and deleting data.
These Data Manipulation Language commands are: SELECT, INSERT, UPDATE,
and DELETE.
 Transaction Control Language (TCL) - These SQL commands are used for
managing changes affecting the data. These commands are COMMIT,
ROLLBACK, and SAVEPOINT.
 Data Control Language (DCL) - These SQL commands are used for providing
security to database objects. These commands are GRANT and REVOKE.

Data Definition Language (DDL)


CREATE DATABASE Example:
 If you want to create database MyDatabase with default collation, the statement
would be like
CREATE DATABASE MyDatabase ;

SQL USE Statement

The USE Statement is used to select a database and perform SQL operations into that
database.
The database remains default until end of session or execution of another USE statement
with some other database.
SQL USE DATABASE Statement:
The Syntax for the USE Statement is:
USEdatabase_name;

database_name - is the name of the database to be selected


USE DATABASE Example:
If we want to use database MyDatabase, the statement would be like
USE MyDatabase ;

The SQL CREATE TABLE Statement


The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;

Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;

Oracle ALTER TABLE Statement


In Oracle, ALTER TABLE statement specifies how to add, modify, drop or delete columns in
a table. It is also used to rename a table.

How to add column in a table

Syntax:
ALTER TABLE table_name
ADD column_name column-definition;

Example:
Consider that already existing table customers. Now, add a new column customer_age into
the table customers.
ALTER TABLE customers
ADD customer_age varchar2(50);
Now, a new column "customer_age" will be added in customers table.

How to add multiple columns in the existing table

Syntax:
ALTER TABLE table_name
ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);

Example

ALTER TABLE customers


ADD (customer_type varchar2(50),
customer_address varchar2(50));
Now, two columns customer_type and customer_address will be added in the table
customers.

How to modify column of a table

Syntax:
ALTER TABLE table_name
MODIFY column_name column_type;

Example:
ALTER TABLE customers
MODIFY customer_name varchar2(100) not null;

Now the column column_name in the customers table is modified


to varchar2 (100) and forced the column to not allow null values.

How to modify multiple columns of a table


Syntax:
ALTER TABLE table_name
MODIFY (column_1 column_type,
column_2 column_type,
...
column_n column_type);

Example:
ALTER TABLE customers
MODIFY (customer_name varchar2(100) not null,
city varchar2(100));
This will modify both the customer_name and city columns in the table.

How to drop column of a table

Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;

Example:
ALTER TABLE customers
DROP COLUMN customer_name;
This will drop the customer_name column from the table.

How to rename column of a table

Syntax:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;

Example:
ALTER TABLE customers
RENAME COLUMN customer_name to cname;
This will rename the column customer_name into cname.

How to rename table

Syntax:
ALTER TABLE table_name
RENAME TO new_table_name;

Example:
ALTER TABLE customers
RENAME TO retailers;
This will rename the customer table into "retailers" table.

Oracle DROP TABLE Statement


Is used to remove or delete a table from the Oracle database.

Example
DROP TABLE customers;
This will drop the table named customers. Here both the structure and the records are
removed from the database.
Oracle TRUNCATE TABLE

In Oracle, TRUNCATE TABLE statement is used to remove only the records from a table,
but the structure of the table remains.
Example
TRUNCATE TABLE EMPLOYEE;
The records of EMPLOYEE table are removed from the database.

Note :

TRUNCATE TABLE vs DELETE TABLE


Both the statements will remove the data from the "customers" table but the main difference
is that we can roll back the DELETE statement whereas we can't roll back the TRUNCATE
TABLE statement.

keys and ER diagram


1.Primary key
The candidate key which is very suitable to be the main key of table is a primary
key.
 Example

2.Composite key
Composite Key has two or more properties which specially identifies the
occurrence of an entity.
 Example:dob,name,contactno.,address.

3. secondary or Alternative key


All the keys which are not primary key are called an alternate key. It is
a candidate key which is currently not the primary key
 Example:
4. Foreign key
Generally foreign key is a primary key from one table, which has a relationship
with another table.
 Example:
E-R MODEL (Entity-Relationship Model)

1. Entity
2. Attribute
3. Relationship
1. Entity
An entity is an object or component of data. An entity is represented as
rectangle in an ER diagram.
For example: In the following ER diagram we have two entities Student and
College and these two entities have many to one relationship as many
students study in a single college. We will read more about relationships later,
for now focus on entities.

Weak Entity:
An entity that cannot be uniquely identified by its own attributes and
relies on the relationship with other entity is called weak entity. The weak
entity is represented by a double rectangle. For example – a bank account
cannot be uniquely identified without knowing the bank to which the account
belongs, so bank account is a weak entity.

2. Attribute
An attribute describes the property of an entity. An attribute is represented as
Oval in an ER diagram. There are four types of attributes:
1. Key attribute
2. Composite attribute
3. Multivalued attribute
4. Derived attribute

1. Key attribute:
A key attribute can uniquely identify an entity from an entity set. For example,
student roll number can uniquely identify a student from a set of students. Key
attribute is represented by oval same as other attributes however the text of
key attribute is underlined.

2. Composite attribute:
An attribute that is a combination of other attributes is known as composite
attribute. For example, In student entity, the student address is a composite
attribute as an address is composed of other attributes such as pin code,
state, country.

3. Multivalued attribute:
An attribute that can hold multiple values is known as multivalued attribute. It
is represented with double ovals in an ER Diagram. For example – A person
can have more than one phone numbers so the phone number attribute is
multivalued.
4. Derived attribute:
A derived attribute is one whose value is dynamic and derived from another
attribute. It is represented by dashed oval in an ER Diagram. For example –
Person age is a derived attribute as it changes over time and can be derived
from another attribute (Date of birth).
E-R diagram with multivalued and derived attributes:

3. Relationship
A relationship is represented by diamond shape in ER diagram, it shows the
relationship among entities. There are four types of relationships:
1. One to One
2. One to Many
3. Many to One
4. Many to Many

1. One to One Relationship


When a single instance of an entity is associated with a single instance of
another entity then it is called one to one relationship. For example, a person
has only one passport and a passport is given to one person.

2. One to Many Relationship


When a single instance of an entity is associated with more than one
instances of another entity then it is called one to many relationship. For
example – a customer can place many orders but a order cannot be placed by
many customers.

3. Many to One Relationship


When more than one instances of an entity is associated with a single
instance of another entity then it is called many to one relationship. For
example – many students can study in a single college but a student cannot
study in many colleges at the same time.

4. Many to Many Relationship


When more than one instances of an entity is associated with more than one
instances of another entity then it is called many to many relationship. For
example, a student can be assigned to many projects and a project can be
assigned to many students.

Oracle Data Types


VARCHAR2(size [BYTE | CHAR])

Variable-length character string having maximum length size bytes or


characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte
or 1 character. You must specify size for VARCHAR2.

NVARCHAR2(size)

Variable-length Unicode character string having maximum


length size characters. Maximum size is determined by the national
character set definition, with an upper limit of 4000 bytes. You must
specify size for NVARCHAR2.

NUMBER[(precision [, scale]])

Number having precision p and scale s. The precision p can range from 1 to 38.
The scale s can range from -84 to 127.

LONG

Character data of variable length up to 2 gigabytes, or 231 -1 bytes. Provided for


backward compatibility.

DATE

The size is fixed at 7 bytes. This data type contains the date time
fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It does not have
fractional seconds or a time zone.

BINARY_FLOAT

32-bit floating point number. This datatype requires 5 bytes, including the
length byte.

BINARY_DOUBLE

64-bit floating point number. This datatype requires 9 bytes, including the
length byte.

TIMESTAMP [(fractional_seconds)]

The sizes varies from 7 to 11 bytes, depending on the precision. This datatype
contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE,
and SECOND. It contains fractional seconds but does not have a time zone.

TIMESTAMP [(fractional_seconds)] WITH TIME ZONE

The size is fixed at 13 bytes. This datatype contains the datetime


fields YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR,
and TIMEZONE_MINUTE. It has fractional seconds and an explicit time zone.
RAW(size)

Raw binary data of length size bytes. Maximum size is 2000 bytes. You
must specify size for a RAW value.

LONG RAW

Raw binary data of variable length up to 2 gigabytes.

CHAR [(size [BYTE | CHAR])]

Fixed-length character data of length size bytes. Maximum size is 2000


bytes or characters. Default and minimum size is 1 byte.

BYTE and CHAR have the same semantics as for VARCHAR2.

NCHAR[(size)]

Fixed-length character data of length size characters. The number of bytes can
be up to two times size for AL16UTF16 encoding and three
times size for UTF8 encoding. Maximum size is determined by the national
character set definition, with an upper limit of 2000 bytes. Default and
minimum size is 1 character.

CLOB

A character large object containing single-byte or multibyte characters.


Both fixed-width and variable-width character sets are supported, both using the
database character set. Maximum size is (4 gigabytes - 1) * (database block
size). It stores large amounts of character data, up to 4 GB in size.

NCLOB

A character large object containing Unicode characters. Both fixed-width and


variable-width character sets are supported, both using the database national
character set. Maximum size is (4 gigabytes - 1) * (database block size). Stores
national character set data.

BLOB
A binary large object. Maximum size is (4 gigabytes - 1) * (database block
size). Since blobs can store binary data, they can be used to store
images or other multimedia files.

Tables
What is a table?
The data in an RDBMS is stored in database objects which are called as tables.
This table is basically a collection of related data entries and it consists of numerous
columns and rows.
Remember, a table is the most common and simplest form of data storage in a
relational database. The following program is an example of a CUSTOMERS table

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
+----+----------+-----+-----------+----------+

What is a field?
Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about
every record in the table.

What is a Record or a Row?


A record is also called as a row of data is each individual entry that exists in a table.
For example, there are 7 records in the above CUSTOMERS table. Following is a
single row of data or record in the CUSTOMERS table −
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
A record is a horizontal entity in a table.

What is a column?
A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents
location description and would be as shown below −
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+

What is a NULL value?


A NULL value in a table is a value in a field that appears to be blank, which means
a field with a NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or
a field that contains spaces. A field with a NULL value is the one that has been left
blank during a record creation.

Constraints
Constraints are the rules enforced on the data columns of a table. These are used
to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the database.
Constraints could be either on a column level or a table level. The column level
constraints are applied only to one column, whereas the table level constraints are
applied to the whole table

Types of Constraints in DBMS-

In DBMS, there are following 5 different types of relational constraints-


1. Domain constraint
2. Tuple Uniqueness constraint
3. Key constraint
4. Entity Integrity constraint
5. Referential Integrity constraint

1. Domain Constraint-

 Domain constraint defines the domain or set of values for an attribute.


 It specifies that the value taken by the attribute must be the atomic value from its domain.

Example-

Consider the following Student table-


STU_ID Name Age

S001 Akshay 20

S002 Abhishek 21

S003 Shashank 20

S004 Rahul A

Here, value ‘A’ is not allowed since only integer values can be taken by the age attribute.

2. Tuple Uniqueness Constraint-

Tuple Uniqueness constraint specifies that all the tuples must be necessarily unique in any
relation.

Example-01:

Consider the following Student table-


STU_ID Name Age
S001 Akshay 20

S002 Abhishek 21

S003 Shashank 20

S004 Rahul 20
This relation satisfies the tuple uniqueness constraint since here all the tuples are unique.
Example-02:

Consider the following Student table-

STU_ID Name Age

S001 Akshay 20

S001 Akshay 20

S003 Shashank 20

S004 Rahul 20

This relation does not satisfy the tuple uniqueness constraint since here all the tuples are not
unique.
3. Key Constraint-

Key constraint specifies that in any relation-


 All the values of primary key must be unique.
 The value of primary key must not be null.

Example-

Consider the following Student table-

STU_ID Name Age

S001 Akshay 20

S001 Abhishek 21

S003 Shashank 20

S004 Rahul 20

This relation does not satisfy the key constraint as here all the values of primary key are not
unique.

4. Entity Integrity Constraint-


 Entity integrity constraint specifies that no attribute of primary key must contain a null
value in any relation.
 This is because the presence of null value in the primary key violates the uniqueness
property.

Example-

Consider the following Student table-

STU_ID Name Age

S001 Akshay 20

S002 Abhishek 21

S003 Shashank 20

Rahul 20

This relation does not satisfy the entity integrity constraint as here the primary key contains a
NULL value.

5. Referential Integrity Constraint-


This constraint is enforced when a foreign key references the primary key of a relation.
 It specifies that all the values taken by the foreign key must either be available in the
relation of the primary key or be null.

Important Results-

The following two important results emerges out due to referential integrity constraint-
 We can not insert a record into a referencing relation if the corresponding record does not
exist in the referenced relation.
 We can not delete or update a record of the referenced relation if the corresponding record
exists in the referencing relation.

Example-

Consider the following two relations- ‘Student’ and ‘Department’.


Here, relation ‘Student’ references the relation ‘Department’.
Student
STU_ID Name Dept_no

S001 Akshay D10

S002 Abhishek D10

S003 Shashank D11

S004 Rahul D14

Department
Dept_no Dept_name

D10 ASET

D11 ALS

D12 ASFL

D13 ASHS

Here,
 The relation ‘Student’ does not satisfy the referential integrity constraint.
 This is because in relation ‘Department’, no value of primary key specifies department no.
14.
 Thus, referential integrity constraint is violated.
Indexing
An index is a database object. It is used by the server to speed up the
retrieval of rows by using a pointer.

It uses a rapid path access method to locate data quickly.

An index helps to speed up select queries and where clauses, but it slows
down data input, with the update and the insert statements.

Indexes can be created or dropped with no effect on the data.

For example, if you want to reference all pages in a book that discusses a
certain topic, you first refer to the index, which lists all the topics
alphabetically and is then referred to one or more specific page numbers.
`Creating an Index – It’s syntax is:

CREATE INDEX index_name ON TABLE_NAME column_name;


where the index_name is the name given to that index and TABLE_NAME is
the name of the table on which that index is created and column_name is the
name of that column for which it is applied.

CREATE INDEX index_name ON TABLE_NAME (column1, column2,.....);


Unique Indexes –

CREATE UNIQUE INDEX index


ON TABLE column;

Unique indexes are used for the maintenance of the integrity of the data
present in the table as well as for the fast performance, it does not allow
multiple values to enter into the table.
When indexes should be created –

 A column contains a wide range of values


 A column does not contain a large number of null values
 One or more columns are frequently used together in a where clause or a
join condition
When indexes should be avoided –

 The table is small


 The columns are not often used as a condition in the query
 The column is updated frequently
Removing an Index – To remove an index from the data dictionary by using
the DROP INDEX command.

DROP INDEX index;

To drop an index, you must be the owner of the index or have the DROP
ANY INDEX privilege.

Altering an Index: To modify an existing table’s index by rebuilding, or


reorganizing the index.
ALTER INDEX IndexName
ON TableName REBUILD;
Confirming Indexes – You can check the different indexes present in a
particular table given by the user or the server itself and their uniqueness.

select * from USER_INDEXES;

It will show you all the indexes present in the server, in which you can locate
your own tables too.

Renaming an index – You can use system stored procedure sp_rename to


rename any index in the database.
EXEC sp_rename
index_name,
new_index_name;`

Views
A view is nothing more than a SQL statement that is stored in the database with an
associated name.
A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or selected rows from a table.
A view can be created from one or many tables which depends on the written SQL query to
create a view.
Views, which are a type of virtual tables, allow users to do the following −
 Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.
 Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created
from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you
use them in a normal SQL SELECT query.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table.
Following is an example for the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
The WITH CHECK OPTION
The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the
WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the
condition(s) in the view definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating same view CUSTOMERS_VIEW with
the WITH CHECK OPTION.
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the
view's AGE column, because the view is defined by data that does not have a NULL value
in the AGE column.
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
Inserting Rows into a View
Rows of data can be inserted into a view. The same rules that apply to the UPDATE
command also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all
the NOT NULL columns in this view, otherwise you can insert rows in a view in a similar
way as you insert them in a table.
Deleting Rows into a View
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and
INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.
SQL > DELETE FROM CUSTOMERS_VIEW
WHERE age = 22;
This would ultimately delete a row from the base table CUSTOMERS and the same would
reflect in the view itself. Now, try to query the base table and the SELECT statement would
produce the following result.
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer
needed. The syntax is very simple and is given below −
DROP VIEW view_name;
Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table.
DROP VIEW CUSTOMERS_VIEW;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy