0% found this document useful (0 votes)
25 views132 pages

DBMS - Sub Q index triger cursor

dbms

Uploaded by

suiiisimon0
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)
25 views132 pages

DBMS - Sub Q index triger cursor

dbms

Uploaded by

suiiisimon0
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/ 132

Database Management Systems

(DBMS)
What is DBMS? Database Management Systems (DBMS) are software systems
used to store, retrieve, and run queries on data. A DBMS serves as an
interface between an end-user and a database, allowing users to create, read,
update, and delete data in the database.
Unit - II
Relational Database
What is a Relational Database (RDBMS)?
• Type of database that stores and provides access to data
points that are related to one another.
• based on the relational model, straightforward way of
representing data in tables.
• In a relational database, each row in the table is a record
with a unique ID called the key.

In this model, the data is organized into a collection


of two-dimensional inter-related tables, also known
as relations.
What is Relational Model?
• Relational Model (RM) represents the database as a collection of relations. A
relation is nothing but a table of values. Every row in the table represents a
collection of related data values. These rows in the table denote a real-world
entity or relationship.

• The table name and column names are helpful to interpret the meaning of
values in each row. The data are represented as a set of relations. In the
relational model, data are stored as tables. However, the physical storage of
the data is independent of the way the data are logically organized.
Some popular Relational Database
management systems are
• DB2 and Informix Dynamic Server – IBM
• Oracle and RDB – Oracle
• SQL Server and Access – Microsoft
Relational Model Concepts in DBMS
1.Attribute: Each column in a Table. Attributes are the properties which define a relation. e.g.,
Student_Rollno, NAME,etc.
2.Tables – In the Relational model the, relations are saved in the table format. It is stored along with
its entities. A table has two properties rows and columns. Rows represent records and columns
represent attributes.
3.Tuple – It is nothing but a single row of a table, which contains a single record.
4.Degree: The total number of attributes which in the relation is called the degree of the relation.
5.Cardinality: Total number of rows present in the Table.
6.Column: The column represents the set of values for a specific attribute.
7.Relation Schema: A relation schema represents the name of the relation with its attributes.
8.Relation instance – Relation instance is a finite set of tuples in the RDBMS system. Relation
instances never have duplicate tuples.
9.Relation key – Every row has one, two or multiple attributes, which is called relation key.
10.Attribute domain – Every attribute has some pre-defined value and scope which is known as
attribute domain
11.Entity is a real-world thing which can be distinctly identified like a person, place or a concept. It is
an object which is distinguishable from others.
Characteristics of Relational Database
Model
Now, each relation must be uniquely
identified. If it is not so, then it would create
a lot of confusion
• 1. Each relation in a database must have
a distinct or unique name which would
separate it from the other relations in a
database.
• 2. A relation must not have two
attributes with the same name. Each
attribute must have a distinct name.
• 3. Duplicate tuples must not be present in a
relation.
• 4. Each tuple must have exactly one data value for an attribute. For example,
below in the first table, you can see that for Roll_No. 265 we have enrolled
two students Jhoson and Charles, this would not work. We must have only
one student for one Roll_No.

5.Tuples in a relation do not have to follow a significant order as the relation is not order-
sensitive.
6. Similarly, the attributes of a relation also do not have to follow certain ordering, it’s up
to the developer to decide the ordering of attributes.
Constraints
• Constraints in DBMS (Database Management Systems)
are rules or conditions that are applied to the data within a
database to ensure data integrity, consistency.
1.rules that are to be followed while entering data into columns of the database
table
2.Constraints ensure that data entered by the user into columns must be within
the criteria specified by the condition

limitation
or
restriction
Domain constraints
• domain constraints in DBMS could specify that the values in a gender
column must be either male or female.
•Referential integrity is the state in which all
values of all foreign keys are valid.
• Referential integrity is based on entity integrity .
•Entity integrity requires that each entity have a
unique key.
Entity integrity constraint
• To identify each row in a table, the table must have a primary key. The
primary key is a unique value that identifies each row. This requirement is
called the entity integrity constraint .
For example, the orders table primary key is D_No.
Key Constraints
•We have 5 types of key constraints in DBMS
•NOT NULL: ensures that the specified column doesn’t contain a
NULL value.
•UNIQUE : provides a unique/distinct values to specified
columns.
•DEFAULT: provides a default value to a column if none is
specified.
•CHECK :checks for the predefined conditions before
inserting the data inside the table.
•PRIMARY KEY: it uniquely identifies a row in a table.
•FOREIGN KEY: ensures referential integrity of the relationship
Not Null
Null represents a record where data may
be missing data or data for that record
may be optional
Once not null is applied to a particular
column, you cannot enter null values to
that column and restricted to
maintain only some proper value other
than null
A not-null constraint cannot be applied at
table level
https://cstaleem.com/unary-operators-in-relational-algebra

