Sql-Unit 1
Sql-Unit 1
Sql-Unit 1
o DBMS architecture depends upon how users (clients) are connected to the
database to get their request done.
1-Tier Architecture
2-Tier Architecture
o The user interfaces and application programs are run on the client-side.
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 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.
Example:
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.
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.
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.
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:
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;
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
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.
Syntax:
ALTER TABLE table_name
ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);
Example
Syntax:
ALTER TABLE table_name
MODIFY column_name column_type;
Example:
ALTER TABLE customers
MODIFY customer_name varchar2(100) not null;
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.
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.
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.
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.
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 :
2.Composite key
Composite Key has two or more properties which specially identifies the
occurrence of an entity.
Example:dob,name,contactno.,address.
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
NVARCHAR2(size)
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
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.
Raw binary data of length size bytes. Maximum size is 2000 bytes. You
must specify size for a RAW value.
LONG RAW
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
NCLOB
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 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 |
+----+------+
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
1. Domain Constraint-
Example-
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.
Tuple Uniqueness constraint specifies that all the tuples must be necessarily unique in any
relation.
Example-01:
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:
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-
Example-
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.
Example-
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.
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-
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.
An index helps to speed up select queries and where clauses, but it slows
down data input, with the update and the insert statements.
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:
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 –
To drop an index, you must be the owner of the index or have the DROP
ANY INDEX privilege.
It will show you all the indexes present in the server, in which you can locate
your own tables too.
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;