0% found this document useful (0 votes)
35 views28 pages

Dbmsss Notes

Uploaded by

jc1177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views28 pages

Dbmsss Notes

Uploaded by

jc1177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT-3

SQL Commands

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.

SQL can perform various tasks like create a table, add data to tables, drop the table, modify
the table, set permission for users.

DDL, DQL, DML, DCL and TCL Commands


The SQL commands are mainly categorized into four categories as:
1. DDL – Data Definition Language
2. DQL - Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL

Ø DDL (Data Definition Language):


DDL or Data Definition Language actually consists of the SQL commands that can be
used to define the database schema. It simply deals with descriptions of the database
schema and is used to create and modify the structure of database objects in the
database.DDL is a set of SQL commands used to create, modify, and delete database
structures but not data. These commands are normally not used by a general user, who
should be accessing the database via an application.
List of DDL commands:
• CREATE: This command is used to create the database or its objects (like table,
index, function, views, store procedure, and triggers).
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example Query:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DO
B DATE);

• DROP: It is used to delete both the structure and record stored in the table.
Syntax:
DROP TABLE table_name;

Examples:
DROP TABLE EMPLOYEE;

DROP DATABASE database_name;


database_name: Name of the database to be deleted.

• ALTER: This is used to alter the structure of the database. ALTER TABLE – ADD
ADD is used to add columns into the existing table. Sometimes we may require to add
additional information, in that case we do not require to create the whole database
again, ADD comes to our rescue.

Syntax:
To add a new column in the table

ALTER TABLE table_name


ADD (Columnname_1 datatype,
Columnname_2 datatype,

Columnname_n datatype);

To modify existing column in the table:

ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

• TRUNCATE: This is used to remove all records from a table, including all
spaces allocated for the records are removed. TRUNCATE statement is a Data
Definition Language (DDL) operation that is used to mark the extents of a table
for deallocation (empty for reuse). The result of this operation quickly removes
all data from a table, typically bypassing a number of integrity enforcing
mechanisms. It was officially introduced in the SQL:2008 standard.
The TRUNCATE TABLE mytable statement is logically (though not physically)
equivalent to the DELETE FROM mytable statement (without a WHERE clause).
Syntax:
TRUNCATE TABLE table_name;
table_name: Name of the table to be truncated.
DATABASE name - student_data

• RENAME: This is used to rename an object existing in the database.

Syntax (Oracle, MySQL, MariaDB):

ALTER TABLE table_name


RENAME TO new_table_name;

Ø DQL (Data Query Language):


DQL statements are used for performing queries on the data within schema objects. The
purpose of the DQL Command is to get some schema relation based on the query passed
to it. We can define DQL as follows it is a component of SQL statement that allows
getting data from the database and imposing order upon it. It includes the SELECT
statement. This command allows getting the data out of the database to perform
operations with it. When a SELECT is fired against a table or tables the result is compiled
into a further temporary table, which is displayed or perhaps received by the program
i.e. a front-end.
DQL is used to fetch the data from the database.
List of DQL Commands:
• SELECT: It is used to retrieve data from the database. Select is the most commonly
used statement in SQL. The SELECT Statement in SQL is used to retrieve or fetch data
from a database. We can fetch either the entire table or according to some specified
rules. The data returned is stored in a result table. This result table is also called
result-set.

Syntax:

1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;

For example:

1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;

Apart from just using the SELECT keyword individually, you can use the following
keywords with the SELECT statement:

o DISTINCT
o ORDER BY

o GROUP BY

o HAVING Clause

o INTO

The ‘SELECT DISTINCT’ Statement

This statement is used to return only different values.

Syntax

SELECT DISTINCT Column1, Column2, ...ColumnN FROM TableName;

SELECT DISTINCT MobNo FROM Emp;

Example

The ‘ORDER BY’ Statement

The ‘ORDER BY’ statement is used to sort the required results in ascending or descending
order. The results are sorted in ascending order by default. Yet, if you wish to get the required
results in descending order, you have to use the DESC keyword.