Relational Algebra
• Relational algebra is a procedural query language. It gives a step by step
process to obtain the result of the query. It uses operators to perform
queries.
Relational Algebra is not actually implemented anywhere. It is collection of mathematical
expressions. So it is a theoretical or logical model to access the database.

This theoretical database model came in 1970. This model was develop by EF CODE which
is consider as the father of Database.

Relational Algebra is a procedural query language or formal query language. In procedural


query language every user has to mention two things to access data
Relational – (Table) 1.What to do?
Algebra – (Operators) 2.How to do?
“DBMS”

“DBMS”
ρ(RelationNew, RelationOld)

ρ(e_name,name)(Emp) π e_name(Emp)
JOIN
A JOIN clause is used to combine rows from two or more
tables, based on a related column between them

•(INNER) JOIN: Returns records that have matching values in both tables.

•LEFT (OUTER) JOIN: Returns all records from the left table(table1), and the matched records from the right
table(table2).

•RIGHT (OUTER) JOIN: Returns all records from the right table(table2), and the matched records from the
left table(table1).

•FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table.
Products Categories
ProductI ProductN Supplier Category Unit Price CategoryID CategoryName Description
D ame ID ID
1 Beverages Soft drinks, coffees,
1 Chais 1 1 10 boxes x 18 teas, beers, and ales
20 bags
2 Chang 1 1 24 - 12 oz 19 2 Condiments Sweet and savory
bottles sauces, relishes,
3 Aniseed 1 2 12 - 550 ml 10 spreads, and
Syrup bottles seasonings
4 Chef 2 2 48 - 6 oz 22
Anton's jars 3 Confections Desserts, candies, and
Cajun sweet breads
Seasoning
5 Chef 2 2 36 boxes 21.35
4 Dairy Products Cheeses
Anton's
Gumbo Mix
5 Grains/Cereals Breads, crackers, pasta,
6 Grandma's 3 2 12 - 8 oz 25 and cereal
Boysenberr jars
y Spread
6 Meat/Poultry Prepared meats
7 Uncle Bob's 3 7 12 - 1 lb 30
Organic pkgs.
7 Produce Dried fruit and bean
Dried Pears
curd
8 Northwoods 3 2 12 - 12 oz 40
Cranberry jars 8 Seafood Seaweed and fish
Sauce
SELECT ProductID, ProductName, CategoryName
FROM Products INNER JOIN
Categories ON
Products.CategoryID = Categories.CategoryID;
ProductID ProductName CategoryName

39 Chartreuse verte Beverages

2 Chang Beverages
24 Guaraná Fantástica Beverages

34 Sasquatch Ale Beverages

35 Steeleye Stout Beverages

1 Chais Beverages

38 Côte de Blaye Beverages


43 Ipoh Coffee Beverages
SQL Joins (Inner, Left, Right and Full Join)
• SQL Join operation combines data or rows from two or more tables
based on a common field between them.

• SQL JOIN clause is used to query and access data from multiple tables
by establishing logical relationships between them. It can access data
from multiple tables simultaneously using common key values shared
across different tables.
SQL JOIN Example
Consider the two tables below as follows:

Student:
StudentCourse :
• Both these tables are connected by one common key (column)
i.e ROLL_NO.

SELECT s.roll_no, s.name, s.address,


s.phone, s.age, sc.course_id FROM
Student s
JOIN StudentCourse sc ON s.roll_no =
sc.roll_no;
Output:
• There are many types of Joins in SQL. Depending on the use case, you
can use different type of SQL JOIN clause.

• Here are the frequently used SQL JOIN types:

