0% found this document useful (0 votes)
20 views32 pages

SQL UNIT IV

The document provides a comprehensive overview of Structured Query Language (SQL), detailing its history, commands, and functionalities within relational database management systems. It covers various SQL commands such as Data Definition Language (DDL), Data Manipulation Language (DML), and integrity constraints, along with examples of their usage. Additionally, it explains data types, aggregate functions, and the importance of constraints in ensuring data integrity.

Uploaded by

SATYA
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)
20 views32 pages

SQL UNIT IV

The document provides a comprehensive overview of Structured Query Language (SQL), detailing its history, commands, and functionalities within relational database management systems. It covers various SQL commands such as Data Definition Language (DDL), Data Manipulation Language (DML), and integrity constraints, along with examples of their usage. Additionally, it explains data types, aggregate functions, and the importance of constraints in ensuring data integrity.

Uploaded by

SATYA
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/ 32

A.B.N&P.R.

R COLLEGE OF SCIENCE, KOVVUR

DATABASE MANAGEMENT SYSTEM – PAPER VA

SQL-UNIT-IV

Introduction

Structured Query Language(SQL) is a database query language


used for storing and managing data in Relational DBMS. SQL was the
first commercial language introduced for E.F Codd's Relational model of
database. Today almost all RDBMS (MySql, Oracle, Informix, Sybase, MS-
Access) use SQL as the standard database query language. SQL is used
to perform all types of data operations in RDBMS.

SQL is a standard language for accessing and manipulating databases.

What is SQL?

 SQL stands for Structured Query Language


 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards
Institute (ANSI) in 1986, and of the International Organization for
Standardization (ISO) in 1987

What Can SQL do?

 SQL can execute queries against a database


 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

History of SQL Standard

Dr. E. F. Codd published the paper, "A Relational Model of Data for Large
Shared Data Banks", in June 1970 in the Association of Computer
Machinery (ACM) journal, Communications of the ACM. Codd's model is
now accepted as the definitive model for relational database
management systems (RDBMS). The language, Structured English Query
Language (SEQUEL) was developed by IBM Corporation, Inc., to use
Codd's model. SEQUEL later became SQL (still pronounced "sequel"). In
1979, Relational Software, Inc. (now Oracle) introduced the first
commercially available implementation of SQL. Today, SQL is accepted
as the standard RDBMS language.

Commands in SQL

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 five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
Note:

DDL  Data Definition Language

DML Data Manipulation Language

DCL Data Control Language

TCL Transaction Control Language

DQL Data Query Language

Q) Explain Data Types in SQL?

A) The various data types of SQL are as follows….

Numeric Data Types

NUMBER
This data type is used to declare numeric integer or decimal fields while
creating the table. This syntax of this data type is as follows…
Syntax
NUMBER(L,D)
In the above syntax L represents total length including the sign and
decimal places and D represents the decimal places after the period.
INTEGER
This data type is used to declare numeric integer data items only. It can
also be used as short cut notation as INT. This data type cannot be used
to declare decimal data items.
SMALLINT
Just like INTEGER, but limited to integer values up to six digits. If your
integer values are small, use SMALLINT instead of INT.
DECIMAL
This data type is used to declare float point data items while creating
tables. The syntax is as follows…
Syntax
DECIMAL(L,D)
Character Data Types
CHAR
This data type is used to declare fixed length character data items upto
255 characters.
VARCHAR Or VARCHAR2
This data type is used to declare variable length character data items
upto 2000 characters.

DATE
This data type is used to store date in Julian Date format. The Oracle
data format is DD-MON-YY for example 01-JAN-21.

Q) Explain DDL commands in SQL?

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

Here are some commands that come under DDL:

o CREATE
o ALTER
o TRUNCATE
o RENAME
o DROP

a. CREATE It is used to create a new table in the database.

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

CREATE TABLE EMPLOYEE