Syntax

SELECT Column1, Column2, ...ColumnN FROM TableName

ORDER BY Column1, Column2, ... ASC|DESC;

Example

Select all employees from the 'Emp’ table sorted by EmpNo:

SELECT * FROM Emp ORDER BY EmpNo;

-- Select all employees from the 'Emp table sorted by EmpNo in Descending order:

SELECT * FROM Employee_Info ORDER BY EmpNo DESC;

-- Select all employees from the 'Empl’ table sorted by EmpNo and EName:

SELECT * FROM Emp ORDER BY EmpNo, EName;

/* Select all employees from the 'Emp' table sorted bsoEmpNo in Descending order and
Ename in

Ascending order: */

SELECT * FROM Emp ORDER BY EmpNo ASC, Ename DESC


The ‘GROUP BY’ Statement

This ‘GROUP BY’ statement is used with the aggregate functions to group the result-set by
one or more columns.

Syntax

SELECT Column1, Column2,..., ColumnN FROM TableName

WHERE Condition GROUP BY ColumnName(s) ORDER BY ColumnName(s);

Example

To list the number of employees from each city.

SELECT COUNT(EmpNo), City FROM Emp GROUP BY City

The ‘HAVING’ Clause

The ‘HAVING’ clause is used in SQL because the WHERE keyword cannot be used

everywhere.

Syntax

SELECT ColumnName(s) FROM TableName WHERE Condition GROUP BY

ColumnName(s) HAVING Condition ORDER BY ColumnName(s);

Example

To list the number of employees in each city. The employees should be sorted high to low
and only

those cites must be included who have more than 5 employees:*/

SELECT COUNT(EmpNo), City FROM Emp GROUP BY City HAVING COUNT(EmpNo)


> 2 ORDER BY

COUNT(EmpNo) DESC;

The ‘SELECT INTO’ Statement

The ‘SELECT INTO’ statement is used to copy data from one table to another.

Ø DML (Data Manipulation Language):


The SQL commands that deals with the manipulation of data present in the database
belong to DML or Data Manipulation Language and this includes most of the SQL
statements. It is the component of the SQL statement that controls access to data and to
the database. Basically, DCL statements are grouped with DML statements.
List of DML commands:

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.

• INSERT : It is used to insert data into a table.


The INSERT INTO statement of SQL is used to insert a new row in a table. There are two
ways of using INSERT INTO statement for inserting rows:
1. Only values: First method is to specify only the value of data to be inserted
without the column names.

INSERT INTO table_name VALUES (value1, value2, value3,…);


table_name: name of the table.
value1, value2,.. : value of first column, second column,… for the new record
2. Column names and values both: In the second method we will specify both the
columns which we want to fill and their corresponding values as shown below:
INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1,
value2, value3,..);
table_name: name of the table.
column1: name of first column, second column …
value1, value2, value3 : value of first column, second column,… for the new record

Example:

INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

• UPDATE: It is used to update existing data within a table.


The UPDATE statement in SQL is used to update the data of an existing table in
database. We can update single columns as well as multiple columns using UPDATE
statement as per our requirement.
Basic Syntax
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
values of columns needs to be updated.
Example Queries
For example:

UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'

Updating single column: Update the column NAME and set the value to
‘PRATIK’ in all the rows where Age is 20.
UPDATE Student SET NAME = 'PRATIK' WHERE Age = 20;

• DELETE : It is used to delete records from a database table.


The DELETE Statement in SQL is used to delete existing records from a table. We can
delete a single record or multiple records depending on the condition we specify in
the WHERE clause.
Basic Syntax:
DELETE FROM table_name WHERE some_condition;
table_name: name of the table
some_condition: condition to choose particular record.

For example:

1. DELETE FROM javatpoint


2. WHERE Author="Sonoo";

DCL (Data Control Language):


