Structured Query Language
Structured Query Language
(STRUCTURED QUERY
LANGUAGE)
Contents
SQL Introduction ....................................................................................................................... 5
SQL History........................................................................................................................... 5
What are the Characteristics of SQL? ................................................................................... 5
Components of a SQL System .............................................................................................. 6
What is Database? ..................................................................................................................... 6
Key Features of a Database ................................................................................................... 6
Why is a Database Important? .............................................................................................. 7
Types of Databases ................................................................................................................ 7
What is a DBMS? ................................................................................................................ 10
SQL Data Types....................................................................................................................... 10
Data types ............................................................................................................................ 11
Operators in SQL..................................................................................................................... 12
Types of SQL Operators ...................................................................................................... 12
Arithmetic Operators ....................................................................................................... 12
Comparison Operators..................................................................................................... 13
Logical Operators ............................................................................................................ 13
Bitwise Operators ............................................................................................................ 13
Compound Operators ...................................................................................................... 14
SQL Commands ...................................................................................................................... 14
1. Data Definition Language (DDL) ................................................................................... 15
Common DDL Commands .............................................................................................. 15
2. Data Manipulation Language .......................................................................................... 15
Common DML Commands ............................................................................................. 15
3. Data Control Language ................................................................................................... 15
Common DCL Commands .............................................................................................. 15
4. Transaction Control Language ........................................................................................ 15
Common TCL Commands .............................................................................................. 16
Database Related Queries........................................................................................................ 16
SQL Table ................................................................................................................................ 16
CREATE TABLE ................................................................................................................ 17
DROP TABLE ..................................................................................................................... 18
ALTER Command in SQL .................................................................................................. 19
DROP and TRUNCATE .......................................................................................................... 19
SQL SELECT queries ............................................................................................................. 20
SQL UPDATE Statement .................................................................................................... 22
SQL Clauses ............................................................................................................................ 23
Aggregate functions ................................................................................................................ 24
SQL Data Constraints .............................................................................................................. 25
SQL Joins ................................................................................................................................ 29
Inner Join ............................................................................................................................. 29
Example of SQL INNER JOIN ......................................................................................... 30
LEFT JOIN (LEFT OUTER JOIN)..................................................................................... 30
SQL RIGHT JOIN ............................................................................................................... 31
SQL Full Join ...................................................................................................................... 33
SQL Date Data Types .............................................................................................................. 35
SQL Date Functions ............................................................................................................ 35
String functions ....................................................................................................................... 36
Common SQL String Functions .......................................................................................... 36
Numeric Functions .................................................................................................................. 37
Commonly Used SQL Numeric Functions ......................................................................... 37
SQL Views ............................................................................................................................... 38
CREATE VIEWS IN SQL .................................................................................................. 38
Examples ........................................................................................................................... 39
Listing all Views in a Database ........................................................................................... 41
Delete View in SQL ............................................................................................................ 41
Update View in SQL ........................................................................................................... 41
Example ............................................................................................................................... 41
SQL Indexes ............................................................................................................................ 42
Creating an Index ................................................................................................................ 42
Creating a Unique Index: ................................................................................................ 43
When Should Indexes Be Created? ..................................................................................... 43
Example ............................................................................................................................... 43
DROP INDEX ..................................................................................................................... 44
Subqueries in SQL................................................................................................................... 44
Examples of SQL Subqueries.............................................................................................. 45
SQL Wildcard Characters ........................................................................................................ 45
Types of SQL Wildcard Characters ..................................................................................... 45
Example of SQL Wildcard Characters ................................................................................ 46
SQL Introduction
SQL was invented in 1970s and was first commercially distributed by Oracle.
The original name was given by IBM as Structured English Query Language,
abbreviated by the acronym SEQUEL.
User-Friendly and Accessible: SQL is designed for a broad range of users, including
those with minimal programming experience, making it approachable for non-technical
individuals.
Efficient Database Management: SQL enables the creation, modification, and
management of databases efficiently, saving time and simplifying complex database
operations.
Standardized Language: Based on ANSI (American National Standards Institute) and
ISO (International Organization for Standardization) standards, SQL ensures
consistency and stability across various database management systems (DBMS).
Command Structure: SQL does not require a continuation character for multi-line
queries, allowing flexibility in writing commands across one or multiple lines.
Execution Mechanism: Queries are executed using a termination character (e.g., a
semicolon ;), enabling immediate and accurate command processing.
Built-in Functionality: SQL includes a rich set of built-in functions for data
manipulation, aggregation, and formatting, empowering users to handle diverse data-
processing needs effectively.
A SQL system consists of several key components that work together to enable efficient data
storage, retrieval, and manipulation. Some of the Key components of a SQL System are:
Databases: Databases are structured collections of data organized into tables, rows, and
columns. Databases serve as repositories for storing information efficiently and provide
a way to manage and access data.
Tables: Tables are the fundamental building blocks of a database, consisting of rows
(records) and columns (attributes or fields). Tables ensure data integrity and consistency
by defining the structure and relationships of the stored information.
Queries: Queries are SQL commands used to interact with databases. They enable users
to retrieve, update, insert, or delete data from tables, allowing for efficient data
manipulation and retrieval.
Constraints: Constraints are rules applied to tables to maintain data
integrity. Constraints define conditions that data must meet to be stored in the database,
ensuring accuracy and consistency.
Transactions: Transactions are groups of SQL statements that are executed as a single
unit of work. Transactions ensure data consistency and integrity by allowing for the
rollback of changes if any part of the transaction fails.
What is Database?
Databases play a critical role in managing and organizing data, enabling businesses to
operate efficiently and make informed decisions. Here’s why they are essential:
1. Efficient Scaling: Databases can handle massive amounts of data, scaling to millions or
billions of records. Without databases, managing this level of digital data would be impossible.
2. Data Integrity: Built-in rules and conditions in databases ensure data
consistency and accuracy, even as it grows or changes.
3. Data Security: Databases protect sensitive information by implementing user
authentication, access control, and compliance with privacy regulations.
4. Data Analytics: Modern databases support analytics tools to identify patterns, trends,
and predictions. This capability helps organizations make data-driven decisions.
Types of Databases
2. Network Databases: A network database builds on the hierarchical model but allows
child records to link to multiple parent records, creating a web-like structure of
interconnected data. For example, in a university database, “Students,” “Faculty,” and
“Resources” can be linked to both “Departments” and “Clubs,” forming a flexible, two-
directional relationship.
4.Relational Databases: Considered the most mature of all databases, these databases lead
in the production line along with their management systems. In this database, every piece of
information has a relationship with every other piece of information. This is on account of
every data value in the database having a unique identity in the form of a record.
What is a DBMS?
A DBMS is a system that allows users to create, modify, and query databases while
ensuring data integrity, security, and efficient data access. Unlike traditional file systems,
DBMS minimizes data redundancy, prevents inconsistencies, and simplifies data management
with features like concurrent access and backup mechanisms. It organizes data
into tables, views, schemas, and reports, providing a structured approach to data management.
Example:
A university database can store and manage student information, faculty records, and
administrative data, allowing seamless retrieval, insertion, and deletion of information as
required.
SQL Data Types are very important in relational databases. It ensures that data is stored
efficiently and accurately. Data types define the type of value a column can hold, such
as numbers, text, or dates.
Data types mainly classified into three categories for every database.
o String Data types
o Numeric Data types
o Date and time Data types
Data types
❖ CHAR
o Description: String (0-255), can store characters of fixed length
o Usage: CHAR(50)
❖ VARCHAR
o Description: String (0-255), can store characters up to a given length
o Usage: VARCHAR(50)
❖ BLOB
o Description: String (0-65535), can store binary large objects
o Usage: BLOB(1000)
❖ INT
o Description: Integer (-2,147,483,648 to 2,147,483,647)
o Usage: INT
❖ TINYINT
o Description: Integer (-128 to 127)
o Usage: TINYINT
❖ BIGINT
o Description:Integer(-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
o Usage: BIGINT
❖ BIT
o Description: Can store x-bit values. x can range from 1 to 64
o Usage: BIT(2)
❖ FLOAT
o Description: Decimal number with precision up to 23 digits
o Usage: FLOAT
❖ DOUBLE
o Description: Decimal number with precision from 24 to 53 digits
o Usage: DOUBLE
❖ BOOLEAN
o Description: Boolean values 0 or 1
o Usage: BOOLEAN
❖ DATE
o Description: Date in the format YYYY-MM-DD, ranging from 1000-01-01 to
9999-12-31
o Usage: DATE
❖ YEAR
o Description: Year in 4 digits, ranging from 1901 to 2155
o Usage: YEAR
Operators in SQL
SQL operators are important in database management systems (DBMS) as they allow us to
manipulate and retrieve data efficiently. SQL operators are symbols or keywords used to
perform operations on data in SQL queries. These operations can include mathematical
calculations, data comparisons, logical manipulations, other data-processing tasks.
Operators help in filtering, calculating, and updating data in databases, making them crucial
for query optimization and accurate data management.
Comparison Operators
Comparison Operators in SQL are used to compare one expression’s value to other
expressions.
Operator Description
= Equal to.
> Greater than.
< Less than.
>= Greater than equal to.
<= Less than equal to.
<> Not equal to.
Logical Operators
Logical Operators in SQL are used to combine or manipulate conditions in SQL queries to
retrieve or manipulate data based on specified criteria..
Operator Description
AND Logical AND compares two Booleans as expressions and returns true when both
expressions are true.
OR Logical OR compares two Booleans as expressions and returns true when one
of the expressions is true.
NOT Not takes a single Boolean as an argument and change its value from false to
true or from true to false.
Bitwise Operators
Bitwise operators in SQL are used to perform bitwise operations on binary values in SQL
queries, manipulating individual bits to perform logical operations at the bit level.
Operator Description
& Bitwise AND operator
| Bitwise OR operator
^ Bitwise XOR (exclusive OR) operator
~ Bitwise NOT (complement) operator
Compound Operators
Compound operators combine an operation with assignment. These operators modify the value
of a column and store the result in the same column in a single step.
Operator Description
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulo and assign
&= Bitwise AND and assign
^= Bitwise XOR and assign
|= Bitwise OR and assign
SQL Commands
SQL Commands are like instructions to a table. It is used to interact with the database with
some operations. It is also used to perform
specific tasks, functions, and queries of data.
SQL can perform various tasks like creating a
table, adding data to tables, dropping the table,
modifying the table, set permission for users.
SQL Commands are mainly categorized into
five categories:
❖ DDL – Data Definition Language
❖ DML – Data Manipulation Language
❖ DCL – Data Control Language
❖ TCL – Transaction Control Language
1. Data Definition Language (DDL)
DDL or Data Definition Language actually consists of the SQL commands that can be used
to defining, altering, and deleting database structures such as tables, indexes, and schemas.
It simply deals with descriptions of the database schema and is used to create and modify the
structure of database objects in the database.
Common DDL Commands
❖ Create: It is used to create a new table in the database or a Database.
❖ Drop: It is used to delete both the structure and record stored in the table.
❖ Alter: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
❖ Truncate: It is used to delete all the rows from the table and free the space containing
the table.
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.
Common DML Commands
❖ Insert: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.
❖ Update: This command is used to update or modify the value of a column in the table.
❖ Delete: It is used to remove one or more row from a table.
❖ Select: It is used to select the attribute based on the condition.
3. Data Control Language
DCL commands are used to grant and take back authority from any database user.
Common DCL Commands
❖ Grant: To give permission
❖ Revoke: It is used to take back permissions from the user.
4. Transaction Control Language
Transactions are atomic i.e. either every statement succeeds or none of statement succeeds.
There are number of Transaction Control statements available that allow us to control this
behaviour. These statements ensure data consistency. TCL commands can only use with DML
commands like INSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.
Common TCL Commands
❖ Commit: Commit command is used to save all the transactions to the database. It makes
your changes permanent and ends the transaction.
❖ Rollback: Rollback command is used to undo transactions that have not already been
saved to the database. Rollback also serves to end the current transaction and begin a
new one.
CREATE DATABASE
Syntax:
CREATE DATABASE database_name;
SHOW DATABASES
Syntax:
SHOW DATABASES;
Delete a Database
Syntax:
DROP DATABASE db_name;
DROP DATABASE IF EXISTS: use the IF EXISTS clause, which will delete the database
only if it exists in the system.
Syntax:
DROP DATABASE IF EXISTS Database_Name;
Select the Database: To set database as the active database, use the USE command
Syntax:
USE db_name;
SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.
Note: A table has a specified number of columns, but can have any number of rows.
EMP_NAME ADDRESS SALARY
Ankita Lucknow 15000
Ramanand Allahabad 18000
Jack New York 20000
CREATE TABLE
The CREATE TABLE command is a crucial tool for database administration because of these
limitations, which aid in ensuring data integrity. To create a table in SQL, use this CREATE
TABLE syntax:
CREATE TABLE table_name(
Column1 datatype(size),
Column2 datatype(size),
.
.
Column n datatype(size)
);
• table_name: The name you assign to the new table.
• column1, column2, … : The names of the columns in the table.
• datatype(size): Defines the data type and size of each column.
A SQL DROP TABLE statement is used to delete a table definition and all data from a table.
• This operation cannot be undone, and once the table is dropped all data in that table is
lost.
• Once executed, this operation removes the table definition and all of its rows, so the
table can no longer be accessed or used.
• This action is irreversible which means that once a table is dropped, it cannot be
recovered.
Syntax:
DROP TABLE "table_name";
SQL DELETE Statement
The SQL DELETE statement removes one or more rows from a database table based on a
condition specified in the WHERE clause. It’s a DML (Data Manipulation Language)
operation that modifies the data within the table without altering its structure.
Syntax:
DELETE FROM table_name
WHERE some_condition;
• Some_condition: condition to choose a particular record.
• table_name: name of the table
ALTER Command in SQL
If we need to rename a table, add a new column, or change the name of an existing column
in SQL, the ALTER command is crucial for making schema changes without affecting the
data that is already there. This is essential for tasks like:
• Renaming a table.
• Changing a column name.
• Adding or deleting columns.
• Modifying the data type of a column.
Syntax:
1.Renaming a Table
ALTER TABLE table_name RENAME TO new_table _name;
2. Renaming a column
ALTER TABLE table_name RENAME COLUMN old_column_name to
new_column_name;
3. Adding a column
ALTER TABLE table_name ADD COLUMN new_column _name data_type;
4. Modifying the data type a column
ALTER TABLE table_name MODIFY COLUMN column_name
new_data_type;
DROP Table
To delete an entire table, including its data and structure:
Syntax:
DROP TABLE table_name;
TRUNCATE Command
The TRUNCATE command is a Data Definition Language (DDL) action that removes all
rows from a table but preserves the structure of the table for future use.
Syntax:
TRUNCATE TABLE table_name;
Key Differences Between DROP and TRUNCATE
The key differences between DROP and TRUNCATE statements are explained in the
following table:
Feature DROP TRUNCATE
Effect on Table Completely removes both the data Removes all rows but preserves
Structure and the table structure the table structure
Data Deletion Deletes both data and table Deletes only the data, not the table
definition structure
Recovery Non-recoverable; once dropped, Can be rolled back if used in a
the table cannot be restored (unless transaction (if supported by the
you have backups) DBMS)
Triggers Does not activate triggers Does not activate DELETE
associated with the table triggers
Performance Slower due to data and structural Faster, especially for large datasets
removal
Usage Used when you want to completely Used to quickly remove all rows
remove a table or database from a table but keep the structure
for future use
SELECT DISTINCT
The SQL DISTINCT command is used with SELECT key word to retrieve only distinct or
unique data.
Syntax:
SELECT DISTINCT column name ,column_name
FROM table_name;
SELECT COUNT
The SQL COUNT() is a function that returns the number of records of the table in the output.
Syntax:
SELECT COUNT(column_name)
FROM table_name;
Syntax of Count (*) Function in SQL
SELECT COUNT(*) FROM table_name;
Example:
Bike_Name Bike_Color Bike_Cost
Livo Black 185,000
Apache Red NULL
Pulsar Red 90,0000
Royal Enfield Black NULL
KTM DUKE Black 80,000
KTM RC White 195,000
The count(*) function in SQL shows all the Null and Non-Null records present in the table.
Count() Function with WHERE clause in SQL
SELECT COUNT(column_name) FROM table_name WHERE [condition];
ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending
order.
The ORDER BY keyword sorts the records in ascending order by default. To sort
the records in descending order, use the DESC keyword.
Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT SUM
It is also known as SQL SUM() function. It is used in a SQL query to return
summed value of an expression.
Syntax:
SELECT SUM (expression)
FROM tables
WHERE conditions;
Syntax:
The syntax for SQL UPDATE Statement is :
UPDATE table_name SET column1 = value1, column2 = value2,…
WHERE condition;
• table_name: name of the table
• column1: name of first, second, third column….
• value1: new value for first, second, third column….
• condition: condition to select the rows for which the
SQL Clauses
WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
The WHERE clause is not only used in SELECT statements, it is also used
in UPDATE, DELETE, etc.!
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
GROUP BY Clause
The GROUP BY statement in SQL is used to arrange identical data into groups based on
specified columns.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
GROUP BY column1, column2
Key Terms
1. function_name: Name of the function used for example, SUM() , AVG().
2. table_name: Name of the table.
3. condition: Condition used.
HAVING Clause
The HAVING clause in SQL is used to filter query results based on aggregate functions. It is
commonly used with functions like SUM(), AVG(), COUNT(), MAX(), and MIN().
It allows filtering grouped data using Boolean conditions (AND, OR).
Key Features of the HAVING Clause
• Used to filter grouped data based on aggregate functions.
• Works with Boolean conditions (AND, OR
• Cannot be used without GROUP BY unless an aggregate function is present.
• Must be placed after the GROUP BY clause and before the ORDER BY clause (if
used).
Syntax:
Aggregate functions
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.
Common SQL Aggregate Functions
Sum():
The SUM() function provides the total sum of a numeric column. This function is ideal for
calculating totals such as sales, revenue, or any other cumulative numeric value.
Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Avg():
The AVG() function provides the average value of a numeric column, helping you determine
central tendencies in your data. This is useful for understanding the mean value of a set of
numbers, such as salaries, prices, or scores.
Syntax:
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Min():
MIN() function returns the smallest value in the column. It can be used with various data types,
including numbers, strings, and dates.
Syntax:
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Max():
MAX() function returns the largest value in the column. It can can be used with various data
types, including numbers, strings, and dates.
The MAX() function in SQL can be used in combination with other SQL clauses and
functions, such as GROUP BY, HAVING.
Syntax:
SELECT MAX(column_name)
FROM table_name
WHERE condition;
New Table
Syntax:
CREATE TABLE child_table_name (
column_name1 DATA_TYPE,
column_name1 DATA_TYPE,
column_name1 DATA_TYPE,
FOREIGN KEY (column_name) REFERENCES parent_table(parent_column)
);
Add Foreign key to Existing Table
ALTER TABLE child_table
ADD CONSTRAINT constraint_name
FOREIGN KEY (column_name) REFERENCES parent_table(parent_column);
SQL Joins
The SQL JOIN clause takes records from two or more tables in a database and combines it
together. 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. We can use SQL
JOIN with multiple tables. It can also be paired with other clauses, the most popular use will
be using JOIN with WHERE clause to filter data retrieval.
SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, is critical for
working with relational databases.
SQL JOIN Syntax
SELECT columns_from_both_tables
FROM table1
JOIN table2
ON table1.column1 = table2.column2
Inner Join
The INNER JOIN clause in SQL is used to combine records from two or more tables. The
result contains only the rows that have matching values in both tables based on a specific
condition. This makes INNER JOIN a valuable tool when we need to work with related data
across multiple tables in a database.
Syntax:
SELECT columns_from_both_tables
FROM table1
INNER JOIN table2
ON table1.column1 = table2.column2
Key Terms
• columns: The specific columns we want to retrieve.
• table1 and table2: The two tables we are joining.
• column_name: The columns from both tables that we want to match based on the join
condition.
Department
Employees
Output:
Output:
The RIGHT JOIN in SQL returns a table that contains all the records from the right table and
only matching records from the left table. In simpler terms, if a row is present in the right table
but not in the left table, the result will include this row
with NULL values for columns from the left table.
Conversely, if a record from the left table is not in the
right table, it will not be included in the result.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ...
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Example:
EMPLOYEE TABLE
DEPARTMENT TABLE
Query:
SELECT emp_no,emp_name,dept_name,location
FROM employee
RIGHT JOIN department
ON employee.dept_no=department.dept_no;
OUTPUT:
• The FULL JOIN or FULL OUTER JOIN in SQL is used to retrieve all rows from
both tables involved in the join, regardless of whether there is a match between the rows
in the two tables.
• It combines the results of both a LEFT JOIN and a RIGHT JOIN.
• When there is no match, the result will include NULLs for the columns of the table that
do not have a matching row.
Syntax:
SELECT table1.column1, table1.column2, table2.column1, ...
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
• SELECT columns: Specifies the columns to retrieve.
• FROM table1: The first table to be joined.
• FULL JOIN table2: Specifies the second table to join with the first table using a FULL
JOIN.
• ON table1.column = table2.column: Defines the condition to match rows between the
two tables.
Note: MySQL does NOT support FULL OUTER JOIN directly. However, we can achieve the
same result by using a combination of LEFT JOIN and UNION with a RIGHT JOIN.
Example:
Students
Courses
Query:
Output:
1. NOW()
The NOW() function retrieves the current date and time in YYYY-MM-DD
HH:MI:SS format.
2. CURDATE()
CURDATE() returns the current date in YYYY-MM-DD format, without the time part.
3. CURTIME()
The CURTIME() function returns the current time in HH:MI:SS format, excluding the date.
4. DATE()
Extracts the date part of a date or date/time expression.
5. EXTRACT()
The EXTRACT() function retrieves a specific part of a DATE, DATETIME,
or TIMESTAMP value, such as the day, year, or second.
Syntax:
EXTRACT(unit FROM date);
String functions
SQL String Functions are powerful tools that allow us to manipulate, format, and extract
specific parts of text data in our database. These functions are essential for tasks like cleaning
up data, comparing strings, and combining text fields.
SQL Numeric Functions are used to perform operations on numeric data types such as INT,
FLOAT, DECIMAL, DOUBLE, and others. These functions help you manipulate numbers in
various ways, including performing arithmetic operations, rounding, formatting, and
aggregating data.
Commonly Used SQL Numeric Functions
SQL Views
Views in SQL are a type of virtual table that simplifies how users interact with data across
one or more tables. Unlike traditional tables, a view in SQL does not store data on disk;
instead, it dynamically retrieves data based on a pre-defined query each time it’s accessed.
A view in SQL is a saved SQL query that acts as a virtual table. It can fetch data from one or
more tables and present it in a customized format, allowing developers to:
• Simplify Complex Queries: Encapsulate complex joins and conditions into a single
object.
• Enhance Security: Restrict access to specific columns or rows.
• Present Data Flexibly: Provide tailored data views for different users.
CREATE VIEWS IN SQL
We can create a view using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2…..
FROM table_name
WHERE condition;
Parameters:
• view_name: Name for the View
• table_name: Name of the table
• condition: Condition to select rows
Examples
Table 1: StudentDetails
Table 2: StudentMarks
SQL allows us to delete an existing View. We can delete or drop View using the DROP
statement.
Syntax:
DROP VIEW view_name;
Update View in SQL
To update the existing data within the view, use the UPDATE statement.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Rules to Update Views in SQL:
Certain conditions need to be satisfied to update a view. If any of these conditions are not met,
the view cannot be updated.
1. The SELECT statement which is used to create the view should not include GROUP
BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
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.
Example
we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table.
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
SQL Indexes
Create an Index
CREATE INDEX idx ON STUDENT(student_id);
Retrieve Data Using the Index
SELECT * FROM STUDENTS USE INDEX(idx);
DROP INDEX
The DROP INDEX statement in SQL is used to delete an index from a table.
ALTER TABLE table_name DROP INDEX index_name;
Key Terms
• table_name: The name of the table.
• index_name: The name of the index to be dropped
Subqueries in SQL
In SQL, subqueries are one of the most powerful and flexible tools for writing efficient
queries. A subquery is essentially a query nested within another query, allowing users
to perform operations that depend on the results of another query. This makes
it invaluable for tasks such as filtering, calculating aggregates, or even modifying data
dynamically.
In SQL, a subquery can be defined as a query embedded within another query. It is often
used in the WHERE, HAVING, or FROM clauses of a statement. Subqueries are commonly
used with SELECT, UPDATE, INSERT, and DELETE statements to achieve complex
filtering and data manipulation.
Syntax:
SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name FROM table_name WHERE ...);
Examples of SQL Subqueries