(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

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

Syntax:

To add a new column in the table


ALTER TABLE Tablename ADD(New Columnname COLUMN-
definition);

To modify existing column in the table:

ALTER TABLE Tablename MODIFY(Existing Columnname


COLUMN definition....);

EXAMPLE

ALTER TABLE EMPLOYEE ADD(HIREDATE DATE);


ALTER TABLE EMPLOYEE MODIFY (NAME VARCHAR2(30));

c. TRUNCATE: It is used to delete all the rows from the table


permanently and free the space containing the table.

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE EMPLOYEE;

d. RENAME: It is used to change the name of an existing database


object (like Table,Column) to a new name. Renaming a table does not
make it to lose any data is contained within it.

Syntax

RENAME Oldtablename TO Newtablename;

Example

RENAME EMPLOYEE TO EMP;

e. DROP: It is used to delete both the structure and records stored in the
table.

Syntax

DROP TABLE Tablename ;

Example

DROP TABLE EMP;


Q) Explain SELECT and PROJECT Operations?

A) The SELECT operation is used for selecting a subset of the tuples


according to a given selection condition. ... It is used as an expression to
choose tuples which meet the selection condition. Select operator
selects tuples that satisfy a given predicate. In other words, SELECT
operation is used to retrieve horizontal rows or tuples.

EXAMPLES

SELECT * FROM EMP;

SELECT * FROM EMP WHERE SAL>2000;

SELECT * FROM EMP WHERE JOB=’MANAGER’;

SELECT * FROM EMP WHERE COMM IS NULL;

The PROJECT operation selects (or chooses) certain attributes


discarding other attributes. The Project operation is also known as
vertical partitioning since it partitions the relation or table vertically
discarding other columns or attributes. In other words, PROJECT
operation is used to retrieve vertical columns or attributes.

EXAMPLES

SELECT EMPNO,ENAME,JOB,SAL,DEPTNO FROM EMP;

SELECT EMPNO,ENAME,HIREDATE FROM EMP;

Q) Explain Aggregate Functions or Group Functions in SQL?

A) Oracle aggregate functions calculate on a group of rows and return a


single value for each group. We commonly use the aggregate functions
together with the GROUP BY clause. The GROUP BY clause divides the
rows into groups and an aggregate function calculates and returns a
single result for each group. If you use aggregate functions without
a GROUP BY clause, then the aggregate functions apply to all rows of the
queried tables or views. We also use the aggregate functions in
the HAVING clause to filter groups from the output based on the results
of the aggregate functions.
The following are aggregate functions in SQL

COUNT: It is used to count the number of rows in the table.

EXAMPLE
SELECT COUNT(*) FROM EMP;

Output is 14

SUM: It is used to calculate total sum of given column value.

EXAMPLE

SELECT SUM(SAL) FROM EMP;

Output is 29025

MIN: It is used to return the minimum value of the given column name.

EXAMPLE

SELECT MIN(SAL) FROM EMP;

Output is 800

MAX: It is used to return the maximum value of the given column name.

EXAMPLE

SELECT MAX(SAL) FROM EMP;

Output is 5000

AVG: It is used to ruturn the average value of the given column name.

EXAMPLE

SELECT AVG(SAL) FROM EMP;

Output is 2073.21429
Q) Explain Data Manipulation Language commands in SQL?

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

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data


into the row of a table.

Syntax:

INSERT INTO TABLE_NAME


(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);

Or

INSERT INTO TABLE_NAME


VALUES (value1, value2, value3, .... valueN);

For example:

INSERT INTO Book(Book_Id,Author, Subject) VALUES (1001,’Paneerselva


m’, ‘DBMS’);

b. UPDATE: This command is used to update or modify the value of a


column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = val


ueN] [WHERE CONDITION]
For example:

UPDATE BOOK
SET SUBJECT = 'Database Management System Concepts'
WHERE BOOK_Id = 1001;

c. DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];

For example:

DELETE FROM BOOK


WHERE BOOK_Id=1001;
Q) Explain Table Modification Commands in SQL?

A) The ALTER TABLE statement is used to add, delete, or modify columns


in an existing table.

The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.

RENAME COLUMN: It is used to rename a column in the table.

SYNTAX

ALTER TABLE Tablename RENAME COLUMN Old Columnname to New


Columnname;

EXAMPLE

ALTER TABLE EMP RENAME COLUMN HIREDATE TO JOINING_DATE;

DROP COLUMN: It is used to drop the column in the table.

SYNTAX