DCL includes commands such as GRANT and REVOKE which mainly deal with the rights,
permissions, and other controls of the database system.
List of DCL commands:
• GRANT: This command gives users access privileges to the database.
Syntax:
GRANT privileges_names ON object TO user;
Parameters Used:
privileges_name: These are the access rights or privileges granted to the user.
Object: It is the name of the database object to which permissions are being granted. In
the case of granting privileges on a table, this would be the table name.
User: It is the name of the user to whom the privileges would be granted.
Privileges:
The privileges that can be granted to the users are listed below along with description:

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USE


R;

1. Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table


named “users” where User Name is Amit, the following GRANT statement should be
executed.
GRANT SELECT ON Users TO'Amit'@'localhost;
2. Granting more than one Privilege to a User in a Table: To grant multiple
Privileges to a user named “Amit” in a table “users”, the following GRANT statement
should be executed.
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost
1. Granting All the Privilege to a User in a Table: To Grant all the privileges to a user
named “Amit” in a table “users”, the following Grant statement should be executed.
GRANT ALL ON Users TO 'Amit'@'localhost;
2. Granting a Privilege to all Users in a Table: To Grant a specific privilege to all the
users in a table “users”, the following Grant statement should be executed.
GRANT SELECT ON Users TO '*'@'localhost;
In the above example the “*” symbol is used to grant select permission to all the users
of the table “users”.

• REVOKE: This command withdraws the user’s access privileges given by using the
GRANT command.
Revoke command withdraw user privileges on database objects if any granted. It
does operations opposite to the Grant command. When a privilege is revoked from
a particular user U, then the privileges granted to all other users by user U will be
revoked.
Syntax:
revoke privilege_name on object_name
from {user_name | public | role_name}
Example:
grant insert,
select on accounts to Ram
By the above command user ram has granted permissions on accounts database object
like he can query or insert into accounts.
revoke insert,
select on accounts from Ram
By the above command user ram’s permissions like query or insert on accounts
database object has been removed.
List of TCL commands:

• COMMIT: Commits a Transaction.


If everything is in order with all statements within a single transaction, all changes
are recorded together in the database is called committed. The COMMIT command
saves all the transactions to the database since the last COMMIT or ROLLBACK
command.

Syntax:
COMMIT;

• ROLLBACK: Rollbacks a transaction in case of any error occurs

ROLLBACK: If any error occurs with any of the SQL grouped statements, all
changes need to be aborted. The process of reversing changes is
called rollback. This command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued.
Syntax:

ROLLBACK;

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

Sets a save point within a transaction. It creates points within the groups of
transactions in which to ROLLBACK. A SAVEPOINT is a point in a transaction in which
you can roll the transaction back to a certain point without rolling back the entire
transaction.
Syntax for Savepoint command:
SAVEPOINT SAVEPOINT_NAME;
This command is used only in the creation of SAVEPOINT among all the transactions.
Sample:
SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.
SQL Constraints

In a database table, we can add rules to a column known as constraints. These rules control
the data that can be stored in a column.

The constraints used in SQL are:

Constraint Description
NOT NULL values cannot be null
UNIQUE values cannot match any older value
PRIMARY KEY used to uniquely identify a row
FOREIGN KEY references a row in another table
CHECK validates condition for new value
DEFAULT set default value if not passed
CREATE INDEX used to speedup the read process

NOT NULL Constraint


The NOT NULL constraint in a column means that the column cannot store NULL values. For
example,

CREATE TABLE Colleges (


college_id INT NOT NULL,
college_code VARCHAR(20) NOT NULL,
college_name VARCHAR(50)
);
Here, the college_id and the college_code columns of the Colleges table won't allow NULL
values.

UNIQUE Constraint

The UNIQUE constraint in a column means that the column must have unique value. For
example,

CREATE TABLE Colleges (


college_id INT NOT NULL UNIQUE,
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);

Here, the value of the college_code column must be unique. Similarly, the value of
college_id must be unique as well as it cannot store NULL values.