1.INNER JOIN
2.LEFT JOIN
3.RIGHT JOIN
4.FULL JOIN
• SQL INNER JOIN
The INNER JOIN keyword selects all rows from both the tables
as long as the condition is satisfied. This keyword will create the result-
set by combining all rows from both the tables where the condition
satisfies i.e value of the common field will be the same.
• Syntax:
The syntax for SQL INNER JOIN is:

SELECT
table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
• Here,
• table1: First table.
• table2: Second table
• matching_column: Column common to both the tables.

• Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.
• INNER JOIN Example
• Let’s look at the example of INNER JOIN clause, and understand it’s
working.
• This query will show the names and age of students enrolled in
different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME,


Student.AGE FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
• Output:
SQL LEFT JOIN
• LEFT JOIN returns all the rows of the table on the left side of the join
and matches rows for the table on the right side of the join. For the
rows for which there is no matching row on the right side, the result-
set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
• Syntax:
The syntax of LEFT JOIN in SQL is:
SELECT
table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column =
table2.matching_column;
• Here,
• table1: First table.
• table2: Second table
• matching_column: Column common to both the tables.
• Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
SQL RIGHT JOIN
• RIGHT 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 the join.It is
very similar to LEFT JOIN For the rows for which there is no matching
row on the left side, the result-set will contain null. RIGHT JOIN is
also known as RIGHT OUTER JOIN.
• RIGHT JOIN Example:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output
SQL FULL JOIN
• FULL JOIN creates the result-set by combining results of both LEFT
JOIN and RIGHT JOIN. The result-set will contain all the rows from
both tables. For the rows for which there is no matching, the result-
set will contain NULL values.
SELECT
Student.NAME,StudentCourse.COUR
SE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO =
Student.ROLL_NO;

Output
Characteristics of SQL, advantages of SQL
Structured Query Language
Standard database language used by almost every Relational Database
Management System (RDMS) such as MySQL, MS Access, Oracle, Postgres, and
SQL Server.
It is a computer language used to store, manipulate, and retrieve data from a
relational database. SQL may do a variety of other tasks, including database
optimization and maintenance.
• Why is SQL Used?
• SQL is useful for querying and maintaining data in a relational database management
system. This is one of the most common uses of SQL.

• It is used to change or modify previous data

• It provides a large number of commands that allow us to perform a variety of database


activities.

• SQL is also used to maintain transactions in a database.

• Almost every website today is supported by a backend database. SQL is most commonly
used to connect with that database.

• Setting table, procedure, and view permissions

• To create functions, views, and to store procedures


SQL data type - SQL operators
Queries and Subqueries in SQL
&
Aggregate Functions in SQL
Queries and Subqueries in SQL
A query is an operation that retrieves data from one or more tables or views. In this
reference, a top-level SELECT statement is called a query, and a query nested within another
SQL statement is called a subquery.

A Subquery is a query
within another SQL
query and embedded
within the WHERE
clause.
•A subquery can be placed in a number of SQL clauses like
WHERE clause, FROM clause, HAVING clause.
•You can use Subquery with SELECT, UPDATE, INSERT, DELETE
statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN, etc.
•A subquery is a query within another query. The outer query is
known as the main query, and the inner query is known as a
subquery.
•Subqueries are on the right side of the comparison operator.
•A subquery is enclosed in parentheses.
•In the Subquery, ORDER BY command cannot be used. But
GROUP BY command can be used to perform the same function
as ORDER BY command.
Subqueries with the Select Statement
SELECT column_name FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );

SELECT * FROM t1 WHERE column1 = (SELECT


column1 FROM t2) In this example, SELECT * FROM
t1 b(SELECT column1 FROM t2) is the subquery.
Sample Table:
DATABASE
NAME ROLL_NO LOCATION PHONE_NUMBER
Ram 101 Chennai 9988775566
Raj 102 Coimbatore 8877665544
Sasi 103 Madurai 7766553344
Ravi 104 Salem 8989898989
Sumathi 105 Kanchipuram 8989856868 STUDENT
NAME ROLL_NO SECTION
Ravi 104 A
Sumathi 105 B
Raj 102 A
Sample Queries:
• To display NAME, LOCATION, PHONE_NUMBER of the students from
DATABASE table whose section is A

SELECT NAME, LOCATION, PHONE_NUMBER


