0% found this document useful (0 votes)
0 views

Module 4 Structured Query Language

Structured Query Language (SQL) is a standard database language used for creating, maintaining, and retrieving relational databases, established by IBM in the 1970s and standardized by ANSI and ISO in the 1980s. SQL allows users to perform various data operations efficiently without extensive coding skills, and it supports multiple database systems. The document also discusses SQL's advantages and disadvantages, including its structured approach, interactive nature, and the importance of commands like DDL and DML for managing database structures and data manipulation.

Uploaded by

shrishtiwari282
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Module 4 Structured Query Language

Structured Query Language (SQL) is a standard database language used for creating, maintaining, and retrieving relational databases, established by IBM in the 1970s and standardized by ANSI and ISO in the 1980s. SQL allows users to perform various data operations efficiently without extensive coding skills, and it supports multiple database systems. The document also discusses SQL's advantages and disadvantages, including its structured approach, interactive nature, and the importance of commands like DDL and DML for managing database structures and data manipulation.

Uploaded by

shrishtiwari282
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

Module 4

Structured Query
Language
-Mrs. Smita Abhijit Ganjare
Overview of Structured Query Language
 Structured Query Language is a standard Database language that is used to create,
maintain, and retrieve the relational database.
 SQL was developed in the 1970s by IBM Computer Scientists and became a
standard of the American National Standards Institute (ANSI) in 1986, and the
International Organization for Standardization (ISO) in 1987.
 SQL is the standard language to communicate with Relational Database Systems.
All the Relational Database Management Systems (RDMS) like MySQL, MS Access,
Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their Standard
Database Language.
How Does SQL Work?
 Structured Query Language (SQL) is a domain-specific language designed for the management,
manipulation, and dynamic modification of relational databases. It serves as a standard interface for
interacting with relational database management systems (RDBMS), allowing users to perform a
variety of routine tasks and operations on data, such as querying, updating, inserting, and deleting
records.
Advantages of SQL
 1. Faster and Efficient Query Processing: SQL works with an efficient speed. This high speed can
boost the amount of data retrieval. It can give users a rapid and effective means to obtain, alter, or
store data.
• SQL can quickly and efficiently retrieve a large volume of data records from a database. Compared to
an unstructured database such as MongoDB, it is a relational database that can characterize the data
in a structured way. Operations like insertion, deletion, querying, manipulation, and calculations on
data via analytical queries in a relational database can be accomplished in a matter of seconds.

 2. No Need for Coding Skills: There is no need for large and complex code lines for data extraction.
One reason for using SQL is that it does not require extensive coding and program writing knowledge.
It is easy to maintain database systems without having to write a good amount of code. There is no
need for large complex lines of code for data extraction.
• SQL is mostly made up of English statements, making it simple to learn and write SQL queries. All
primary keywords, like SELECT, INSERT INTO, DELETE, UPDATE, etc., can be used to carry out
operations. Also, the syntactical rules are simple and easy to understand, making it a user-friendly
language.
Advantages of SQL
• 3. Portable : SQL is highly portable because it is employed in programs on PCs, servers, tablets, and
independent laptops running operating systems such as Windows, Linux, Mac, and even some mobile
phones. It can also be embedded with other programs based on the requirements.
• It can be used on local systems (internet and the intranet). SQL databases can be easily transferred from
one device to another.

• 4. Standardized Language: SQL is a relational database query language that has been accepted
by ISO and ANSI. It gives all users a consistent platform worldwide due to proper documentation and
years of establishment.
• In 19861986 and 19871987, ANSI (American National Standards Institute) and ISO (International
Standards Organization) standardized the language. The most recent standard part was produced
in 20112011.
Advantages of SQL
 5. Interactive Language : SQL is a domain language that is simple to learn and easy to understand. It can also