PRIMARY KEY Constraint

The PRIMARY KEY constraint is simply a combination of NOT NULL and UNIQUE constraints. It
means that the column value is used to uniquely identify the row. For example,

CREATE TABLE Colleges (


college_id INT PRIMARY KEY,
college_code VARCHAR(20) NOT NULL,
college_name VARCHAR(50)
);

Here, the value of the college_id column is a unique identifier for a row. Similarly, it cannot
store NULL value and must be UNIQUE.

FOREIGN KEY Constraint

The FOREIGN KEY (REFERENCES in some databases) constraint in a column is used to


reference a record that exists in another table. For example,

CREATE TABLE Orders (


order_id INT PRIMARY KEY,
customer_id int REFERENCES Customers(id)
);

In SQL, the FOREIGN KEY constraint is used to create a relationship between two tables. A
foreign key is defined using the FOREIGN KEY and REFERENCES keywords.

Example
-- this table doesn't contain foreign keys
CREATE TABLE Customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100),
age INTEGER
);

-- create another table named Products


-- add foreign key to the customer_id column
-- the foreign key references the id column of the Customers table

CREATE TABLE Products (


customer_id INTEGER ,
name VARCHAR(100),
FOREIGN KEY (customer_id)
REFERENCES Customers(id)
);

Here, the customer_id column in the Products table references the id column in the
Customers table.
Check Constraint
The CHECK constraint checks the condition before allowing values in a table. For example,

CREATE TABLE Orders (


order_id INT PRIMARY KEY,
amount int CHECK (amount >= 100)
);

Here, the value of the amount column must be greater than or equal to 100. If not, the SQL
statement results in an error.

DEFAULT Constraint
The DEFAULT constraint is used to set the default value if we try to store NULL in a column.
For example,

CREATE TABLE College (


college_id INT PRIMARY KEY,
college_code VARCHAR(20),
college_country VARCHAR(20) DEFAULT 'US'
);

Here, the default value of the college_country column is US.

If we try to store the NULL value in the college_country column, its value will be US.

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, ...);

SQL Set Operation

The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union

• The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
• In the union operation, all the number of datatype and columns must be same in both
the tables on which UNION operation is being applied.
• The union operation eliminates the duplicate rows from its resultset.

Syntax

1. SELECT column_name FROM table1


2. UNION
3. SELECT column_name FROM table2;

Example:

The First table

ID NAME
1 Jack
2 Harry
3 Jackson

The Second table

ID NAME
3 Jackson
4 Stephan
5 David

Union SQL query will be:

1. SELECT * FROM First


2. UNION
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David

2. Union All

Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:

1. SELECT column_name FROM table1


2. UNION ALL
3. SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

1. SELECT * FROM First


2. UNION ALL
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David

3. Intersect

• It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must be the same.
• It has no duplicates and it arranges the data in ascending order by default.
Syntax

1. SELECT column_name FROM table1


2. INTERSECT
3. SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

1. SELECT * FROM First


2. INTERSECT
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME
3 Jackson

4. Minus

• It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
• It has no duplicates and data arranged in ascending order by default.

Syntax:

1. SELECT column_name FROM table1


2. MINUS
3. SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

1. SELECT * FROM First


2. MINUS
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME
1 Jack
2 Harry
JOIN

SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them. Different types of Joins are as follows:

• INNER JOIN

• LEFT JOIN

• RIGHT JOIN

• FULL JOIN

• NATURAL JOIN

Consider the two tables below as follows:

Student

StudentCourse
The simplest Join is INNER JOIN.

A. 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.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

Example Queries(INNER JOIN)

This query will show the names and age of students enrolled in different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student


INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

B. LEFT JOIN

This join returns all the rows of the table on the left side of the join and matches rows for the
table on the right side of the join. For the rows for which there is no matching row on the
right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.