FROM DATABASE
WHERE ROLL_NO IN (SELECT ROLL_NO
FROM STUDENT
WHERE SECTION='A');
•Explanation : First subquery executes “ SELECT ROLL_NO from STUDENT where
SECTION=’A’ ” returns ROLL_NO from STUDENT table whose SECTION is ‘A’.Then
outer-query executes it and return the NAME, LOCATION, PHONE_NUMBER from
the DATABASE table of the student whose ROLL_NO is returned from inner
subquery. Output:
Output
NAME LOCATION PHONE_NUMBER

Ravi Salem 8989898989

Raj Coimbatore 8877665544


Insert Query Example:
Table1: Student1
NAME ROLL_NO LOCATION PHONE_NUMBER
Ram 101 chennai 9988773344
Raju 102 coimbatore 9090909090
Ravi 103 salem 8989898989

Table2: Student2
NAME ROLL_NO LOCATION PHONE_NUMBER
Raj 111 chennai 8787878787

Sai 112 mumbai 6565656565

Sri 113 coimbatore 7878787878


• To insert Student2 into Student1 table:
INSERT INTO Student1
SELECT * FROM Student2;

Output Now consider Student1

NAME ROLL_NO LOCATION PHONE_NUMBER


Ram 101 chennai 9988773344
Raju 102 coimbatore 9090909090
Ravi 103 salem 8989898989
Raj 111 chennai 8787878787
Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878
Delete Query Example:
DELETE FROM Student2
WHERE ROLL_NO IN (SELECT ROLL_NO
FROM Student1
WHERE LOCATION = 'chennai');

NAME ROLL_NO LOCATION PHONE_NUMBER


Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878
Follow one by one all query
Aggregate Functions in SQL
An aggregate function in SQL returns one value after calculating multiple values of a column. We often use
aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement.
Aggregate Functions in SQL

In SQL, aggregate functions are used to calculate a set of values and return a single value. When using
aggregate functions in SQL, it is crucial to understand column references. A column reference is a name
containing the data you want to aggregate. To use an aggregate function with a column reference, specify
the column's name in the function's parentheses.

https://www.simplilearn.com/tutorials/sql-tutorial/sql-aggregate-functions
AVG () funcation
• For example, to find the average salary of employees in a table
called "employees", you would use the AVG function with the
column reference "salary" like this:

SELECT AVG (salary) FROM employees;

• Using column aliases instead of column references is also


possible for a more readable code. However, understanding
column references is essential when working with SQL
aggregate functions.
COUNT() Function
The COUNT() function returns the number of rows in a database
table.
Syntax:
COUNT(*)
Example
We will use the ‘products’ table from the sample database for
our demonstration.
This will produce the following result.
The below-given command will display those product ids where
the unit price is greater than 4.

This will display the following result.


Let's look at how we can use GROUP BY and HAVING functions
with the COUNT function.
Consider the following dataset:
This will produce the following results:
SUM() Function
The SUM() function returns the total sum of a numeric column.
Syntax:
SUM()
• Example:
The following SQL statement finds the sum of the "unit price"
fields in the "products" table:
This will produce the following result:
AVG() Function
The AVG() function calculates the average of a set of values.
Syntax:
AVG()

This will produce the following result.


MIN() Function
The MIN() aggregate function returns the lowest value
(minimum) in a set of non-NULL values.
Syntax:
MIN()
Cursor in SQL
Whenever DML statements are
executed, a temporary work area is created
in the system memory and it is called a cursor.
A cursor can have more than one row,
but processing wise only 1 row is taken into
account. Cursors are very helpful in all kinds
of databases like Oracle, SQL Server, MySQL,
etc
Cursor is a Temporary Memory or Temporary
Work Station. It is Allocated by Database Server at
the Time of Performing DML(Data Manipulation
Language) operations on the Table by the User.
Cursors are used to store Database Tables.

There are 2 types of Cursors:


Implicit Cursors, and
Explicit Cursors.
TCL - Transaction Control Language
•COMMIT: Permanently saves changes made to the database
•ROLLBACK: Undoes changes made to the database
•SAVEPOINT: Temporarily saves the state of a transaction
Cursor in SQL
Cursor is a temporary workstation that is allocated by the database server
during the execution of a statement.
- Access data of one row at a time.
Types of Cursor in SQL
1.Implicit Cursor
These types of cursors are generated and allocated by the SQL server
when the system performs INSERT, DELETE, and UPDATE operations on SQL
queries.
This cursor is also referred to as the default cursor in SQL.