be used to interface with databases and receive responses to complicated queries in seconds.
• It becomes an interactive language for its users because it offers easy commands for all purposes. SQL
commands are also understandable to non-programmers.
• SQL is used to build and administer large databases, including data sharing, updating, and retrieval from
numerous tables. This is the primary reason organizations employ SQL in various applications such as web
development, data analysis, IT support, etc.
 6. Multiple Data Views : The SQL language gives each user a unique view of the data. A view is a SQL
statement that includes specified SQL queries that are stored in the database. It can be built from one or
more tables based on the queries written or the aim that the view satisfies.
• SQL can provide distinct views of the database's structure and content to different users.
 7. Internet Usage
• Three-tier Internet architectures are compatible with SQL architecture. Client, application server, and
database components make up the architecture.
Advantages of SQL
 8. Large User Community
• The SQL programming language is nearly 50 years old and is incredibly mature and still extensively
used. It boasts a vibrant network of specialists eager to provide advice and well-established best
practices.
• There are several opportunities to improve one's skills and collaborate. Consultants and SQL suppliers
can provide extra assistance if needed. Your developers will be able to find the answers they require
using SQL.
Disadvantages of SQL
 1. Resource-Intensive Scaling : SQL databases typically scale up vertically by increasing hardware
investment. This is both costly and time-consuming. An organization may seek to scale a SQL database
horizontally using partitioning in particular instances.
 2. Partial Control : SQL does not provide programmers complete control over databases. This is
primarily due to hidden corporate rules.
 3. Cost Inefficient : Some versions are expensive, which makes programmers unable to access
them. For example, SQL Server Standard costs around $1,418 per year.
 4. Rigidity : The schema of a SQL database must be specified before it can be used. They are rigid once
installed, and changes are often complex and time-consuming. As a result, significant work must be
invested in upfront preparation before the database is ever put into production.
Structured Query Language (SQL)
 Data Definition
Language (DDL), Data
Manipulation
Language
(DML), Transaction
Control Language
(TCL), and Data
Control Language
(DCL) form the
backbone of SQL. Each
of these languages
plays a critical role in
defining, managing,
and controlling data
within a database
system, ensuring both
structural integrity and
user access control.
DDL (Data Definition Language)

 Data Definition Language is used to define the database structure or schema.


 DDL command in SQL is also used to specify additional properties of the data.
 The storage structure and access methods used by the database system by a set of
statements in a special type of DDL called a data storage and definition language.
 These statements define the implementation details of the database schema, which are
usually hidden from the users. The data values stored in the database must satisfy certain
consistency constraints.
 DDL Commands :
1. Create
2. Alter
3. truncate
4. drop
5. Rename
Command-1 : CREATE
Command-2 : ALTER
 This command is used to add, delete or change columns in the existing table. The user needs to
know the existing table name and can do add, delete or modify tasks easily.
Command-3 : TRUNCATE
 This command is used to remove all rows from the table, but the structure of the table still
exists.
Command-4 : DROP
 This command is used to remove an existing table along with its structure from the
Database.
Command -5: RENAME
 It is possible to change name of table with or without data in it using simple RENAME
command.
 We can rename any table object at any point of time.
DML (Data Manipulation Language)
 DML stands for Data Manipulation Language. Tables and formulas are helpful
when communicating with data stored up to a point in a database through SQL
(Structured Query Language), but a time comes when we actually want to
execute some fairly complicated data interactions.
 DML Commands:
• INSERT adds fresh data to a table.
• UPDATE Change the data that is already in a table.
• DELETE takes a record out of a table.
• SELECT Get information out of one or more tables.
Difference Between DDL and DML in DBMS
 DDL is a Data Definition Language that is used to define data structures. For example: creating a table, and
altering a table are instructions in SQL.

 DML is a Data Manipulation Language that is used to manipulate data itself. For example: insert, update,
and delete are instructions in SQL.

 Data Definition Language :


