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

SQL Commands: SR - No. Command & Description

vv

Uploaded by

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

SQL Commands: SR - No. Command & Description

vv

Uploaded by

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

Module-2,3

Module 2:Introduction to Structured Query Language (SQL), Data Definition Language


(DDL), Table definitions and operations – CREATE, DROP, ALTER, INSERT, DELETE,
UPDATE.
Module3 : Structured Query Language (SQL): Basic SQL Structure, examples, Set
operations, Aggregate Functions, nested sub-queries. Views, assertions and triggers.
Structured Query Language
SQL Commands
The standard SQL commands to interact with relational databases are CREATE, ALTER,
DROP, SELECT, INSERT, UPDATE, DELETE. These commands can be classified into the
following groups based on their nature −

DDL - Data Definition Language


Sr.No. Command & Description

1 CREATE
Creates a new table, a view of a table, or other object in the database.

2 ALTER
Modifies an existing database object, such as a table.

3 DROP
Deletes an entire table, a view of a table or other objects in the database.

4. RENAME

To rename old table to a new table.


RENAME <old_tablename> to <new table name>
DML - Data Manipulation Language
Sr.No. Command & Description

1 INSERT
Creates a record.

2 UPDATE
Modifies records.

3 DELETE

7
Deletes records.
DQL-Data Query Language

4 SELECT
Retrieves certain records from one or more tables.

SQL - CREATE Table

Creating a basic table involves naming the table and defining its columns and each
column's data type.
Data types:
 Varchar(size)-Variable length string(can be store letter,number ,special
characters)
 Int-integer
 Float(size,d):Floating point Number,(where size represents digit, d –number
after decimal)
 Double(size,d)-Floating point number(large numbers)
 Boolean-True (result will be non zero)or false(result will be zero)
 Date-Date(YYYY-MM-DD)

The SQL CREATE TABLE statement is used to create a new table.

Basic syntax of CREATE TABLE statement is as follows:

CREATE TABLE table_name

( column1 datatype, column2 datatype, column3 datatype,

.....

columnN datatype,

PRIMARY KEY( one or more columns ));

Example:
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, AGE INT NOT NULL,ADDRESS CHAR (25), SALARY DOUBLE(18, 2),

7
PRIMARY KEY (ID));
or
CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255),Age int,CONSTRAINT PK_Person PRIMARY
KEY (ID,LastName));
or
CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, LastName varchar(255)
NOT NULL, FirstName varchar(255), Age int);

SQL - ALTER Table

The SQL ALTER TABLE command is used to add, delete or modify columns in an
existing table.
You would also use ALTER TABLE command to add and drop various constraints on
an existing table.
The basic syntax of ALTER TABLE to add a new column in an existing table is as
follows:
ALTER TABLE table_name ADD column_name datatype;
Eg: ALTER TABLE CUSTOMERS ADD CITY CHAR(20);

The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as


follows:
ALTER TABLE table_name DROP COLUMN column_name;

The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a
table is as follows:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;

The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a
table is as follows:
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;

The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is
as follows:
ALTER TABLE TableName ADD PRIMARY KEY (ColumnName);
or
ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID);

The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a
table is as follows:

ALTER TABLE table_name DROP CONSTRAINT Primary Key;


or
ALTER TABLE Persons DROP CONSTRAINT PK_Person;

7
SQL - DROP Table

The SQL DROP TABLE statement is used to remove a table definition and all data,
constraints, and permission specifications for that table.
Basic syntax of DROP TABLE statement is as follows:

DROP TABLE table_name;

Eg: DROP TABLE CUSTOMERS;

SQL-RENAME TABLE/COLUMN NAME


 RENAME old_table _name To new_table_name ;

RENAME Cars To Car_2023_Details ;

 Rename old column name to new column name

ALTER TABLE table_name RENAME COLUMN old_name TO new_name;

DML

SQL - INSERT Query

The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.
There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)


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

Here, column1, column2,...columnN are the names of the columns in the table into
which you want to insert data.

You may not need to specify the column(s) name in the SQL query if you are adding
values for all the columns of the table. But make sure the order of the values is in the
same order as the columns in the table. The SQL INSERT INTO syntax would be as
follows:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);