ALTER TABLE EMP DROP COLUMN Columnname;

EXAMPLE

ALTER TABLE EMP DROP COLUMN COMM;


ADDING CONSTRAINTS

ADDING PRIMARY KEY: It is used to add primary key to the existing


table column name.

SYNTAX

ALTER TABLE Tablename ADD PRIMARY KEY(Columnname);

EXAMPLE

ALTER TABLE EMP ADD PRIMARY KEY(EMPNO);

ADDING FOREIGN KEY: It is used to add foreign key to the existing


table column name.

SYNTAX

ALTER TABLE Tablename ADD FOREIGN KEY(Column name) REFERENCES


PARENT TABLE NAME(Common Column name) ON DELETE CASCADE;

EXAMPLE

ALTER TABLE EMP ADD FOREIGN KEY(DEPTNO) REFERENCES


DEPT(DEPNTO) ON DELETE CASCADE;

DROPPING CONSTRAINTS

DROPPING PRIMARY KEY(S): It is used to drop the primary key or keys.

SYNTAX

ALTER TABLE EMP DROP PRIMAR Y KEY;

EXAMPLE

ALTER TABLE EMP DROP PRIMARY KEY;

DROPPING FOREIGN KEY: It is used to drop the foreign keys.

SYNTAX

ALTER TABLE Tablename DROP CONSTRAINT Constraint Name;

EXAMPLE

ALTER TABLE EMP DROP CONSTRAINT FK_DEPTNO;


Q) Explain Table truncation in SQL?

A) Table truncation command belongs to DDL Command. This command


is used to delete the records of the table permanently. After using this
command we can’t get the records back by using transaction control
language command ROLLBACK also, hence be cautious when using this
command.

SYNTAX

TRUNCATE TABLE Tablename;

EXAMPLE

TRUNCATE TABLE EMP;

Q) Explain Imposition of Constraints or Integrity Constraints in SQL?

A) SQL constraints are used to specify rules for data in a table.

SQL Create Constraints

Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER TABLE
statement.

Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

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.

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 - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific
condition
 DEFAULT - Sets a default value for a column when no value is
specified

SQL NOT NULL Constraint

By default, a column can hold NULL values.

The NOT NULL constraint enforces a column to NOT accept NULL values.

This enforces a field to always contain a value, which means that you
cannot insert a new record, or update a record without adding a value to
this field.

SQL NOT NULL on CREATE TABLE

The following SQL ensures that the "ID", "LastName", and "FirstName"
columns will NOT accept NULL values when the "Persons" table is
created:

Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are different.

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint.

However, you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE

The following SQL creates a UNIQUE constraint on the "ID" column when
the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

To name a UNIQUE constraint, and to define a UNIQUE constraint on


multiple columns, use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table.

Primary keys must contain UNIQUE values, and cannot contain NULL
values.

A table can have only ONE primary key; and in the table, this primary key
can consist of single or multiple columns (fields).
SQL PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int);

To allow naming of a PRIMARY KEY constraint, and for defining a


PRIMARY KEY constraint on multiple columns, use the following SQL
syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName));

Note: In the example above there is only ONE PRIMARY KEY


(PK_Person). However, the VALUE of the primary key is made up of TWO
COLUMNS (ID + LastName. Composite primary keys can be created by
using table level method only.

SQL FOREIGN KEY Constraint

A FOREIGN KEY is a key used to link two tables together.

A FOREIGN KEY is a field (or collection of fields) in one table that refers
to the PRIMARY KEY in another table.

The table containing the foreign key is called the child table, and the
table containing the candidate key is called the referenced or parent
table.

Consider the two tables Persons and Orders.

Notice that the "PersonID" column in the "Orders" table points to the
"PersonID" column in the "Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the


"Orders" table.

The FOREIGN KEY constraint is used to prevent actions that would


destroy links between tables.

The FOREIGN KEY constraint also prevents invalid data from being
inserted into the foreign key column, because it has to be one of the
values contained in the table it points to.

SQL FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "PersonID" column


when the "Orders" table is created:

CREATE TABLE Orders (


OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID) on delete
cascade);

Note: Already we created the table Persons as Parent table.

SQL CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed
in a column.

