DBMS Unit-II (1)
DBMS Unit-II (1)
In SQL, the 'Create Database' statement is a first step for storing the structured data in the database.
The database developers and the users use this statement in SQL for creating the new database in the database
systems. It creates the database with the name which has been specified in the Create Database statement.
Syntax
In this syntax, Database_Name specifies the name of the database which we want to create in the system. We
have to type the database name in query just after the 'Create Database' keyword.
Example
When this query is executed successfully, then it will show the following output:
Database created successfully
We can also verify that your database is created in SQL or not by using the following query:
SHOW DATABASE ;
Following are the most important points which are required to learn while creating a database:
The database we want to create should be a simple and unique name, which can be easily identified.
Database name should be no more than 128 characters.
SQL does not allow developers to create the database with the existing database name. Suppose if you want to create
another Student database in the same database system, then the Create Database statement will show the following error in
the output:
Can't create database 'Student'; database exists
So, firstly you have to delete the existing database by using the Drop Statement. You can also replace the existing database
with the help of Replace keyword.
If you want to replace the existing Student database, then you have to type the following SQL query:
• SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set
permission for users.
CREATE
ALTER
DROP
TRUNCATE
Syntax:
Example:
Syntax:
Example:
Syntax
Example
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
Syntax:
Example:
DML commands are used to modify the database. It is responsible for all form of changes in the database.
The command of DML is not auto-committed that means it can't permanently save all the changes in the
database. They can be rollback.
Here are some commands that come under DML:
INSERT
UPDATE
DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, .... valueN);
or
INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
For example:
Syntax:
For example:
The SELECT statement in MySQL is used to fetch data from one or more tables. We can retrieve
records of all fields or specified fields that match specified criteria using this statement.
Syntax
**************************************************************************
Alter Command
a. Add b. Modify
**************************************************************************
*******************************************************************
*
Select * from stud_info;
UPDATE stud_info
SET LastName = ’pqr’, FirstName= ’efg'
WHERE RollNo = 1234567890;
*****************************************************************
*****************************************************************
Rollback;
***********************************************************************
Commit;
***********************************************************************
Language It is a DML (Data Manipulation Language) It is a DDL (Data Definition Language) command.
command.
WHERE It can use the WHERE clause to filter any specific It does not use the WHERE clause to filter records from the
row or data from the table. table.
Permission We need to have DELETE permission to use this We need to have ALTER permission to use this command.
command.
Working This command eliminates records one by one. This command deletes the entire data page containing the
records.
Lock It will lock the row before deletion. It will lock the data page before deletion.
Table This command does not reset the table identity It always resets the table identity.
Identity because it only deletes the data.
Transactio It maintains transaction logs for each deleted It does not maintain transaction logs for each deleted data
n record. page.
Speed Its speed is slow because it maintained the log. Its execution is fast because it deleted entire data at a time
without maintaining transaction logs.
Trigger This command can also activate the trigger applied This command does not activate the triggers applied on the
on the table and causes them to fire. table to fire.
Restore It allows us to restore the deleted data by using the We cannot restore the deleted data after using executing this
COMMIT or ROLLBACK statement. command.
Indexed It can be used with indexed views. It cannot be used with indexed views.
view
Space The DELETE statement occupies more transaction The TRUNCATE statement occupies less transaction space
space than truncate because it maintains a log for because it maintains a transaction log for the entire data page
BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
To display the products outside the range of the previous example, use NOT BETWEEN:
Ex.- SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20;
IN Operator
NOT IN Operator
SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
SQL statement selects all fields from "Customers" where country is NOT "Germany":
SQL statement selects all fields from "Customers" where country is "Germany" AND city must be "Berlin" OR "München"
SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It returns a single value.
It is also used to summarize the data.
COUNT function is used to Count the number of rows in a database table. It can work on both numeric and non-numeric data types.
COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table. COUNT(*) considers duplicate and Null.
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function returns the average of all non-Null values.
MAX function is used to find the maximum value of a certain column. This function determines the largest value of all selected values of a
column.
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function determines the smallest value of all selected values of a
column.
12.Select * from Worker where SALARY NOT BETWEEN 100000 and 500000;
SQL PRIMARY KEY
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When multiple
fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field, then you cannot have two records having the same
value of that field.
Or
The NOT NULL is a constraint in SQL which does not allow you to insert NULL values in the specified
column.
If any column is defined as a NOT NULL constraint in the table, we cannot insert a new record in the
table without adding the value to the column.
Ex. –
CREATE TABLE students
(
StudentID number(10) NOT NULL ,
LastName varchar2 (255) NOT NULL ,
FirstName varchar2 (255) NOT NULL ,
Address varchar2 (255),
City varchar2 (255),
)
Note - We can define NOT NULL constraint to one or more columns in one SQL table.
A unique key is used to remove the duplicity of values in a table. However, the usage of a primary
key is the same, but there is a difference between both keys. A primary key cannot take
a NULL value, but a unique key can have one NULL value as its value.
There are the following difference points that will let us understand the difference between a Unique
key and a Primary key:
A primary key field can never have a NULL value as its value, whereas a unique key can have one
of its field values as NULL.
A table cannot have more than one primary key, but a table can have more than one unique key.
There are different types of relational databases, but in some of these databases, the primary key
can generate a clustered index by default. On the other hand, a unique key is able to generate a
non-clustered index by default.
Ex.-
CREATE TABLE Persons (
ID number(10) NOT NULL UNIQUE,
LastName varchar2(255) NOT NULL,
SQL - CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn't entered the table.
The following program creates a new table called CUSTOMERS and adds five columns. Here, we add a
CHECK with AGE column, so that you cannot have any CUSTOMER who is below 18 years.
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign (%) represents zero, one, or multiple characters
The underscore sign (_) represents one, single character
The following SQL statement selects all customers with a CustomerName ending with "a":
The following SQL statement selects all customers with a CustomerName that have "r" in the
second position:
The following SQL statement selects all customers with a ContactName that starts with "a"
and ends with "o":
4. Select the details of the employee who work either for department E-104
or E-102.
All these are the candidate keys and from which we can pick the most appropriate attribute that
can easily identify all records of the table, which will be described as the Primary key.
Alternate Key in SQL
Alternate Key or Secondary Key is the key that has not been selected to be the primary key, but are
candidate keys. A candidate key not selected as a primary key is called alternate or secondary key.
Candidate key is an attribute or set of attributes that you can consider as a Primary key.
If a table has more than one candidate key, one of them will become the primary key and rest of all
are called alternate keys.
Super Key in DBMS
We can define a super key as a set of those keys that identify a row or a tuple uniquely. The word
super denotes the superiority of a key. Thus, a super key is the superset of a key known as
a Candidate key . It means a candidate key is obtained from a super key only.
Here, we will discuss about the super key, i.e., what is the role of a super key, how to use it, and will
be looking at some practical examples that will help us to understand it in a better way.
The role of the super key is simply to identify the tuples of the specified table in the database. It is
the superset where the candidate key is a part of the super key only. So, all those attributes in a table
that is capable of identifying the other attributes of the table in a unique manner are all super keys.
Difference between Candidate Key and Super Key
It is not at all compulsory that all super keys are On the other hand, all candidate keys are super
candidate keys. keys.
The super key attribute can be NULL, which means An attribute holding a candidate key can never be
its values can be null. NULL, which means its values cannot be null.
All the super keys formed together to bring the Similarly, candidate keys are put together to create
candidate keys. primary keys.
The number of super keys formed is always seen Here, Candidate keys are less than super keys.
more.
Note- The super key is the super set, the candidate key is the subset, and the primary key is the
sub-subset of the super key.
What is a DEFAULT constraint
The DEFAULT is a constraint in SQL which allows users to fill a column with the default or fixed
value.
If no value is specified to the column at the time of insertion, then the default value will be added
automatically to that column.
CREATE TABLE Client_Info
(
Ex.-
Client_ID INT PRIMARY KEY,
Client_Name VARCHAR (100),
Client_Gender Varchar(20),
Client_Age INT NOT NULL DEFAULT 18,
Client_Address Varchar (80)
);
Ex.-
CREATE TABLE Doctor_Info
(
Doctor_ID INT PRIMARY KEY,
Doctor_Name VARCHAR (100),
Doctor_Specialist VARCHAR (80) DEFAULT Heart,
Statement1: In Statement 1, we have not specified the value for Country and DOJ columns, so it will take the default values
i.e. INDIA and Current system date for the Country and DOJ columns.
Statement2: In Statement 2, we have not specified the value for the DOJ column, so it will take the default system date value
for the DOJ column. In the Country column, it will store the given value i.e. UK.
Statement3: In Statement 3, we have not specified the value for the Country column, so it will take the default value i.e.
INDIA for the Country column. In the DOJ column, it will store the given value.
Statement4/5: In Statement 4 and 5, it will not insert the default values as we have specified the values for the Country and
DOJ columns.
Once you execute the INSERT Statements and if you verify the Employee table, then you will get the following
records.
Write an SQL query to fetch “FIRST_NAME” from the Worker table in upper case.
Write an SQL query to fetch unique values of DEPARTMENT from the Worker table.
Write an SQL query to find the employee id whose salary lies in the range of 9000 and
15000.
Write an SQL query to find the maximum, minimum, and average salary of the
employees.
Write an SQL query to fetch the count of employees working in project ‘P1’.
Write an SQL query to fetch all those employees who work on Projects other than P1.
Write an SQL query to fetch all the EmpIds which are present in either of the tables –
‘EmployeeDetails’ and ‘EmployeeSalary’.
Write an SQL query to fetch records that are present in one table but not in another
table.
The above query will create a table with DeptNo as the primary key, which will act as a reference table or a
parent table for another table that will contain the foreign key.
Create another table Employee, which will be the child table for the Department table. It contains
the EmpNo, EmpName, Salary, and DeptNo as its fields.
Parent Table
Difference between primary key and foreign key in SQL:
Primary key cannot be null on the other hand foreign key can be null.
Primary key is always unique while foreign key can be duplicated.
Primary key uniquely identify a record in a table while foreign key is a
field in a table that is
primary key in another table.
There is only one primary key in the table on the other hand we can
have more than one
foreign key in the table.
Roll No (PK) Name Address
1 Rahul Delhi
2 Mohan UP
3 Ram Punjab
PARENT TABLE
CREATE TABLE Employee (
emp_id int(10) PRIMARY KEY ,
name varchar(40) NOT NULL,
birthdate date NOT NULL,
gender varchar(10) NOT NULL,
hire_date date NOT NULL
);
CHILD TABLE
CREATE TABLE Payment (
payment_id int(10) PRIMARY KEY,
emp_id int(10) NOT NULL,
amount float NOT NULL,
payment_date date NOT NULL,
FOREIGN KEY (emp_id) REFERENCES Employee (emp_id) ON DELETE CASCADE
INSERT INTO Employee (emp_id, name, birthdate, gender, hire_date) VALUES
(101, 'Bryan', '1988-08-12', 'M', '2015-08-26'),
(102, 'Joseph', '1978-05-12', 'M', '2014-10-21'),
(103, 'Mike', '1984-10-13', 'M', '2017-10-28'),
(104, 'Daren', '1979-04-11', 'M', '2006-11-01'),
(105, 'Marie', '1990-02-11', 'F', '2018-10-12');
The above statement will delete the employee records whose emp_id =
102 and referencing data into the child table.
Introduction to Nested Queries or Sub Query
A Subquery is a query within another SQL query and embedded within the WHERE clause.
Important Rule:
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.
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.
1. Subqueries with the Select Statement
SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);
SQL subquery can also be used with the Insert statement. In the insert statement, data returned
from the subquery is used to insert into another table.
Example
Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.
INSERT INTO EMPLOYEE_BKP SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE);
The subquery of SQL can be used in conjunction with the Update statement. When a subquery is
used with the Update statement, then either single or multiple columns in a table can be updated.
Example
The given example updates the SALARY by .25 times in the EMPLOYEE table for all employee
whose AGE is greater than or equal to 29.
UPDATE EMPLOYEE SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM
EMPLOYEE WHERE AGE >= 29);
4. Subqueries with the DELETE Statement
Example
The given example deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE is
greater than or equal to 29.
DELETE FROM EMPLOYEE WHERE AGE IN (SELECT AGE FROM EMPLOYEE WHERE AGE >= 29 );
SQL GROUP BY
In SQL, The Group By statement is used for organizing similar data into groups. The data is further
organized with the help of equivalent function. It means, if different rows in a precise column have
the same values, it will arrange those rows in a group.
The SELECT statement is used with the GROUP BY clause in the SQL query.
WHERE clause is placed before the GROUP BY clause in SQL.
ORDER BY clause is placed after the GROUP BY clause in SQL.
It is often used with aggregate functions like SUM, COUNT, AVG, MAX, or MIN, which allows us to
perform calculations on the grouped data.
For example, let us suppose you have a table of sales data consisting of date, product, and sales
amount. To calculate the total sales of an organization in an year, the GROUP BY clause can be used
to group the sales of products together. Similarly, you can group the data by date to calculate the
total sales for each day, or by a combination of product and date to calculate the total sales for
each product on each day.
Syntax-
SELECT column_name(s) FROM table_name GROUP BY column_name(s);
GROUP BY with Single Column
When we use the GROUP BY clause with a single column, SQL will place all rows in the table that
have the same value in that particular column into a single record.
NAME SALARY
John 50000
Nick 44000
Amara 15000
GROUP BY with Multiple Columns
When we use the GROUP BY clause with multiple columns, SQL will place all rows in the table that
have the same values in all of the specified columns into a single group.
SUBJECT YEAR NAME
C language 2 John
C language 2 Ginny
C language 2 Jasmeen
C language 3 Nick
C language 3 Amara
Java 1 Sifa
Java 1 dolly
SELECT SUBJECT, YEAR, Count (*) FROM Student Group BY SUBJECT, YEAR;
SUM(Emp_Salary) Emp_City
9000 Delhi
8000 Jaipur
Roll_No Name Marks Age
1 Rithik 91 20
2 Kapil 60 19
3 Arun 82 17
4 Ram 92 18
5 Anuj 50 20
6 Suman 88 18
7 Sheetal 57 19
8 Anuj 64 20
Count(Roll_No) Age
3 20
2 19
2 18
Emp_ID Name Emp_Salary Emp_Dept
1001 Anuj 9000 Finance
1002 Saket 4000 HR
1003 Raman 3000 Coding
1004 Renu 6000 Coding
1005 Seenu 5000 HR
1006 Mohan 10000 Marketing
1007 Anaya 4000 Coding
1008 Parul 8000 Finance
MIN(Emp_Salary) Emp_Dept
8000 Finance
10000 Marketing
SQL Server Comparison Operator
Index Comparison Operator Description
1) = It specifies equal symbol.
2) <> It specifies not equal symbol.
3) != It specifies not equal symbol.
4) > It specifies greater than symbol.
5) >= It specifies greater than or equal symbol.
6) < It specifies less than symbol.
7) <= It specifies less than or equal symbol.
8) !> It specifies not greater than symbol.
9) !< It specifies not less than symbol.
10) IN ( ) It matches a value in a list.
11) NOT It is used to negate a condition.
12) BETWEEN It is used to specify within a range (inclusive) value.
13) IS NULL It specifies null value.
14) IS NOT NULL It specifies non-null value.
15) LIKE It specifies pattern matching with % and _
16) EXISTS It specifies that the condition is met if subquery returns at
least one row
SQL JOINS
The join clause allows us to retrieve data from two or more related tables into a meaningful
result set. We can join the table using a SELECT statement and a join condition. It indicates how SQL
Server can use data from one table to select rows from another table. In general, tables are related to
each other using foreign key constraints.
Choose columns from each table that should be used in the join. A join condition indicates a foreign
key from one table and its corresponding key in the other table.
Specify the logical operator to compare values from the columns like =, <, or >.
INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables. An Inner Join
retrieves the intersection of two tables. It compares each row of the first table with each row of the
second table. If the pairs of these rows satisfy the join-predicate, they are joined together. This is a
default join.
The following visual representation explains how INNER JOIN returns the matching records
from table1 and table2:
Table: Student Table: Fee
Output
SELECT Student.admission_no,
Student.first_name,
Student.last_name,
Fee.course,
Fee.amount_paid
FROM Student
INNER JOIN Fee
ON Student.admission_no = Fee.admission_no;
LEFT OUTER JOIN
The LEFT OUTER JOIN retrieves all the records from the left table and matching rows from the right
table. It will return NULL when no matching record is found in the right side table. Since OUTER is an
optional keyword, it is also known as LEFT JOIN.
The below visual representation illustrates the LEFT OUTER JOIN:
Table: Student Table: Fee
Output
SELECT Student.admission_no,
Student.first_name,
Student.last_name,
Fee.course,
Fee.amount_paid
FROM Student
LEFT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;
RIGHT OUTER JOIN
The RIGHT OUTER JOIN retrieves all the records from the right-hand table and matched
rows from the left-hand table. It will return NULL when no matching record is found in the left-
hand table. Since OUTER is an optional keyword, it is also known as RIGHT JOIN.
Table: Student Table: Fee
Output
SELECT Student.admission_no,
Student.first_name,
Student.last_name,
Fee.course,
Fee.amount_paid
FROM Student
RIGHT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;
FULL OUTER JOIN
The FULL OUTER JOIN in SQL Server returns a result that includes all rows from both tables.
The columns of the right-hand table return NULL when no matching records are found in the left-
hand table. And if no matching records are found in the right-hand table, the left-hand table column
returns NULL.
Table: Student Table: Fee
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.
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.
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.
Example
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM Student_Details WHERE
STU_ID < 4;
Creating View from multiple tables
Deleting View
Ex.-
DROP VIEW MarksView;
Deleting Rows into a View
Ex.-
DELETE FROM CUSTOMERS_VIEW WHERE age =
22;
DCL - DATA CONTROL LANGUAGE
The Data Control Language is the sublanguage responsible for the administrative tasks of
controlling the database itself, most notably granting and revoking database permissions
for users.
Grant Privilege
MySQL has a feature that provides many control options to the administrators and users on the
database. MySQL provides GRANT statements to give access rights to a user account.
Use the GRANT statement to give privileges to a specific user or role, or to all users, to perform
actions on database objects. You can also use the GRANT statement to grant a role to a user, to
PUBLIC, or to another role.
Syntax
Parameter Name Descriptions
GRANT privilege_name(s) ON object TO user_account_name;
privilege_name( It specifies the access rights or grant privilege to user accounts. If we want to give
s) multiple privileges, then use a comma operator to separate them.
object It determines the privilege level on which the access rights are being granted. It
means granting privilege to the table; then the object should be the name of the
table.
user_account_n It determines the account name of the user to whom the access rights would be
Privilege Levels
Column GRANT SELECT (col1), INSERT (col1, col2), It applies on a single column of a table. Here, we must have to specify the
UPDATE (col2) column(s) name enclosed with parenthesis for each privilege. The user can
ON mydb.mytable select one column, insert values in two columns, and update only one column
TO john@localhost; in the given table.
Stored GRANT EXECUTE It applies to stored routines (procedure and functions). It contains CREATE
Routine ON PROCEDURE mydb.myprocedure ROUTINE, ALTER ROUTINE, EXECUTE, and GRANT OPTION privileges. Here, a
TO john@localhost; user can execute the stored procedure in the current database.
Proxy GRANT PROXY It enables one user to be a proxy for other users.
ON root
TO peter@localhost;
SQL REVOKE statement
Issue REVOKE statements to withdraw privileges. The revoke statement enables system
administrators to revoke privileges and roles to the MySQL user accounts so that they cannot use
the assigned permission on the database in the past.
Syntax
Ex.-
A sequence object can be defined as a user-defined object which is bound to the schema that
generates a numeric values sequence according to the increment value that is defined at the time of
the creation of the sequence.
The numeric values sequence that is generated can be in a descending or ascending order depending
upon an already preset incremental value and it can also be started again (cycle) when it reaches its
termination limit. Unlike identity columns, the sequences are not associated with some particular
tables. In order to get the next value of the sequence generated, the applications can refer to an
object of sequence.
The application controls the relationship between tables and sequences. A sequence can be seen as a
schema-level object which any user can access. Unlike a procedure, a sequence belongs to no user.
Let us take an example for a better understanding. Let us create a table named students having three
columns named studID, rollNo, Name to store the student ID, roll no, and Name of the student
respectively. The command for creating a table in SQL server with the above-mentioned schema will
be:
CREATE TABLE students (
studID varchar(10),
rollNo int,
Name varchar(30)
);
INSERT INTO students(rollNo, Name) VALUES(87459, "Andrew");
INSERT INTO students(rollNo, Name) VALUES(54786, "Samuel");
INSERT INTO students(rollNo, Name) VALUES(22149, "Nirnay");
INSERT INTO students(rollNo, Name) VALUES(94365, "Paul");
INSERT INTO students(rollNo, Name) VALUES(35479, "Casey");
INSERT INTO students(rollNo, Name) VALUES(74566, "Martin");
INSERT INTO students(rollNo, Name) VALUES(10259, "Raphel");
As we can see in the image, we have successfully added seven rows to the students' table and the same can be seen in
the result of the SELECT query.
Now we add data in the studID column using a sequence object. For this, a sequence object needs to be created. The
syntax for the same is:
We have created a sequence object named stud_seq having the initial value as 101 and it gets incremented by 1 where
the value from the sequence object named stud_seq is fetched. For retrieving the next value from the sequence object,
the syntax is:
SQL Server Index
The Index in SQL is a special table used to speed up the searching of the data in the database tables.
It also retrieves a vast amount of data from the tables frequently. The INDEX requires its own space
in the hard disk.
The index concept in SQL is same as the index concept in the novel or a book.
It is the best SQL technique for improving the performance of queries. The drawback of using
indexes is that they slow down the execution time of UPDATE and INSERT statements. But they have
one advantage also as they speed up the execution time of SELECT and WHERE statements.
In SQL, an Index is created on the fields of the tables. We can easily build one or more indexes on a
table. The creation and deletion of the Index do not affect the data of the database.
SQL Indexes can search the information of the large database quickly.
This concept is a quick process for those columns, including different values.
This data structure sorts the data values of columns (fields) either in ascending or descending
order. And then, it assigns the entry for each value.
Each Index table contains only two columns. The first column is row_id, and the other is indexed-
column.
When indexes are used with smaller tables, the performance of the index may not be recognized.
Create an INDEX
Syntax - CREATE INDEX Index_Name ON Table_Name ( Column_Name);
Here, Index_Name is the name of that index that we want to create, and Table_Name is the name
of the table on which the index is to be created. The Column_Name represents the name of the
column on which index is to be applied.
If we want to create an index on the combination of two or more columns, then the following syntax
can be used in SQL:
Syntax -
CREATE INDEX Index_Name ON Table_Name ( column_name1, column_name2, ...., column_nameN);
Emp_Id Emp_Name Emp_Salary Emp_City Emp_State
Example for creating
1001 an Index in SQL:
Akshay 20000 Noida U.P
1002 Ram 35000 Jaipur Rajasthan
1003 Shyam 25000 Gurgaon Haryana
1004 Yatin 30000 Lucknow U.P
The following SQL query creates an Index 'Index_state' on the Emp_State column of
the Employee table.
Unique Index is the same as the Primary key in SQL. The unique index does not allow selecting
those columns which contain duplicate values. This index is the best way to maintain the data
integrity of the SQL tables.
Remove an INDEX
Stored Procedure in SQL Server