2.Explicit Cursor
These types of cursors are created by the user using the SELECT query,
cursor holds multiple records but processes a single row at a time
Life Cycle of Cursor
• The life cycle of the cursor is described into the following five stages:
1.Declare a Cursor
2.Open Cursor
3.Fetch Data from Cursor
4.Close Cursor Connection
5.Deallocate cursor
1. Declare a Cursor
First, we have to declare the cursor by using the following SQL syntax:
DECLARE Cursor_Name CURSOR FOR Select_Statement;

2. Open Cursor
It is the second stage that opens the cursor for storing the data retrieved from the result set. We can open
the cursor by using the following SQL syntax:
OPEN Cursor_Name;
3. Fetch Cursor
• It is the third stage in the cursor life cycle that fetches the rows for performing the
insertion, deletion, and updation operations on the currently active tuple in the cursor.
• Following are the six options that are used in syntax for fetching data from the cursor:
FIRST, LAST, NEXT, PRIOR, ABSOLUTE n
FETCH FIRST FROM Cursor_Name;
4. Close Cursor
It is the fourth stage in the process of the cursor. When we complete the
work with the cursor, we have to close the cursor in this stage. We can close
the cursor in SQL by using the following query:
CLOSE Cursor_Name;
5. Deallocate Cursor
It is the last and fifth stage of the cursor life cycle. In this part, we have
to erase the definition of the cursor and discharge all the system resources
combined with the cursor. DEALLOCATE Cursor_Name;
Syntax of a Cursor in SQL
1.DECLARE @YourVariables nvarchar(50)
//You have to declare all the required variables
2.DECLARE My_Cursor_Name CURSOR
// You have to declare the Name of your Cursor
3.OPEN My_Cursor_Name
// You have to Open Your Cursor
4.FETCH NEXT FROM My_Cursor_Name
// This line fetches the data from your Cursor
5.CLOSE My_Cursor_Name
// Here, you have to close Your Cursor
6.DEALLOCATE My_Cursor_Name
// Here, you have to deallocate the cursor memory.
https://www.youtube.com/watch?v=OuFJzs1hGxM
Triggers
SQL triggers are defined using SQL statements and are
associated with a specific table. When the defined trigger
event (e.g., INSERT, UPDATE, DELETE) occurs on that table,
the associated trigger code is executed automatically.
Automatically executed in response to certain events on a particular table.

Trigger in SQL codes that are SQL works similar to a real-world trigger

For example, when the gun trigger is pulled a bullet is fired. We all know this,
but how this is related to Triggers in SQL?

https://www.youtube.com/watch?v=MOZwaPzL8As https://www.youtube.com/watch?v=lfzfkxzZ_CA
An SQL trigger is a database object that is associated
with a table and automatically executes a set of SQL
statements when a specific event occurs on that table.
Triggers are used to enforce business rules, maintain data
integrity, and automate certain actions within a database.