Example Queries(LEFT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

C. RIGHT JOIN

RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right
side of the join and matching rows for the table on the left side of the join. For the rows for
which there is no matching row on the left side, the result-set will contain null. RIGHT JOIN
is also known as RIGHT OUTER JOIN.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.
Example Queries(RIGHT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

D. FULL JOIN

FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT
JOIN. The result-set will contain all the rows from both tables. For the rows for which there
is no matching, the result-set will contain NULL values.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.

Example Queries(FULL JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4

Ø Aggregate functions in SQL


In database management an aggregate function is a function where the values of
multiple rows are grouped together as input on certain criteria to form a single value
of more significant meaning.
Various Aggregate Functions
1) Count ()
2) Sum ()
3) Avg ()
4) Min ()
5) Max ()

Example: Table Employee


Id Name Salary
-----------------------
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F Null

Count ():
Count (*): Returns total number of records .i.e. 6.
Count (salary): Return number of Non Null values over the column salary. i.e.5.
Count (Distinct Salary): Return number of distinct Non Null values over the column
salary .i.e. 4
Sum ():
Sum (salary): Sum all Non Null values of Column salary i.e., 310
sum (Distinct salary): Sum of all distinct Non-Null values i.e., 250.

Avg ():
Avg (salary) = Sum (salary) / count (salary) = 310/5
Avg (Distinct salary) = Sum (Distinct salary) / Count (Distinct Salary) = 250/4

Min ():
Min (salary): Minimum value in the salary column except NULL i.e., 40.
Max (salary): Maximum value in the salary i.e., 80.

SQL Views
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 pields from one or more tables present in the
database.
o A view can either have specipic rows based on certain condition or all the rows of
a table.

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.

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_Marks
4. WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of View MarksView:


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;

SQL Subquery
A SQL subquery as the term suggested is a query nested within another query. These
subqueries can be present in the FROM clause, WHERE clause, or the SELECT clause.
Subqueries are a powerful tool for combining data available in two tables into a single result.
An SQL subquery is nothing but a query inside another query. We use a subquery to fetch data
from two tables. A subquery is often also referred to as an inner query, while the statement
containing a subquery is also called an outer query or outer select. We can implement
subqueries with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.

General Rules of Subqueries


There are some rules which are followed while using subqueries. They are:
• A subquery must be enclosed in parentheses.
• Subqueries that return over one row can only be used with multiple value operators
such as the IN operator.
• SQL Server allows you to nest subqueries up to 32 levels.

Subqueries With SELECT Statement


Subqueries are commonly used with the SELECT statement. The basic form is shown below -
(SELECT [DISTINCT] subquery_select_argument
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY aggregate_expression [, aggregate_expression] ...]
[HAVING search_conditions])
Example:
Consider the ‘products’ table having the following records.

Now, let us implement the following SQL subquery with SELECT statement.

This will produce the following result.

Subqueries With FROM Statement


A FROM clause is used to specify the subquery statement in SQL.
Note: The result of the evaluation is stored in a temporary variable.
Example:

The following SQL query fetches the result where quantity in stock from products_bkp table
where the quantity in stock is greater than average quantity in stock
Subqueries With an INSERT statement
Consider the table ‘products_bkp’ with a similar structure to the ‘products’ table.
Now, to copy the complete ‘products’ table into the ‘products_bkp’ table, you can use the SQL
subquery with INSERT statement in the following way.

This will copy the data into the ‘products_bkp’ table.

Subqueries With an UPDATE Statement


You can set a new column value in an UPDATE statement equal to the result returned by a
single row subquery.

Example:
If you want to update the unit price of products_bkp table where the unit price will be greater
than the minimum unit price from the products table, we can use the following SQL query:

This will produce the following result.


Subqueries With the DELETE Statement
We can use the DELETE statement with subqueries to delete the records.

Example:
The following SQL query will delete the data from the products_bkp table where the unit price
is less than the maximum unit price from the table products.

This will produce the following result.

You might also like