SQL Views and Indexes
SQL Views and Indexes
Views in SQL are a kind of virtual table. A view also has rows and columns like tables, but a view
doesn’t store data on the disk like a table. View defines a customized query that retrieves data from
one or more tables, and represents the data as if it was coming from a single source.
We can create a view by selecting fields from one or more tables present in the database. A View can
either have all the rows of a table or specific rows based on certain conditions.
In this article, we will learn about creating, updating, and deleting views in SQL.
StudentDetails
StudentMarks
You can create these tables on your system by writing the following SQL query:
MySQL
NAME VARCHAR(255),
ADDRESS VARCHAR(255)
);
VALUES
NAME VARCHAR(255),
Marks INT,
Age INT
);
VALUES
We can create a view using CREATE VIEW statement. A View can be created from a single table or
multiple tables.
Syntax
Parameters:
Let’s look at some examples of CREATE VIEW Statement in SQL to get a better understanding of how
to create views in SQL.
In this example, we will create a View named DetailsView from the table StudentDetails. Query:
To see the data in the View, we can query the view in the same manner as we query a table.
Output:
In this example, we will create a view named StudentNames from the table StudentDetails. Query:
Output:
Example 3: Creating View from multiple tables
In this example we will create a View named MarksView from two tables StudentDetails and
StudentMarks. To create a View from multiple tables we can simply include multiple tables in the
SELECT statement. Query:
Output:
We can list View using the SHOW FULL TABLES statement or using the information_schema table. A
View can be created from a single table or multiple tables.
Syntax
USE "database_name";
SHOW FULL TABLES WHERE table_type LIKE "%VIEW";
Using information_schema
SELECT table_name
FROM information_schema.views
WHERE table_schema = 'database_name';
OR
SQL allows us to delete an existing View. We can delete or drop View using the DROP statement.
Syntax
Example
If you want to update the existing data within the view, use the UPDATE statement.
Syntax
UPDATE view_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Note: Not all views can be updated using the UPDATE statement.
If you want to update the view definition without affecting the data, use the CREATE OR REPLACE
VIEW statement. you can use this syntax
Certain conditions need to be satisfied to update a view. If any of these conditions are not met, the
view can not be updated.
1. The SELECT statement which is used to create the view should not include GROUP BY clause
or ORDER BY clause.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables
then we will not be allowed to update the view.
Examples
Let’s look at different use cases for updating a view in SQL. We will cover these use cases with
examples to get a better understanding.
If we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this by:
Output:
We can insert a row in a View in the same way as we do in a table. We can use the INSERT
INTO statement of SQL to insert a row in a View.
In the below example, we will insert a new row in the View DetailsView which we have created
above in the example of “creating views from a single table”.
Output:
Deleting rows from a view is also as simple as deleting rows from a table. We can use the DELETE
statement of SQL to delete rows from a view. Also deleting a row from a view first deletes the row
from the actual table and the change is then reflected in the view.
In this example, we will delete the last row from the view DetailsView which we just added in the
above example of inserting rows.
Output:
The WITH CHECK OPTION clause in SQL is a very useful clause for views. It applies to an updatable
view.
The WITH CHECK OPTION clause is used to prevent data modification (using INSERT or UPDATE) if the
condition in the WHERE clause in the CREATE VIEW statement is not satisfied.
If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the UPDATE or
INSERT clause does not satisfy the conditions then they will return an error.
In the below example, we are creating a View SampleView from the StudentDetails Table with a
WITH CHECK OPTION clause.
In this view, if we now try to insert a new row with a null value in the NAME column then it will give
an error because the view is created with the condition for the NAME column as NOT NULL. For
example, though the View is updatable then also the below query for this View is not valid:
Uses of a View
2. Hiding data complexity – A view can hide the complexity that exists in multiple joined tables.
3. Simplify commands for the user – Views allow the user to select information from multiple
tables without requiring the users to actually know how to perform a join.
5. Rename Columns – Views can also be used to rename the columns without affecting the
base tables provided the number of columns in view must match the number of columns
specified in a select statement. Thus, renaming helps to hide the names of the columns of
the base tables.
6. Multiple view facility – Different views can be created on the same table for different users.
We can create a view using the CREATE VIEW statement and delete a view using the DROP
VIEW statement.
WITH CHECK OPTION clause is used to prevent inserting new rows that do not satisfy the
view’s filtering condition.
SQL Indexes
An index is a schema object. It is used by the server to speed up the retrieval of rows by using a
pointer. It can reduce disk I/O(input/output) by using 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. In
this article, we will see how to create, delete, and use the INDEX in the database.
Creating an Index
Syntax
ON TABLE column;
where the index is the name given to that index TABLE is the name of the table on which that index
is created and column is the name of that column for which it is applied.
Syntax:
CREATE INDEX index
Unique indexes are used for the maintenance of the integrity of the data present in the table as well
as for fast performance, it does not allow multiple values to enter into the table.
Syntax:
ON TABLE column;
One or more columns are frequently used together in a where clause or a join condition.
Removing an Index
Remove an index from the data dictionary by using the DROP INDEX command.
Syntax
To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.
Altering an Index
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.
Syntax:
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 the system-stored procedure sp_rename to rename any index in the database.
Syntax:
EXEC sp_rename
index_name,
new_index_name,
N’INDEX’;
Syntax:
Indexing is an important topic when considering advanced MySQL, although most people know
about its definition and usage they don’t understand when and where to use it to change the
efficiency of our queries or stored procedures by a huge margin.
Here are some scenarios along with their explanation related to Indexing:
When executing a query on a table having huge data ( > 100000 rows ), MySQL performs a
full table scan which takes much time and the server usually gets timed out. To avoid this
always check the explain option for the query within MySQL which tells us about the state of
execution. It shows which columns are being used and whether it will be a threat to huge
data. On basis of the columns repeated in a similar order in condition.
The order of the index is of huge importance as we can use the saitions, we can create an
index for them in the same order to maximize the speed of the query. me index in many
scenarios. Using only one index we can utilize it in more than one query which different
conditions. like for example, in a query, we make a join with a table based on customer_id
wards we also join another join based on customer_id and order_date. Then we can simply
create a single index by the order of customer_id, order_date which would be used in both
cases. This also saves storage.
We should also be careful to not make an index for each query as creating indexes also take
storage and when the amount of data is huge it will create a problem. Therefore, it’s
important to carefully consider which columns to index based on the needs of your
application. In general, it’s a good practice to only create indexes on columns that are
frequently used in queries and to avoid creating indexes on columns that are rarely used. It’s
also a good idea to periodically review the indexes in your database and remove any that are
no longer needed.
Indexes can also improve performance when used in conjunction with sorting and grouping
operations. For example, if you frequently sort or group data based on a particular column,
creating an index on that column can greatly improve performance. The index allows MySQL
to quickly access and sort or group the data, rather than having to perform a full table scan.
In some cases, MySQL may not use an index even if one exists. This can happen if the query
optimizer determines that a full table scan is faster than using the index.
Conclusion
Enhance query speed, however, inserts and updates might take longer.
Indexes must be carefully selected and kept up-to-date in order for database operations to go
smoothly.