• What is a Trigger?
• Syntax and Example
• Operation in Triggers
Syntax
Create Trigger Trigger_Name
(Before | After) [ Insert | Update | Delete]
on [Table_Name]
[ for each row | for each column ]
[ trigger_body ]
• Create Trigger
These two keywords are used to specify that a trigger block is going to be declared.
• Trigger_Name
It specifies the name of the trigger. Trigger name has to be unique and shouldn’t repeat.
• ( Before | After This specifies when the trigger will be executed. It tells us the time at which the trigger is initiated, i.e,
either before the ongoing event or after.
• Before Triggers are used to update or validate record values before they’re saved to the database.
• After Triggers are used to access field values that are set by the system and to effect changes in other records. The
records that activate the after trigger are read-only. We cannot use the After trigger if we want to update a record
because it will lead to a read-only error.
• [ Insert | Update | Delete ]
These are the DML operations and we can use either of them in a given trigger.
• on [ Table_Name We need to mention the table name on which the trigger is being applied. Don’t forget to
use on keyword and also make sure the selected table is present in the database.
• [ for each row | for each column ]
1. Row-level trigger gets executed before or after any column value of a row changes
2. Column Level Trigger gets executed before or after the specified column changes
CREATE TABLE purchase(productname varchar(30),
stock int);
INSERT INTO purchase VALUES(‘pipe',50);

test

CREATE TABLE sales(dateofsales date,


productname varchar(30), nos int);
DELIMITER //
Create Trigger salesstockupdate
BEFORE INSERT ON sales
FOR EACH ROW
BEGIN
UPDATE purchase SET stock = (stock - new.nos)
where productname = new.productname;
END //
INSERT INTO sales VALUES(curdate(),”pipe,20);

Output
1.Data Definition Language (DDL) Triggers
2.Data Manipulation Language (DML) Triggers
3.Logon Triggers
The DML triggers can be classified into two types:
1.After Triggers
2.Instead Of Triggers

After Triggers
After trigger fires, when SQL Server completes the triggering action
successfully, that fired it. Generally, this trigger is executed when a table
completes an insert, update or delete operations. It is not supported in views.
Sometimes it is known as FOR triggers.

We can classify this trigger further into three types:


1.AFTER INSERT Trigger
2.AFTER UPDATE Trigger
3.AFTER DELETE Trigger
1.CREATE TRIGGER schema_name.trigger_name
2.ON table_name
3.AFTER {INSERT | UPDATE | DELETE}
4.AS
5. BEGIN
6. -- Trigger Statements
7. -- Insert, Update, Or Delete Statements
8. END
•Instead of triggers executes prior to data
modification while
•After trigger executes after data modification.
Index and Views
Index
It makes the querying process fast by providing easy access to
rows in data tables.

Similar to how a book's index will quickly locate information


inside that book.

speed up query performance


CREATE INDEX index_name ON tableName (columnName1,
columnName2, ...);

CREATE INDEX name_in ON dataflair_employee (name_emp);


•As databases grow in size, finding
efficient ways to retrieve and
manipulate data becomes increasingly
important. A well-designed indexing
strategy is key to achieving this
efficiency.
Let's start with the basics of
indexing in databases. An index,
much like the index at the end of
a book, is a data structure that
speeds up data retrieval
operations. Just as a book index
lists keywords alongside page
numbers to help locate
information quickly, a database
index serves a similar purpose,
speeding up data retrieval without
needing to scan every row in a
database table.
Index
Select * from player where name = ‘Ramel’ and age = 22;
Clustered Index and Non-Clustered Index.
1.Clustered index is a type of index where the table records are
physically reordered to match with the index

2.Non-clustered index is a special type of index in which the logical


order of the index does not match with the physically stored order of
the rows on the disk
Key Clustered Index Non-Clustered Index
Clustered index is created on Non-clustered index can be
Basic
primary key. created on any key.
Store data physically according to It doesn't impact the order.
Ordering
the order.
Only one clustered index can be There can be any number of non-
Number of index there in a table. clustered indexes in a table.
No extra space is required to Extra space is required to store
Space
store logical structure. logical structure.
Data retrieval is faster than non- Data update is faster than
Performance
cluster index. clustered index.
The leaf nodes contains the The leaf nodes does not contain
Leaf node actual data in the clustered index. the actual data in the non-
clustered index.
A table can have only one A table can have multiple non
Number of indices
clustered index. clustered indices.
Clustered index contains main Non-clustered index contains a
Data
data. copy of data.
t
Views in SQL
•Views in SQL are considered as a virtual table.
A view also contains rows and columns.
•To create the view, we can select the fields
from one or more tables present in the
database.
•A view can either have specific rows based on
certain condition or all the rows of a table.
Joining
Advantages of View:
1.Complexity: Views help to reduce the complexity. Different views can be created
on the same base table for different users.
2.Security: It increases the security by excluding the sensitive information from
the view.
3.Query Simplicity: It helps to simplify commands from the user. A view can draw
data from several different tables and present it as a single table.
4.Consistency: A view can present a consistent, unchanged image of the structure
of the database. Views can be used to rename the columns without affecting the
base table.
5.Data Integrity: If data is accessed and entered through a view, the DBMS can
automatically check the data to ensure that it meets the specified integrity
constraints.
6.Storage Capacity: Views take very little space to store the data.
7.Logical Data Independence: View can make the application and database tables
to a certain extent independent.
Syntax
CREATE VIEW view_name AS SELECT column1, column2.....
FROM table_name WHERE condition;

Query
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FR
OM Student_Details WHERE STU_ID < 4;

SELECT * FROM DetailsView;


Student_Detail
STU_ID NAME ADDRESS

1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram

Output
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad

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