Example:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES

(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

SQL - UPDATE Query

The SQL UPDATE Query is used to modify the existing records in a table.
7
You can use WHERE clause with UPDATE query to update selected rows otherwise
all the rows would be affected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name SET column1 = value1, column2 = value2...., columnN =
valueN WHERE [condition];

Eg: UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6;

SQL - DELETE Query

The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise
all the records would be deleted.
The basic syntax of DELETE query with WHERE clause is as follows:
DELETE FROM table_name WHERE [condition];

Eg: DELETE FROM CUSTOMERS WHERE ID = 6;

Now, CUSTOMERS table would not have any record If you want to DELETE all the
records from CUSTOMERS table, you do not need to use WHERE clause and
DELETE query would be as follows:
SQL> DELETE FROM CUSTOMERS;
Drop statement is used to delete the entire table structure. Delete is used just to delete
the data. Table structure will be unaffected.
SQL - SELECT Query

SQL SELECT statement is used to fetch the data from a database table which returns
data in the form of result table. These result tables are called result-sets.
Syntax:
The basic syntax of SELECT statement is as follows:
SELECT column1, column2, columnN FROM table_name;

Here, column1, column2...are the fields of a table whose values you want to fetch.
If you want to fetch all the fields available in the field, then you can use the following
syntax:
SELECT * FROM table_name;
SQL - LIKE Clause

The SQL LIKE clause is used to compare a value to similar values using wildcard
operators. There are two wildcards used in conjunction with the LIKE operator.

The percent sign (%)


The underscore (_)
The percent sign represents zero, one or multiple characters. The underscore represents a
7
single number or character. These symbols can be used in combinations.

Syntax
The basic syntax of % and _ is as follows −

SELECT FROM table_name


WHERE column LIKE 'XXXX%'

or

SELECT FROM table_name


WHERE column LIKE '%XXXX%'

or

SELECT FROM table_name


WHERE column LIKE 'XXXX_'

or

SELECT FROM table_name


WHERE column LIKE '_XXXX'

or

SELECT FROM table_name


WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here, XXXX could
be any numeric or string value.
SQL – ORDER BY Clause

The SQL ORDER BY clause is used to sort the data in ascending or descending
order, based on one or more columns.
Some databases sort the query results in an ascending order by default.

Syntax
The basic syntax of the ORDER BY clause is as follows −

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever
column you are using to sort that column should be in the column-list.

Example
Consider the CUSTOMERS table having the following records −

7
+ + + + + +
| 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 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
The following code block has an example, which would sort the result in an ascending order
by the NAME and the SALARY −

SQL> SELECT * FROM CUSTOMERS

ORDER BY NAME, SALARY; This


would
produce the following result −

+The +following+code+ block has+ an example,


+ which would sort the result in the descending
| ID | NAME | AGE | ADDRESS | SALARY |
order by NAME.
+ + + + + +
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
SQL> SELECT * FROM CUSTOMERS
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3ORDER
| kaushik
BY| NAME
23 | Kota | 2000.00 |
DESC;
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+ + + + + +

7
Module-3 DBMS

This would produce the following result −

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ +- GROUP
SQL + BY+Clause + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 GROUP
The SQL | Indore BY| 10000.00
clause is| used in collaboration with the SELECT statement to
| 6 | Komal | 22 | MP | 4500.00 |
arrange identical data into groups. This GROUP BY clause follows the WHERE
| 2 | Khilan | 25 | Delhi | 1500.00 |
clause| in
| 3 | kaushik 23a| SELECT
Kota | statement
2000.00 |and precedes the ORDER BY clause.
| 5 | Hardik | 27 | Bhopal | 8500.00 |
Syntax
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+ + The basic + syntax
+ of a GROUP
+ BY
+ clause is shown in the following code block. The
GROUP BY clause must follow the conditions in the WHERE clause and must
precede the ORDER BY clause if one is used.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Example
Consider the CUSTOMERS table is having the following records −

+ + + + + +
| 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 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
If you want to know the total amount of the salary on each customer, then the GROUP BY
query would be as follows.

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;

This would produce the following result −

+Now, let +us look at a+table where the CUSTOMERS table has the following records with
| NAME | SUM(SALARY) |
duplicate names −
+ + +
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
19 | 2000.00 |
| kaushik
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
Module-3 DBMS

+ + + + + +

| ID | NAME | AGE | ADDRESS | SALARY |


+ + + + + +

| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |

| 2 | Ramesh | 25 | Delhi | 1500.00 |

| 3 | kaushik | 23 | Kota | 2000.00 |

| 4 | kaushik | 25 | Mumbai | 6500.00 |


| 5 | Hardik | 27 | Bhopal | 8500.00 |

| 6 | Komal | 22 | MP | 4500.00 |

| 7 | Muffy | 24 | Indore | 10000.00 |

+ + + + + +
Now again, if you want to know the total amount of salary on each customer, then the
GROUP BY query would be as follows −

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS

GROUP BY NAME; This


would
produce the following result −

+ + +
| NAME | SUM(SALARY) |
+ + +
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+ + +

SQL - Distinct Keyword


The SQL DISTINCT keyword is used in conjunction with the SELECT statement to
eliminate all the duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While
fetching such records, it makes more sense to fetch only those unique records instead
of fetching duplicate records.

Syntax
The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows −

SELECT DISTINCT column1, column2,. columnN


FROM
19table_name
WHERE [condition]
Module-3 DBMS
Example
Consider the CUSTOMERS table having the following records −

+ + + + + + First,
| ID | NAME | AGE | ADDRESS | SALARY | let us
+ + + + + + see
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | how
| 2 | Khilan | 25 | Delhi | 1500.00 | the
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
following SELECT query returns the duplicate salary records.

SQL> SELECT SALARY FROM CUSTOMERS

ORDER BY SALARY;
This would produce the following result, where the salary (2000) is coming twice which is a
duplicate record from the original table.
+ +
| SALARY |
+ +
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+ +
Now, let us use the DISTINCT keyword with the above SELECT query and then see the
result.

SQL> SELECT DISTINCT SALARY FROM CUSTOMERS

ORDER BY SALARY; This


would
produce the following result where we do not have any duplicate entry.

+ +
| SALARY |
+ + Set
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+ 19 +
Module-3 DBMS
Operations in SQL
SQL supports few Set operations to be performed on table data. These are used to get
meaningful results from data, under different special conditions.
Set operators are used to join the results of two (or more) SELECT statements. The
SET operators available in sql are UNION, UNION ALL, INTERSECT, EXCEPT
(MINUS).

UNION
UNION is used to combine the results of two or more Select statements. However it
will eliminate duplicate rows from its result set.
In case of union, number of columns and datatype must be same in both the tables.

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 19
result table will look like,
Module-3 DBMS

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
19 ALL
UNION
Module-3 DBMS
Select * from Second
The result 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 returns the
records which are common from both SELECT statements.
In case of Intersect the number of columns and datatype must be same.

Example of Intersect
The First table,

ID NAME

1 Abhi

2 Adam

The Second table,

ID NAME

19
Module-3 DBMS
2 Adam

3 Chester

Intersect query will be,


Select * from First
INTERSECT
Select * from SECOND
The result table will look like

ID NAME

2 Adam

EXCEPT (MINUS)
Minus operation combines result of two Select statements and return only those result
which belongs to first set of result.

Example of Minus
The First table,

ID NAME

1 Abhi

2 Adam

The Second table,

ID NAME
19
Module-3 DBMS
2 Adam

3 Chester

EXCEPT query will be,


Select * from First
EXCEPT
Select * from Second
The result table will look like,

ID NAME

1 Abhi

Aggregate Functions in SQL

An aggregate function allows you to perform a calculation on a set of values to return


a single scalar value.
We often use aggregate functions with the GROUP BY and HAVING clauses of
the SELECT statement.
Used to summarize the informations from multiple tuples into single tuple.
The following are the most commonly used

SQL aggregate functions:

COUNT – counts rows in a specified table or view.


1. SUM – calculates the sum of values.
2. AVG – calculates the average of a set of values.
3. MIN – gets the minimum value in a set of values.
4. MAX – gets the maximum value in a set of values.

COUNT( )

The COUNT() function returns the number of rows that matches a specified criteria.
Syntax is
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

COUNT function example :


19To get the number of the products in the products table, you use the COUNT function
Module-3 DBMS
as follows:

Select COUNT (*) FROM products;

SUM ( )

The SUM() function returns the total sum of a numeric column.


Syntax is
SELECT SUM(column_name)
FROM table_name
WHERE condition;

Example for SUM( )

To calculate the sum of units in stock by product category, you use the SUM function
as follows:

SELECT categoryid, SUM(unitsinstock) FROM products;

AVG ( )

The AVG() function returns the average value of a numeric column.


AVG() Syntax is

SELECT AVG(column_name)
FROM table_name
WHERE condition;
To calculate the average units in stock of the products, you use the AVG function as
follows:
SELECT AVG(unitsinstock) FROM products;

19
Module-3 DBMS

MIN ( )

The MIN( ) function returns the smallest value of the selected column.MIN( ) Syntax is

SELECT MIN(column_name)
FROM table_name
WHERE condition;

MIN function example

To get the minimum units in stock of products in the products table, you use the
MIN function as follows:

SELECT MIN(unitsinstock) FROM products;

MAX ( )

The MAX() function returns the largest value of the selected column.
MAX() Syntax is
SELECT MAX(column_name)
FROM table_name
WHERE condition;
MAX function example

To get the maximum units in stock of products in the products table, you use
the MAX function as shown in the following query:

SELECT MAX(unitsinstock) FROM products;

Nested Sub Queries


A Subquery or Inner query or a Nested query is a query within another SQL query
and embedded within the WHERE clause.outer query called main query and inner
query called subquery
Subquery execute first and its output is used to complete the query condition for the
main outer query.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

19There are a few rules that subqueries must follow −


Module-3 DBMS
1. Subqueries must be enclosed within parentheses.
2. We can place the subquery in a number of SQL clauses : where ,having,from,.
3. An ORDER B Y command cannot be used in a subquery, Th e GROU P BY
comman d ca n b e use d to perform the same function as the ORDER BY in a
subquery.
4. Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.

Sub queries with the SELECT Statement


Sub queries are most frequently used with the SELECT statement. The basic syntax
is as follows −

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example
Consider the CUSTOMERS table having the following records −

+ + + + + +

| ID | NAME | AGE | ADDRESS | SALARY |

+ + + + + +

| 1 | Ramesh | 35 | 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 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |

+ + + + + +

19
Now, let us check the following subquery with a SELECT statement.

SQL> SELECT *
FROM CUSTOMERS This
would
WHERE ID IN (SELECT ID

FROM CUSTOMERS

WHERE SALARY > 4500) ;


produce the following result.

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY | Sub
+ + + + + + queries
| 4 | Chaitali | 25 | Mumbai | 6500.00 | with the
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
INSERT Statement
Subqueries also can be used with INSERT statements.
The INSERT statement uses the data returned from the subquery to insert into
another table.
The selected data in the subquery can be modified with any of the character, date or
number functions.

The basic syntax is as follows.

INSERT INTO table_name [ (column1 [, column2 ]) ]


SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
Sub
SQL> INSERT INTO CUSTOMERS_BKP
queries
SELECT * FROM CUSTOMERS
with the
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
UPDATE Statement
The subquery can be used in conjunction with the UPDATE statement.
Either single or multiple columns in a table can be updated when using a subquery
with the UPDATE statement.

22
The basic syntax is as follows.

UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table. The following example updates SALARY by 0.25 times in the
CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.

UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP


+ WHERE
+ AGE + >= +27 ); + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
This would impact two rows and finally CUSTOMERS table would have the following
records.
Sub queries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows.

