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

Views in SQL

Uploaded by

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

Views in SQL

Uploaded by

veena shinde
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Views in SQL

o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present
in the database.
o A view can either have specific rows based on certain condition or all the rows
of a table.
Advantages of View:
1. Complexity: Views help to reduce the complexity. Different views can be created on the
same base table for different users.
2. Security: It increases the security by excluding the sensitive information from the view.
3. Query Simplicity: It helps to simplify commands from the user. A view can draw data
from several different tables and present it as a single table.
4. Consistency: A view can present a consistent, unchanged image of the structure of the
database. Views can be used to rename the columns without affecting the base table.
5. Data Integrity: If data is accessed and entered through a view, the DBMS can
automatically check the data to ensure that it meets the specified integrity constraints.
6. Storage Capacity: Views take very little space to store the data.

Sample table:
Student_Detail

STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram
Student_Marks

STU_ID NAME MARKS AGE

1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from
a single table or multiple tables.

Syntax:

1. CREATE VIEW view_name AS


2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;

2. Creating View from a single table


In this example, we create a View named DetailsView from the table Student_Detail.

Query:

1. CREATE VIEW DetailsView AS


2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. WHERE STU_ID < 4;
Just like table query, we can query the view to view the data.

1. SELECT * FROM DetailsView;


Output:

NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables


View from multiple tables can be created by simply include multiple tables in the
SELECT statement.

In the given example, a view is created named MarksView from two tables
Student_Detail and Student_Marks.

Query:

1. CREATE VIEW MarksView AS


2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS

3. FROM Student_Detail, Student_Mark


4. WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of View MarksView:

1. SELECT * FROM MarksView;

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90
4. Deleting View
A view can be deleted using the Drop View statement.

Syntax

1. DROP VIEW view_name;

Example:
If we want to delete the View MarksView, we can do this as:

1. DROP VIEW MarksView;

SQL - Using Sequences


Sequences in SQL are database objects that generate a sequence of unique
integer values. They are frequently used in databases because many
applications require that each row in a table must contain unique values and
sequences provide an easy way to generate them.

Sequences are a feature of many SQL database management systems, such


as Oracle, PostgreSQL, SQL server, and IBM DB2.

MySQL does not support the CREATE SEQUENCE statement to create


sequences for table rows or columns. Instead, we can use AUTO_INCREMENT
attribute.

Sequences in MySQL
In MySQL, we use the AUTO_INCREMENT attribute to generate unique
integer values (sequences) for a column. By default, the sequence starts with
an initial value of 1 and increments by 1 for each new row.
Syntax
Following is the syntax of AUTO_INCREMENT attribute in MySQL −

CREATE TABLE table_name (


column1 datatype AUTO_INCREMENT,
column2 datatype,
column3 datatype,
...
columnN datatype
);

Example
In the following example, we are creating a table named CUSTOMERS. In
addition to that, we are defining AUTO_INCREMENT on ID column of the table.