• DDL is used to specify a database’s structure, which includes its tables, views, indexes, and constraints.
• DDL commands come in the following types: CREATE, ALTER, DROP, RENAME, and TRUNCATE.
• DDL statements only modify the database’s schema; they have no direct effect on the data within the
database.
• DDL declarations are irreversible and difficult to undo.
Difference Between DDL and DML in DBMS
 Data Manipulation Language
• Inserting, updating, removing, and retrieving data from a database are all possible with DML.
• DML commands come in the following types: SELECT, INSERT, UPDATE, DELETE, and
MERGE.
• DML statements have a direct impact on the database’s data.
• In the event of an error, data can be recovered thanks to the reversibility of DML statements.
Difference Between DDL and DML in DBMS
DDL DML
It stands for Data Definition Language . It stands for Data Manipulation Language .

It is used to create database schema and can be used


It is used to add, retrieve, or update the data.
to define some constraints as well.
It adds or updates the row of the table. These rows are
It basically defines the column (Attributes) of the table.
called tuples.
It is further classified into Procedural and Non-
It doesn’t have any further classification.
Procedural DML.
Basic commands present in DDL are CREATE, DROP, BASIC commands present in DML
RENAME, ALTER, etc. are UPDATE , INSERT , MERGE etc.

DDL does not use WHERE clause in its statement. While DML uses WHERE clause in its statement.

DDL is used to define the structure of a database. DML is used to manipulate the data within the database.

DDL is used to create and modify database objects like DML is used to perform operations on the data within
tables, indexes, views, and constraints. those database objects.
DDL statements are typically executed less frequently DML statements are frequently executed to manipulate
than DML statement and query data.
DDL statements are typically executed by database DML statements are typically executed by application
administrators. developers or end-users.
DDL statements are not used to manipulate data
DML statements are used to manipulate data directly.
directly.
The database’s contents are not altered by DDL
DML commands alter the database’s contents.
commands.

Examples of DDL commands: CREATE TABLE, ALTER TABLE, Examples of DML commands: SELECT, INSERT, UPDATE,
DROP TABLE, TRUNCATE TABLE, and RENAME TABLE. DELETE, and MERGE.
SQL Joins (Inner, Left, Right and Full Join)
 SQL joins are the foundation of database management systems, enabling the combination
of data from multiple tables based on relationships between columns. Joins allow efficient
data retrieval, which is essential for generating meaningful observations and
solving complex business queries.
 Types of Joins in SQL
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• Natural Join
1. 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.
5. SQL Natural Join (?)
 Natural join can join tables based on the common columns in the tables being joined. A
natural join returns all rows by matching values in common columns having same name
and data type of columns and that column should be present in both tables.
• Both table must have at least one common column with same column name and same data
type.
• The two table are joined using Cross join.
• DBMS will look for a common column with same name and data type. Tuples having exactly
same values in common columns are kept in result.
WHERE Clause in SQL
SQL ORDER BY Keyword

ProductID ProductNa SupplierID CategoryID Unit Price


me

1 Chais 1 1 10 boxes x 18
20 bags

2 Chang 1 1 24 - 12 oz 19
bottles

3 Aniseed 1 2 12 - 550 ml 10
Syrup bottles

4 Chef 2 2 48 - 6 oz jars 22
Anton's
Cajun
Seasoning

5 Chef 2 2 36 boxes 21.35


Anton's
Gumbo Mix
Example 1 : Sort According To a Single Column
using ORDER BY Clause
SQL ORDER BY Clause Examples
SQL | GROUP BY
 The GROUP BY statement in SQL is used for organizing and summarizing data based
on identical values in specified columns.
 By using the GROUP BY clause, users can apply aggregate functions like SUM,
COUNT, AVG, MIN, and MAX to each group, making it easier to perform detailed data
analysis.
 Key Points About GROUP BY:
• GROUP BY clause is used with the SELECT statement.
• In the query, the GROUP BY clause is placed after the WHERE clause.
• In the query, the GROUP BY clause is placed before the ORDER BY clause if used.
• In the query, the Group BY clause is placed before the Having clause.
• Place condition in the having clause.
Examples of GROUP BY in SQL
HAVING Clause in GROUP BY Clause
 We know that the WHERE clause is used to place conditions on