DELETE FROM TABLE_NAME


[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)

22
[ WHERE) condition];
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the
CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.

SQL> DELETE FROM CUSTOMERS

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP


WHERE AGE >= 27 );
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
This would impact two rows and finally the CUSTOMERS table would have the following
records.

Views
A View is a single table that is derived from other tables.
These other tables can be base tables or previously defined views.
A View does not necessarily exist in physical form; It is considered to be a virtual
table
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, which are kind of virtual tables, allow users to do the following:
 Structure data in a way that users or classes of users find natural or
intuitive.
 Restrict access to the data such that a user can see and (sometimes)
modify exactly what they need and no more.
 Summarize data from various tables which can be used to generate
reports.
Creating Views:

Database views are created using the CREATE VIEW statement


Views can be created from a single table, multiple tables, or another view.
22
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 very similar way as
you use them in normal SQL SELECT query.
Example:
Consider the CUSTOMERS table having the following records:
+ + + + + +

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

+ + + + + +

Now, following is the example to create a view from CUSTOMERS table.


This view would be used to have customer name and age from CUSTOMERS table:
CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM
CUSTOMERS;

Now, you can query CUSTOMERS_VIEW in similar way as you query an actual
table.
Following is the example:
SELECT * FROM CUSTOMERS_VIEW;