If you define a CHECK constraint on a single column it allows only certain


values for this column.

If you define a CHECK constraint on a table it can limit the values in


certain columns based on values in other columns in the row.

SQL CHECK on CREATE TABLE

The following SQL creates a CHECK constraint on the "Age" column


when the "Persons" table is created. The CHECK constraint ensures that
the age of a person must be 18, or older:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18));

SQL DEFAULT on CREATE TABLE

The following SQL sets a DEFAULT value for the "City" column when the
"Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Chicago');

Q) Explain Joining Database Tables Or Join Operations in SQL?

A) The ability to combine (join) tables based on common attributes is


perhaps the most important feature in relational databases. A join is
performed when data are retrieved from more than one table at a time.

To join tables, simply list the tables in the from clause of the
SELECT statement. The join condition is generally composed of an
equality comparison between foreign key and the primary key of related
tables. Hence, in the join condition where clause consists of common
attribute used to link tables. The following query is used to join VENDOR
and PRODUCT tables based on the common field V_CODE.

SELECT P_CODE,P_DESC,P_PRICE,V_NAME,V_CONTACT,V_AREACODE,

V_PHONE FROM PRODUCT, VENDOR

WHERE PRODUCT.V_CODE=VENDOR_V_CODE;

Joins are classified into 4 types. They are as follows…

1. Inner Joins
2. Self-Join
3. Outer Joins
4. Cross Join
1. INNER JOINS

Old Style Join

SELECT * FROM EMP,DEPT

WHERE EMP.DEPTNO=DEPT.DEPTNO;

Returns only the rows that meet the join condition in the WHERE
clause(Old Style)Only rows with matching values are selected.

NATURAL JOIN

SELECT * FROM EMP NATURAL JOIN DEPT;

Returns only the rows with matching values in the matching columns.
The matching columns must have the same names and similar data
types.

JOIN…USING CLAUSE

SELECT * FROM EMP JOIN DEPT USING(DEPTNO)

Returns only the rows with matching values in the columns indicated in
the USING clause.

JOIN…ON CLAUSE

SELECT * FROM EMP JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;

Returns only the rows that meet the join condition indicated in the ON
clause.

2. SELF JOIN
A table which joins to itself is called self-join.
Old Style SELF JOIN
SELECT E1.ENAME||’ WORKING UNDER ’||E2.ENAME ”EMPLOYEES AND
THEIR MANAGERS” FROM EMP E1,EMP E2
WHERE E1.MGR=E2.EMPNO

New Style SELF JOIN

SELECT E1.ENAME||’ WORKING UNDER ’||E2.ENAME ”EMPLOYEES AND


THEIR MANAGERS” FROM EMP E1 JOIN EMP E2
ON E1.MGR=E2.EMPNO

3. OUTER JOINS

Old Style OUTER JOIN

SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO(+)=DEPT.DEPTNO;

Returns rows with matching values and includes all rows from the left
table EMP with unmatched values.

New Style OUTER JOINS

LEFT [OUTER] JOIN


SELECT * FROM EMP LEFT JOIN DEPT USING(DEPTNO);
Returns rows with matching values and includes all rows from the left
table EMP with unmatched values.
RIGHT [OUTER] JOIN

SELECT * FROM EMP RIGHT JOIN DEPT USING(DEPTNO);


Returns rows with matching values and includes all rows from the right
table DEPT with unmatched values.
FULL [OUTER] JOIN
SELECT * FROM EMP FULL JOIN DEPT USING(DEPTNO);
Returns rows with matching values and includes all rows from both the
tables EMP & DEPT with unmatched values.
4. CROSS JOIN

Old Style CROSS JOIN

SELECT * FROM EMP,DEPT;

Returns the Cartesian product of EMP and DEPT.

New Style CROSS JOIN

SELECT * FROM EMP CROSS JOIN DEPT;

Returns the Cartesian product of EMP and DEPT.

Q) Explain SET Operations in SQL?

A) SET Operations in SQL


SQL supports few Set operations which can be performed on the table
data. These are used to get meaningful results from data stored in the
table, under different special conditions.
In this tutorial, we will cover 4 different types of SET operations, along
with example:

1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

UNION Operation
UNION is used to combine the results of two or
more SELECT statements. However it will eliminate duplicate rows from
its resultset. In case of union, number of columns and datatype must be
same in both the tables, on which UNION operation is being applied.

Example of UNION

The First table,


ID Name

1 abhi

2 adam

The Second table,

ID Name

2 adam

3 Chester

Union SQL query will be,


SELECT * FROM First
UNION
SELECT * FROM Second;
The result set table will look like,

ID NAME

1 abhi

2 adam

3 Chester
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.

Example of Union All

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester
Union All query will be like,
SELECT * FROM First
UNION ALL
SELECT * FROM Second;
The result set table will look like,

ID NAME

1 abhi

2 adam

2 adam

3 Chester

INTERSECT
Intersect operation is used to combine two SELECT statements, but it
only retuns the records which are common from
both SELECT statements. In case of Intersect the number of columns and
datatype must be same.
NOTE: MySQL does not support INTERSECT operator.
Example of Intersect
The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Intersect query will be,


SELECT * FROM First
INTERSECT
SELECT * FROM Second;

The result set table will look like


ID NAME

2 adam

MINUS
The Minus operation combines results of two SELECT statements and
return only those in the final result, which belongs to the first set of the
result.

Example of Minus
The First table,

ID NAME

1 abhi

2 adam
The Second table,

ID NAME

2 adam

3 Chester

Minus query will be,


SELECT * FROM First
MINUS
SELECT * FROM Second;

The result set table will look like,

ID NAME

1 abhi

Q) Explain Views or Virtual Table in SQL?

A) A view is nothing more than a SQL statement that is stored in the


database with an associated name. A view is actually a composition of a
table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view
can be created from one or many tables which depends on the written
SQL query to create a view. Views are also called as Virtual Table.

Creating Views

Database views are created using the CREATE VIEW statement. Views
can be created from a single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege
according to the specific implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar
way as you use them in a normal SQL SELECT query.

Example

Consider the CUSTOMERS table having the following records −

ID NAME AGE ADDRESS SALARY


1 Mahesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chahal 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
Following is an example to create a view from the CUSTOMERS table.
This view would be used to have customer name and age from the
CUSTOMERS table.

SQL > CREATE VIEW CUSTOMERS_VIEW AS


SELECT NAME, AGE
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an
actual table. Following is an example for the same.

SQL > SELECT * FROM CUSTOMERS_VIEW;


This would produce the following result.
NAME AGE
Mahesh 32
Khilan 25
Kaushik 23
Chahal 25
Hardik 27
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Mahesh';
This would ultimately update the base table CUSTOMERS and the same
would reflect in the view itself. Now, try to query the base table and the
SELECT statement would produce the following result.
ID NAME AGE ADDRESS SALARY
1 Mahesh 35 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chahal 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00

Inserting Rows into a View

Rows of data can be inserted into a view. The same rules that apply to
the UPDATE command also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have
not included all the NOT NULL columns in this view, otherwise you can
insert rows in a view in a similar way as you insert them in a table.

Deleting Rows into a View

Rows of data can be deleted from a view. The same rules that apply to
the UPDATE and INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.

SQL > DELETE FROM CUSTOMERS_VIEW


WHERE age = 27;
This would ultimately delete a row from the base table CUSTOMERS and
the same would reflect in the view itself. Now, try to query the base
table and the SELECT statement would produce the following result.

ID NAME AGE ADDRESS SALARY


1 Mahesh 35 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chahal 25 Mumbai 6500.00
Dropping Views

Obviously, where you have a view, you need a way to drop the view if it
is no longer needed. The syntax is very simple and is given below −
DROP VIEW Viewname;
Following is an example to drop the CUSTOMERS_VIEW from the
CUSTOMERS table.

DROP VIEW CUSTOMERS_VIEW;

Q) Explain Sub-Queries in SQL?

A) Sub-Queries are used to process the data based on another


processed data. For example consider the following queries.

SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM EMP

WHERE ENAME=’SMITH’;

The above query is used to display the colleagues of the employee


‘SMITH’

SELECT * FROM EMP WHERE HIREDATE=(SELECT MIN(HIREDATE) FROM


EMP)