columns but what if we want to place conditions on groups?
 This is where the HAVING clause comes into use. We can use
the HAVING clause to place conditions to decide which group
will be part of the final result set. Also, we can not use aggregate
functions like SUM(), COUNT(), etc. with the WHERE clause. So
we have to use the HAVING clause if we want to use any of these
functions in the conditions.
HAVING Clause in GROUP BY Clause
SQL Constraints
 SQL constraints are used to specify rules for the data in a
table.
 Constraints 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 table. If there is any violation between the
constraint and the data action, the action is aborted.
 Constraints can be column level or table level. Column level
constraints apply to a column, and table level constraints
apply to the whole table.
SQL Constraints
 The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL
 The NOT NULL constraint ensures that a column cannot contain NULL values. This is
particularly important for columns where a value is essential for identifying records or
performing calculations. If a column is defined as NOT NULL, every row must include a value
for that column.
UNIQUE Constraint
 The UNIQUE constraint ensures that all values in a column are distinct across all rows in a
table. Unlike the PRIMARY KEY, which requires uniqueness and does not allow NULLs, the
UNIQUE constraint allows NULL values but still enforces uniqueness for non-NULL entries.
PRIMARY KEY Constraint
 A PRIMARY KEY constraint is a combination of the NOT NULL and UNIQUE constraints. It
uniquely identifies each row in a table. A table can only have one PRIMARY KEY, and it
cannot accept NULL values. This is typically used for the column that will serve as the
identifier of records.
FOREIGN KEY Constraint
 A FOREIGN KEY constraint links a column in one table to the primary key in another table.
This relationship helps maintain referential integrity by ensuring that the value in the foreign
key column matches a valid record in the referenced table.
FOREIGN KEY Constraint
CHECK Constraint
 The CHECK constraint allows us to specify a condition that data must satisfy before it is
inserted into the table. This can be used to enforce rules, such as ensuring that a column’s value
meets certain criteria (e.g., age must be greater than 18).
DEFAULT Constraint
 The DEFAULT constraint provides a default value for a column when no value is specified during
insertion. This is useful for ensuring that certain columns always have a meaningful value, even if
the user does not provide one.
Nested Queries in SQL
 Nested queries in SQL are a powerful tool for retrieving data from databases in a structured
and efficient manner. They allow us to execute a query within another query, making it easier to
handle complex data operations.
 A nested query (also called a subquery) is a query embedded within another SQL query. The
result of the inner query is used by the outer query to perform further operations. Nested
queries are commonly used for filtering data, performing calculations, or joining
datasets indirectly.
 Key Characteristics:
• The inner query runs before the outer query.
• The result of the inner query can be used by the outer query for comparison or as input data.
• Nested queries are particularly useful for breaking down complex problems into smaller,
manageable parts, making it easier to retrieve specific results from large datasets.
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS');

Types of Nested Queries in SQL


 1. Independent Nested Queries :In independent nested queries, the execution of the inner query
is not dependent on the outer query. The result of the inner query is used directly by the outer
query. Operators like IN, NOT IN, ANY, and ALL are commonly used with this type of nested
query.
 Example 1: Using IN
 Find the S_IDs of students who are enrolled in the courses ‘DSA’ or ‘DBMS’.
 Step 1: Find the C_IDs of the courses:
 This query retrieves the IDs of the courses named ‘DSA’ or ‘DBMS’ from the COURSE table.
 Step 2: Use the result of Step 1 to find the
corresponding S_IDs:
 The inner query finds the course IDs, and the outer
query retrieves the student IDs associated with those
courses from the STUDENT_COURSE table
2. Correlated Nested Queries
 In correlated nested queries, the inner query depends on the outer query for its execution. For