This would produce the following result:


+ + +

| name | age |

+ + +
| Ramesh | 32 |

22
| Khilan | 25 |

| kaushik | 23 |

| Chaitali | 25 |

| Hardik | 27 |

+ + +

Updating Views:

Database views can be updated using the UPDATE statement


The basic syntax for update a view is as follows:
UPDATE view_name SET ColumnName= value WHERE [condition];

Following is the example:

UPDATE CUSTOMERS_VIEW SET age=40 WHERE Name=”Ramesh”;


Now this would ultimately update the base table CUSTOMERS and same would reflect in the
view itself.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 40 | 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 |
+ + + + + +
Views defined on multiple tables using joins are generally not updatable.
Views defined using grouping and aggregate functions are not updatable.

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 as given below:
DROP VIEW view_name;

Following is an example to drop CUSTOMERS_VIEW from CUSTOMERS table:


DROP VIEW CUSTOMERS_VIEW;

22
Inline View

It is possible to define a view table in the FROM clause of an SQL query. This is known as
in-line view. In this case, the view is defined within the query itself.

Advantages of Views
Restrict Data Access and/or Simplify Data Access
Simplify Data Manipulation
Import and Export Data
Merge Data

Triggers
Triggers are stored programs, which are automatically executed or fired when some
events occur.
Triggers are, in fact, written to be executed in response to any of the following
events –
1. A database manipulation (DML) statement (DELETE, INSERT,
or UPDATE)
2. A database definition (DDL) statement (CREATE, ALTER, or
DROP).
3. A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event
is associated.