CREATE TABLE CUSTOMERS (


ID INT AUTO_INCREMENT,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Here, we are adding some records into the above created table –
INSERT INTO CUSTOMERS VALUES
(NULL, 'Ramesh', 32, 'Ahmedabad', 2000.00),
(NULL, 'Khilan', 25, 'Delhi', 1500.00),
(NULL, 'Kaushik', 23, 'Kota', 2000.00),
(NULL, 'Chaitali', 25, 'Mumbai', 6500.00),
(NULL, 'Hardik', 27, 'Bhopal', 8500.00),
(NULL, 'Komal', 22, 'Hyderabad', 4500.00),
(NULL, 'Muffy', 24, 'Indore', 10000.00);

The table will be created as follows −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

As we can see in the above table, the values in the ID column are auto
incremented.
Starting a Sequence at a Particular Value in MySQL
By default, MySQL sequences start from 1. To start a sequence with a
different value, we use the AUTO_INCREMENT in combination with
the ALTER statement.
Syntax
Following is the syntax to start the sequence with different value −

ALTER TABLE table_name AUTO_INCREMENT = value;

In the following query, we are creating a table named BUYERS with


AUTO_INCREMENT defined on the ID column.

CREATE TABLE BUYERS (


ID INT AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Here, we are making the sequence start with 100 using the ALTER Statement
as shown below −

ALTER TABLE BUYERS AUTO_INCREMENT=100;

Now, we are adding records into the BUYERS table using the INSERT INTO
statement −

INSERT INTO BUYERS VALUES


('Ramesh', 32, 'Ahmedabad', 2000.00),
('Khilan', 25, 'Delhi', 1500.00),
('Kaushik', 23, 'Kota', 2000.00),
('Chaitali', 25, 'Mumbai', 6500.00),
('Hardik', 27, 'Bhopal', 8500.00),
('Komal', 22, 'Hyderabad', 4500.00),
('Muffy', 24, 'Indore', 10000.00);

The table will be created as −

ID NAME AGE ADDRESS SALARY


100 Ramesh 32 Ahmedabad 2000.00

101 Khilan 25 Delhi 1500.00

102 Kaushik 23 Kota 2000.00

103 Chaitali 25 Mumbai 6500.00

104 Hardik 27 Bhopal 8500.00

105 Komal 22 Hyderabad 4500.00

106 Muffy 24 Indore 10000.00

As observed in the table above, the values in the "ID" column begin with 100
instead of 1.

Sequences in SQL Server


In SQL server, a sequence can be created using the CREATE
SEQUENCE statement. The statement specifies the name of the sequence,
the starting value, the increment, and other properties of the sequence.
Syntax
Following is the syntax to create a sequence in SQL −

CREATE SEQUENCE Sequence_Name


START WITH Initial_Value
INCREMENT BY Increment_Value
MINVALUE Minimum_Value
MAXVALUE Maximum_Value
CYCLE|NOCYCLE;

Here,

 Sequence_Name − This specifies the name of the sequence.


 Initial_Value − This specifies the starting value from where the
sequence should start.
 Increment_Value − This specifies the value by which the sequence
will increment by itself. This can be valued positively or negatively.
 Minimum_Value − This specifies the minimum value of the sequence.
 Maximum_Value − This specifies the maximum value of the
sequence.
 Cycle − When the sequence reaches its Maximum_Value, it starts
again from the beginning.
 Nocycle − An exception will be thrown if the sequence exceeds the
Maximum_Value.
Example
First of all, let us create a table named CUSTOMERS using the following query

CREATE TABLE CUSTOMERS (


ID INT,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
);

We are inserting some records in the above-created table using INSERT INTO
statement as shown in the query below −

INSERT INTO CUSTOMERS VALUES


(NULL, 'Ramesh', 32, 'Ahmedabad', 2000.00),
(NULL, 'Khilan', 25, 'Delhi', 1500.00),
(NULL, 'Kaushik', 23, 'Kota', 2000.00),
(NULL, 'Chaitali', 25, 'Mumbai', 6500.00),
(NULL, 'Hardik', 27, 'Bhopal', 8500.00),
(NULL, 'Komal', 22, 'Hyderabad', 4500.00),
(NULL, 'Muffy', 24, 'Indore', 10000.00 );

The table is successfully created in the SQL database.

ID NAME AGE ADDRESS SALARY

NULL Ramesh 32 Ahmedabad 2000.00

NULL Khilan 25 Delhi 1500.00

NULL Kaushik 23 Kota 2000.00

NULL Chaitali 25 Mumbai 6500.00

NULL Hardik 27 Bhopal 8500.00


NULL Komal 22 Hyderabad 4500.00

NULL Muffy 24 Indore 10000.00

Now, create a sequence using the following query −

CREATE SEQUENCE My_Sequence AS INT


START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 7
CYCLE;
In the above query, the sequence is named My_Sequence and it starts with
the value 1 and increments by 1 each time a value is generated. The
sequence has a maximum value of 5 and cycles back to the starting value
when it reaches the maximum value.
Once the sequence is created, it can be used to generate unique integer
values. Now, let us update the data in the ID column of the CUSTOMERS table
using the following query −
UPDATE CUSTOMERS SET ID = NEXT VALUE FOR my_Sequence;
Output
When you execute the above query, the output is obtained as follows −

(7 rows affected)
Verification
Let us verify whether is sequence is updated in the ID column of the table or
not using the following query −

SELECT * FROM CUSTOMERS;

The table will be displayed as −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00


3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

Synonyms

In the world of database management, SQL Server offers


various tools and features to enhance productivity and
maintainability. One such feature is synonyms, which
provide a convenient way to simplify SQL queries,
especially in scenarios where objects are frequently
renamed, relocated, or replaced. Synonyms act as aliases
for database objects, allowing users to refer to them by a
consistent name regardless of their actual name or
location within the database.

Understanding Synonyms:

A synonym in SQL Server is an alternate name for a


database object such as a table, view, stored procedure, or
function. It provides a layer of abstraction over the
underlying object, allowing users to reference the object
by its synonym name rather than its actual name. This
abstraction helps in scenarios where the object’s name or
location may change over time, as applications referencing
the synonym need not be updated.
Synonyms can be particularly useful in the following
situations:

1. Renaming Objects: When an object’s name needs to


be changed, updating all references to that object in
existing code can be time-consuming and error-prone.
By using synonyms, you can maintain a consistent alias
for the object, reducing the need for widespread code
changes.
2. Hiding Complexity: Synonyms can hide the complexity
of database schemas by providing simplified and
consistent names for objects. This can improve code
readability and maintainability, especially in large
databases with numerous tables and views.
3. Cross-Database Access: Synonyms can be created to
reference objects in other databases on the same SQL
Server instance, facilitating seamless access to data
across multiple databases without the need for fully
qualified object names.

Creating a synonym in SQL Server is straightforward using


the CREATE SYNONYM statement.

Let’s consider an example where we have a table


named Employees in the HumanResources schema, and we want
to create a synonym called Emp for this table:
USE AdventureWorks;
GO

CREATE SYNONYM Emp


FOR HumanResources.Employees;
GO

Once the synonym is created, we can use it in SQL queries


just like we would use the original table name:

SELECT * FROM Emp;

This query will retrieve data from the Employees table, but it
refers to it using the synonym Emp.

SQL INDEX Statement


Indexes are used to retrieve data from the database more quickly. The users
cannot see the indexes, they are just used to speed up searches/queries.

CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2, ...);

CREATE UNIQUE INDEX Syntax


Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

Note: The syntax for creating indexes varies among different databases.
Therefore: Check the syntax for creating indexes in your database.
CREATE INDEX Example
The SQL statement below creates an index named "idx_lastname" on the
"LastName" column in the "Persons" table:

CREATE INDEX idx_lastname


ON Persons (LastName);

If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:

CREATE INDEX idx_pname


ON Persons (LastName, FirstName);

DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.

MS Access:

DROP INDEX index_name ON table_name;

MySQL:

ALTER TABLE table_name


DROP INDEX index_name;

Nested Queries in SQL


SQL is used to manage data stored in a relational database. SQL has
the ability of nest queries. A nested query is a query within another
query. Nested query allows for more complex and specific data
retrieval.
Nested Query

In SQL, a nested query involves a query that is placed within another query.
Output of the inner query is used by the outer query. A nested query has two
SELECT statements: one for the inner query and another for the outer query.
Syntax of Nested Queries

The basic syntax of a nested query involves placing one query inside of
another query. Inner query or subquery is executed first and returns a set of
values that are then used by the outer query. The syntax for a nested query
is as follows:

SELECT column1, column2, ...


FROM table1
WHERE column1 IN ( SELECT column1
FROM table2
WHERE condition );

Types of Nested Queries in SQL

Subqueries can be either correlated or non-correlated


Non-correlated (or Independent) Nested Queries

Non-correlated (or Independent) Nested Queries : Non-correlated (or


Independent) subqueries are executed independently of the outer query.
Their results are passed to the outer query.

Correlated Nested Queries

Correlated subqueries are executed once for each row of the outer query.
They use values from the outer query to return results.

Execution Order in Independent Nested Queries

In independent nested queries, the execution order is from the innermost


query to the outer query. An outer query won't be executed until its inner
query completes its execution. The outer query uses the result of the inner
query.

Operators Used in Independent Nested Queries


IN Operator

This operator checks if a column value in the outer query's result is present in
the inner query's result. The final result will have rows that satisfy the IN
condition.

NOT IN Operator

This operator checks if a column value in the outer query's result is not
present in the inner query's result. The final result will have rows that satisfy
the NOT IN condition.

ALL Operator

This operator compares a value of the outer query's result with all the values
of the inner query's result and returns the row if it matches all the values.

ANY Operator

This operator compares a value of the outer query's result with all the inner
query's result values and returns the row if there is a match with any value.
Execution Order in Co-related Nested Queries

In correlated nested queries, the inner query uses values from the outer
query, and the execution order is different from that of independent nested
queries.

 First, the outer query selects the first row.


 Inner query uses the value of the selected row. It executes its query
and returns a result set.
 Outer query uses the result set returned by the inner query. It
determines whether the selected row should be included in the final
output.
 Steps 2 and 3 are repeated for each row in the outer query's result set.
 This process can be resource-intensive. It may lead to performance
issues if the query is not optimized properly.
Operators Used in Co-related Nested Queries

In co-related nested queries, the following operators can be used

EXISTS Operator

This operator checks whether a subquery returns any row. If it returns at


least one row. EXISTS operator returns true, and the outer query continues to
execute. If the subquery returns no row, the EXISTS operator returns false,
and the outer query stops execution.

NOT EXISTS Operator

This operator checks whether a subquery returns no rows. If the subquery


returns no row, the NOT EXISTS operator returns true, and the outer query
continues to execute. If the subquery returns at least one row, the NOT
EXISTS operator returns false, and the outer query stops execution.

ANY Operator

This operator compares a value of the outer query's result with one or more
values returned by the inner query. If the comparison is true for any one of
the values returned by the inner query, the row is included in the final result.
ALL Operator

This operator compares a value of the outer query's result with all the values
returned by the inner query. Only if the comparison is true for all the values
returned by the inner query, the row is included in the final result.

These operators are used to create co-related nested queries that depend on
values from the outer query for execution.

Examples

Consider the following sample table to execute nested queries on these.

Table: employees table

emp_i
emp_name dept_id
d

1 John 1

2 Mary 2

3 Bob 1

4 Alice 3

5 Tom 1

Table: departments table

dept_i
dept_name
d

1 Sales

2 Marketing

3 Finance
Table: sales table

sale_id emp_id sale_amt

1 1 1000

2 2 2000

3 3 3000

4 1 4000

5 5 5000

6 3 6000

7 2 7000

Example 1: Find the names of all employees in the Sales department.

Required query
SELECT emp_name
FROM employees
WHERE dept_id IN (SELECT dept_id
FROM departments
WHERE dept_name = 'Sales');
Output
emp_name

John

Bob

Tom
Example 2: Find the names of all employees who have made a sale

Required query
SELECT emp_name
FROM employees
WHERE EXISTS (SELECT emp_id
FROM sales
WHERE employees.emp_id = sales.emp_id);
Output
emp_name

John

Mary

Bob

Alice

Tom

This query selects all employees from the "employees" table where there
exists a sale record in the "sales" table for that employee.

Example 3: Find the names of all employees who have made sales greater
than $1000.
Required query
SELECT emp_name
FROM employees
WHERE emp_id = ALL (SELECT emp_id
FROM sales
WHERE sale_amt > 1000);
Output
emp_name

John
Mary

Bob

Alice

Tom

This query selects all employees from the "employees" table. With the
condition that where their emp_id equals all the emp_ids in the "sales" table
where the sale amount is greater than $1000. Since all employees have
made a sale greater than $1000, all employee names are returned.

SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is
also used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

Types of SQL Commands


There are four types of SQL commands: DDL, DML, DCL, TCL.

1. Data Definition Language (DDL)


o DDL changes the structure of the table like creating a table, deleting a table, altering
a table, etc.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
2. Data Manipulation Language
o DML commands are used to modify the database. It is responsible for all form of
changes in the database.
o 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.

Data Control Language (DCL)

DCL commands are used to grant and take back authority from any database user.

DCL commands include GRANT and REVOKE , which are used to control
access to the database.
i. GRANT
In SQL, the GRANT statement gives users access privileges to the database.
For example,

GRANT SELECT, UPDATE ON Customers TO user1;

This command grants SELECT and UPDATE permissions on


the Customers table to user1 .

ii. REVOKE
In SQL, the REVOKE statement withdraws access privileges given by
the GRANT statement.
Let's look at an example.

REVOKE SELECT ON Customers FROM user1;

Here, the SQL query revokes SELECT permission on the Customers table
from user1 .
Transaction Control Language (TCL)
In SQL, TCL commands manage changes affecting the database.

i. COMMIT
In SQL, the COMMIT command is used for saving the changes made in the
database. For example,

UPDATE Customers
SET country = 'UK'
WHERE customer_id = 4;
COMMIT;

Here, the SQL command updates the country of the customer


with customer_id 4 and commits the transaction.
ii. ROLLBACK
In SQL, ROLLBACK is used to undo the transactions that have not been
saved in the database. For example,

DELETE FROM Orders;


ROLLBACK;

Here, the query deletes all records from the Orders table but then rolls back
the transaction.

SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;
In the above syntax, SAVEPOINT_NAME is the name given to savepoint.

To selectively ROLLBACK a group of statements within a large transaction use the


following command is used.

1. Rollback TO <save_point_name>
Example:
1. DELETE FROM CUSTOMERS WHERE AGE = 15;
2. SAVEPOINT A;
3. DELETE FROM CUSTOMERS WHERE AGE = 35;
4. ROLLBCAK TO A;

You might also like