each row processed by the outer query, the inner query is executed. The EXISTS keyword is
often used with correlated queries.
 Example 2: Using EXISTS
 Find the names of students who are enrolled in the course with C_ID = ‘C1’:
Best Practices for Using Nested Queries
1. Optimize independent queries: Use independent nested queries whenever possible, as they are
easier to execute and debug. Ensure that inner queries are optimized for performance by adding
appropriate indexes.
2. Prefer joins for simple queries: For cases where nested queries add unnecessary complexity,
consider using joins instead. Joins are typically faster and more readable for straightforward
relationships.
3. Avoid deep nesting: Limit the levels of nesting in queries to improve performance and maintain
readability. Deeply nested queries can be computationally expensive and difficult to debug.
4. Use EXISTS and IN wisely: Choose the appropriate operator based on the scenario.
Use EXISTS for checking existence and IN for comparing with a list of values.
5. Test query performance: Analyze the execution plan of our queries to identify bottlenecks and
improve efficiency. Rewrite queries where necessary to enhance performance.
6. Maintain clarity: Use meaningful table aliases and comments to ensure that nested queries
remain understandable to other developers or your future self.
Data Control Language (DCL) in SQL
 DCL (Data Control Language) includes commands such as GRANT and REVOKE which
mainly deal with the rights, permissions, and other controls of the database system. These
commands are used to control access to data in the database by granting or revoking
permissions.
 Common DCL Commands
GRANT Command
 GRANT Command Definition: The GRANT command allows the database administrator
to grant specific privileges or permissions to a user on a database object, such as tables, views,
procedures, etc.
 In layman’s terms, the GRANT command allows a user to access and perform specific actions on the
database or its objects. You should also remember that the GRANT command is mainly used by
database administrators in order to ensure the security and integrity of the data in the database. In
order to better understand the workings of the GRANT command, let’s go through an example.
 GRANT Command Example:
 Consider a database with a table named “employees.” If you want to allow a user named “Vivek” to
only SELECT (read) data from the “employees” table, you can use the following GRANT command:

This command will allow the user “Vivek” to run SELECT queries on the “employees” table. But Vivek
won’t be able to make any changes, such as inserting, updating, or removing the data in the
“employees” table.
REVOKE Command
 REVOKE Command: The REVOKE command allows the database administrator
to revoke previously granted privileges or permissions to a user on a database object, such as
tables, views, procedures, etc.
 In layman’s terms, the REVOKE command restricts a user from accessing and performing specific
actions on the database or its objects. You should remember that the REVOKE command is also
mainly used by database administrators in order to ensure the security and integrity of the data
in the database. In order to better understand the working of the REVOKE command, let’s go
through an example.
 REVOKE Command Example:
 Let’s consider the above example that we discussed in the GRANT command. In that, we have granted
access to Vivek to SELECT (read) data from the “employees” table. Now, due to certain reasons, you want
to revoke those permissions. Hence, you can use the following REVOKE command to remove that privilege:
Advantages of DCL Commands
• Security: DCL commands allow database administrators to control
who has access to the data in a database and what actions they can
perform on that data. Thus, ensuring the security and integrity of the
data stored in the database.
• Granular control: DCL commands allow administrators to grant
and revoke specific privileges and permissions, Thus giving differing
levels of access (granular control) to a particular user.
• Flexibility: The ability to grant and revoke privileges as per the
requirements provides flexibility to database administrators in order
to manage access to the database.
Disadvantages of DCL Commands
• Complexity: If there is a large number of users and the database is complex,
then granting and revoking privileges can be complex and time-consuming.
• Risk of human error: Human administrators execute DCL commands and can
make mistakes in granting or revoking privileges. Thus, giving unauthorized
access to data or imposing unintended restrictions on access.
• Lack of audit trail: There may be no built-in mechanism to track changes to
privileges and permissions over time. Thus, it is extremely difficult to
determine who has access to the data and when that access was granted or
revoked.
Transaction Control Language (TCL) in SQL
 Transactions group a set of tasks into a single execution unit. Each transaction begins with a