Benefits of Triggers
Triggers can be written for the following purposes −

Generating some derived column values automatically


Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
Creating Triggers
The syntax for creating a trigger is −

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER }

22
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF column_name]

ON table_name

[FOR EACH ROW]

WHEN (condition)
BEGIN

……………

END;

Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER } − This specifies when the trigger will be executed.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF column_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.

Example
To start with, we will be using the CUSTOMERS table.

Select * from customers;

+ + + + + +
| 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 | MP | 4500.00 |
+ + + + + +

22
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −

CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON customers When


the
FOR EACH ROW above
code is
WHEN (NEW.ID > 0)

DECLARE

sal_diff number;

BEGIN

sal_diff := :NEW.salary - :OLD.salary;

dbms_output.put_line('Old salary: ' || :OLD.salary);

dbms_output.put_line('New salary: ' || :NEW.salary);

dbms_output.put_line('Salary difference: ' || sal_diff);

END;

/
executed at the SQL prompt, it produces the following result −

Trigger created. The


following points need to be considered here −
OLD and NEW references are not available for table-level triggers, rather you can
use them for record-level triggers.
If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.

Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −

22
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the CUSTOMERS table, the above create


trigger, display_salary_changes will be fired and it will display the following result −

Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null.
Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE
statement will update an existing record in the table −

UPDATE customers

SET salary = salary + 500


WHERE id = 2;
Old salary: 1500
New salary: 2000
Salary difference: 500
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −

22

You might also like