The above query is used to display the senior employee in the EMP Table
i.e., it displays the details of the employee SMITH.

SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP)

The above query is used to display the employee details who is getting
highest salary in the EMP Table i.e., it displays the details of the
employee KING.

Note: All these above sub-query examples the query which is in


parenthesis executes at first and the output the query is submitted as
input to the outer query and then final result will be displayed.

Characteristics of Sub-Query

 A Sub-Query is a query (Select statement) inside a query.


 A Sub-Query is normally expressed inside parenthesis.
 The first query in the SQL statement is known as the outer query.
 The query inside the SQL statement is known as the inner query.
 Always, inner query is executed at first.
 The output of an inner query is used as the input for the outer
query.
 The entire SQL statement is sometimes referred to as a nested
query.

Sub-Queries with DML Commands

INSERT INTO PROD SELECT * FROM PRODUCT;


The above Sub-Query inserts all rows from the PRODUCT Table into the
PROD Table if both the tables having the same attributes.
UPDATE PRODUCT SET P_PRICE=(SELECT AVG(P_PRICE) FROM
PRODUCT)WHERE V_CODE IN(SELECT V_CODE FROM VENDOR
WHERE V_AREACODE=615);
Updates the product price to the average product price, but only for the
products that are provided by the vendors who have an area code equal
to 615.
DELETE FROM PRODUCT WHERE V_CODE IN(SELECT V_CODE FROM
VENDOR WHERE V_AREACODE=615);
Deletes the PRODUCT table rows that are provided by the vendors with
area code equal to 615.

Sub-Query as Virtual Table

CREATE TABLE PROD AS SELECT * FROM PRODUCT;

The above Sub-Query creates PROD table with PRODUCT table structure
and its data (records).

Q) Explain Embedded SQL?

A) SQL consists of powerful and data retrieval and data manipulation


capabilities, but in the real world, database systems are related to other
systems and programs, and we still need a conventional programming
languages such as VB.NET, C# or COBOL to integrate database systems
with other programs and systems. Web applications & windows-based
GUI system requires access to a database such as MS-Access, SQL Server,
Oracle or DB2, and there is a need to use SQL to manipulate the data in
the database.
Embedded SQL is a term used to refer to SQL statements that are
contained within an application programming languages such as VB.NET,
C#,COBOL or Java. No matter what language we use, if it contains
Embedded SQL statements, it is called as Host Language. We knew that
SQL doesn’t consist of procedural features hence the key differences
between SQL and Procedural Languages as follows…

Run-time mismatch

SQL is a nonprocedural and interpreted language, processing of SQL


statements takes place at Server side where as procedural language or
host language statements process in its own memory space i.e., Client
Side.

Processing mismatch
Conventional programming languages (COBOL, ADA, FORTRAN, PASCAL,
C, C++ & PL/I) process and data element at a time. Even arrays & files
also process the data element by element. Where as in Visual Studio.net
adopted new technologies such as Object oriented extensions that help
the programmer manipulate the data sets in cohesive manner.

Data type mismatch


SQL provides several data types, but some of those data types might not
match data types used in different host languages (for example, date
and varchar2 data types)

Note:

 The SQL statements which are in between EXEC SQL/END-EXEC


keywords are identified as Embedded SQL statements.
 The variables with prefix colon(:) are identified as host language
variables.
 A communication area used to exchange status and error
information between SQL and the host language. This
communication area contains two variables—SQLCODE &
SQLSTATE.

Embedded SQL program is as follows…


#include<sqlca.h>

void main()

EXEC SQL BEGIN DECLARE SECTION;

int CustId,OrderId;

char SalesPerson[20],Status[6];

EXEC SQL END DECLARE SECTION;

printf(‘Enter OrderId:”);

scanf(“%d”,&OrderId);

EXEC SQL

SELECT CustId,SalesPerson,Status FROM ORDERS

WHERE OrderId=:OrderId INTO :CustId,:SalesPerson,:Status;

END-EXEC;

printf(“Customer Id:%d\n”,CustId);

printf(“SalesPerson:%s\n”,SalesPerson);

printf(“Status:%s\n”,Status);

You might also like