specific task and ends when all the tasks in the group are successfully completed. If any of
the tasks fail, the transaction fails. Therefore, a transaction has only two
results: success or failure.
In this example, a transaction is started, changes are made, and a savepoint
is set. If needed, the transaction can be rolled back to the savepoint before
being committed.
SQL Aggregate functions
 SQL Aggregate Functions are used to perform calculations on a set of rows and return a
single value. They are often used with the GROUP BY clause in SQL to summarize data for
each group. Commonly used aggregate functions include COUNT(), SUM(), AVG(), MIN(),
and MAX().
 SQL Aggregate Functions are essential for summarizing and analyzing large datasets.
These functions operate on multiple rows of a table, combining them into a single, more
meaningful result. SQL Aggregate functions are mostly used with the GROUP BY clause
of the SELECT statement.
 Various Aggregate Functions
1. Count()
2. Sum()
3. Avg()
4. Min()
5. Max()
SQL Aggregate Functions with Examples
Using HAVING with Aggregate Functions
Views in SQL
 Views in SQL are a type of virtual
table that simplifies how users interact
with data across one or more tables. In
SQL, a view is a virtual table based on
the result-set of an SQL statement.
 A view contains rows and columns,
just like a real table. The fields in a
view are fields from one or more real
tables in the database.
 You can add SQL statements and
functions to a view and present the
data as if the data were coming from
one single table.
Example 1: Creating View From a Single Table
 In this example, we will create a View named DetailsView from the table StudentDetails.
 Query : Table: StudentDetails

 Output :
Example 2: Create View From Table
Example 3: Creating View From Multiple Tables
Table: StudentsMarks
Example 3: Creating View From Multiple Tables
Delete View in SQL
 SQL allows us to delete an existing View. We can delete or drop View using the DROP
statement.
Update View in SQL
 Example 1: Update View to Add or Replace a View Field
 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:
Example 2: Update View to Insert a row in a view
OUTPUT:
Example 3: Deleting a row from a View
OUTPUT :
Uses of a View
1. Restricting data access – Views provide an additional level of table security by restricting
access to a predetermined set of rows and columns of a table.
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.
4. Store complex queries – Views can be used to store complex queries.
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.
Types of Views in SQL
SQL offers three primary types of views in SQL to address different
data handling and query optimization needs.
• Simple Views: Derived from a single table, focusing on presenting
specific columns or rows.
• Complex Views: Combine data from multiple tables or include
operations like joins and aggregations.
• Materialized Views: Unlike the other two, materialized views store
query results physically for faster access and performance.
SQL Indexes
 SQL Indexes are important components in relational databases that
significantly enhance data retrieval speeds by reducing the need for full table
scans.
 By providing quick access paths, indexes allow queries to perform faster,
especially on large datasets. However, while indexes speed up SELECT
queries, they can slow down data manipulation operations (INSERT, UPDATE,
DELETE).
 An index in SQL is a schema object that improves the speed of data
retrieval operations on a table. It works by creating a separate data
structure that provides pointers to the rows in a table, making it faster to look
up rows based on specific column values.
 Indexes act as a table of contents for a database, allowing the server to locate
data quickly and efficiently, reducing disk I/O operations.
SQL Indexes
 An index in a database is a data structure that helps to improve the
speed of retrieving specific data from tables and views.
 Data in a table is stored in the form of an unordered data structure called
a "Heap", where rows are placed without any specific order. Thus, when
retrieving data from a table, the query optimizer must scan the entire
table to locate the requested rows.
 This process can be time-consuming, especially when we are dealing with
large tables. To speed up the data retrieval, SQL provides a data object
called index that stores and organizes table data in a specific way,
allowing faster data access.
Creating an Index
 Creating an index allows us to define a quick access path to data. SQL indexes can be applied
to one or more columns and can be either unique or non-unique.
 Unique indexes ensure that no duplicate values are entered in the indexed columns,
while non-unique indexes simply speed up queries without enforcing uniqueness.
For Multiple Columns
 If queries often use more than one column in conditions, we can create a multi-column index for
better performance.
Unique Indexes
 A unique index ensures that all values in the indexed column(s) are unique, preventing
duplicates. These are useful for maintaining the integrity of the data, ensuring that no two
rows have the same values in the indexed columns.
Removing an Index
 If an index is no longer needed, it can be removed to improve write performance or
save storage space. As indexes can slow down operations like INSERT, UPDATE,
and DELETE due to the overhead of maintaining them, dropping unnecessary indexes can
improve overall database efficiency. The DROP INDEX command is used for this purpose.
Altering an Index
 If an index requires adjustments, such as reorganizing or rebuilding, it
can be altered without affecting the data. This is useful for optimizing
index performance as tables grow larger.
When Should Indexes Be Created?
 Wide Range of Values: Indexes are helpful when a column
has a wide range of values, such as product IDs or customer
names, as they speed up search operations.
 Non-NULL Values: Columns that don’t contain many NULL
values are ideal candidates for indexing, as NULLs
complicate the indexing process.
 Frequent Query Conditions: Indexes should be created on
columns frequently used in WHERE clauses or as part of a join
condition.
When Should Indexes Be Avoided?
1. Small Tables: Indexes are not needed for small tables as
queries will likely perform well without them.
2. Infrequent Query Use: If a column is rarely used in queries,
indexing it will only add overhead.
3. Frequently Updated Columns: Avoid indexing columns that
are frequently updated, as the index will need to be updated
with each change, adding overhead.
Predicate in SQL
 A predicate is simply an expression that evaluates to TRUE, FALSE, or UNKNOWN.
Predicates are typically employed in the search condition of WHERE and HAVING clauses,
the join conditions of FROM clauses, as well as any other part of a query where a boolean
value is required.
 There are numerous types of predicates, including:
 Comparison
 LIKE
 BETWEEN
 IN
 EXISTS
 IS NULL (/INTEGER/DECIMAL/FLOAT...)
Comparison Predicates
 Any time that we use a comparison operator in an expression, such as WHERE
employee_salary > 100000, we are constructing a Predicate that evaluates to TRUE,
FALSE, or UNKNOWN. Comparison operators include:
 = Equal to
 > Greater than
 < Less than
 >= Greater than or equal to
 <= Less than or equal to
 <> Not equal to
 Hence, a comparison predicate takes the form of:

 expression_1 comparison_operator expression_2


 In a comparison predicate, expression2 can also be a subquery. If the subquery does
not return any rows, the comparison predicate evaluates to FALSE.
Like Predicate
 The LIKE operator is used in a WHERE clause to search
for a specified pattern in a column. Example:
Return all customers from a
 There are two wildcards often used in conjunction with city that contains the letter
the LIKE operator: 'L':

 The percent sign % represents zero, one, or multiple


characters
 The underscore sign _ represents one, single character
 Example: Select all customers that starts with
the letter "a":
BETWEEN Predicate
 The BETWEEN operator specifies a range, which determines the lower and upper
bounds of qualifying values. For instance, in the Predicate income BETWEEN 5000
AND 20000 the selected data is a range of greater then or equal to 5000 and less
then or equal to 20000. The Between operator can be used with numeric, text and
date data types. Here's an example:
 Example: Select all products with a price between 10 and 20:
IN Predicate
 An IN operator allows the specification of two or more expressions to be used for a
query search. The result of the condition is TRUE if the value of the corresponding
column equals one of the expressions specified by the IN predicate:
 Example: Return all customers from 'Germany', 'France', or 'UK'
EXISTS Predicate
 The EXISTS operator is used to test for the existence of any record in a subquery.
 The EXISTS operator returns TRUE if the subquery returns one or more records.
 The EXISTS Predicate accepts a subquery as an argument. It returns TRUE if the subquery
returns one or more rows, and returns FALSE if it returns zero rows.
IS NULL Predicate
 Use IS NULL to determine whether an expression is null, because you cannot test for null
by using the = comparison operator. When applied to row value expressions, all elements
must test the same.
 The IS NULL predicate takes the following form: IS [NOT] NULL
Trigger in SQL
 SQL triggers are a critical feature in database management systems (DBMS) that
provide automatic execution of a set of SQL statements when specific database
events, such as INSERT, UPDATE, or DELETE operations, occur.
 Triggers are commonly used to maintain data integrity, track changes, and enforce
business rules automatically, without needing manual input.
 A trigger is a stored procedure in a database that automatically invokes whenever a
special event in the database occurs. By using SQL triggers, developers
can automate tasks, ensure data consistency, and keep accurate records
of database activities. For example, a trigger can be invoked when a row is inserted
into a specified table or when specific table columns are updated.
 In simple words, a trigger is a collection of SQL statements with particular names
that are stored in system memory. It belongs to a specific class of stored
procedures that are automatically invoked in response to database server events.
Every trigger has a table attached to it.
Trigger in SQL
Types of SQL Triggers
 Triggers can be categorized into different types based on the action they are
associated with:
1. DDL Triggers : The Data Definition Language (DDL) command events such
as Create_table, Create_view, drop_table, Drop_view, and Alter_table cause
the DDL triggers to be activated. They allow us to track changes in the structure of the
database. The trigger will prevent any table creation, alteration, or deletion in the
database.
2. DML Triggers :The Data manipulation Language (DML) command events that begin
with Insert, Update, and Delete set off the DML triggers. DML triggers are used for
data validation, ensuring that modifications to a table are done under controlled
conditions.
3. Logon Triggers :These triggers are fired in response to logon events. Logon triggers
are useful for monitoring user sessions or restricting user access to the database. As
a result, the PRINT statement messages and any errors generated by the trigger will
all be visible in the SQL Server error log. Authentication errors prevent logon triggers
from being used. These triggers can be used to track login activity or set a limit on the
number of sessions that a given login can have in order to audit and manage server
sessions.
BEFORE and AFTER Triggers
 SQL triggers can be specified to run BEFORE or AFTER the triggering event.
• BEFORE Triggers: Execute before the actual SQL statement is executed. Useful for validating
data before insertion or updating.
• AFTER Triggers: Execute after the SQL statement completes. Useful for logging or cascading
updates to other tables.
• Example: Using BEFORE Trigger for Calculations
• Given Student Report Database, in which student marks assessment is recorded. In such a
schema, create a trigger so that the total and percentage of specified marks are automatically
inserted whenever a record is inserted. Here, a trigger will invoke before the record is
inserted so BEFORE Tag can be used.
 Below SQL statement will create a trigger in the student database in which whenever
subjects marks are entered, before inserting this data into the database, the trigger will
compute those two values and insert them with the entered values. In this way, triggers can
be created and executed in the databases.
After Trigger
 Example: Write a trigger to count
number of new tuples inserted
using each insert statement.
 Explanation: We want to keep track
of the number of new Tuples in the
employee table. For that, we first
create a variable ‘count’ and initialize
it to 0. After that, we create a trigger
named Count_tuples that will
increment the value of count after
insertion of any new Tuple in the
table employee.

Advantages of Triggers
• Data Integrity: Triggers help enforce consistency and business rules,
ensuring that data follows the correct format.
• Automation: Triggers eliminate the need for manual intervention by
automatically performing tasks such as updating, inserting, or deleting
records when certain conditions are met.
• Audit Trail: Triggers can track changes in a database, providing an audit
trail of INSERT, UPDATE, and DELETE operations.
• Performance: By automating repetitive tasks, triggers improve SQL
query performance and reduce manual workload.

You might also like