DBMS-Unit3
DBMS-Unit3
What is SQL?
SQL was initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce after
learning about the relational model from Edgar F. Codd in the early 1970s.
It is used in programming and managing data held in relational database management systems
such as MySql, MS SQL Server, oracle Sybase, etc as a medium (instructions) for accessing and
interacting with data.
It enables performing several operations such as creating, deleting, modifying, and fetching
entries in the database and some other advanced statistical, arithmetic, and mathematical
operations.
This database language is mainly designed for maintaining the data in relational database
management systems. It is a special tool used by data professionals for handling structured data
(data that is stored in the form of tables).
It is also designed for stream processing in RDBMS. You can easily create and manipulate the
database, access and modify the table rows and columns, etc. It is used in relational database
management systems such as MySql, MS SQL Server, Oracle Sybase, etc as a medium
(instructions) for accessing and interacting with data.
CREATE
CREATE TABLE table_name( column1 datatype, column2 datatype, .... columnN datatype);
This creates a new table with the name 'table_name' in our database. It will have N columns for
each of the same datatypes as mentioned adjacent to it in the create syntax.
DESC(DESCRIBE) command is used to retrieve the structure of a table. It may confirm that the
table is created.
ALTER: This command changes the structure of a table in a database. We can add a new
column in a table and change the data type and size of a column.
Syntax: ALTER table table_name ADD column_name COLUMN definition;
ALTER table table_name MODIFY(column_definition);
Example: ALTER TABLE Student ADD ( Ph_number INTEGER(12));
In the above example, we added a new column in the existing table student.
In the above example, we changed the size of the City from 30 to 50.
RENAME: This command changes the name of an existing table in a database. For this purpose,
we use ALTER command.
In the above example, first, we use the TRUNCATE command, which deletes all rows from the
Student_details table. When we try to retrieve the table details, it shows a message ‘EMPTY set’.
After that, we use the DROP command, which completely deletes the table Student_details from
the database. So when we try to retrieve the table details again, it shows the message
‘Student_details’ doesn’t exist in the database.
Data Manipulation Language
DML is used for inserting, deleting, and updating data in a database. It is used to retrieve and
manipulate data in a relational database. It includes INSERT, UPDATE, and DELETE. Let's
discuss these commands one at a time.
INSERT
Insert statement is used to insert data in a SQL table. Using the Insert query, we can add one or
more rows to the table. Following is the syntax of the MySQL INSERT Statement.
UPDATE: This statement updates the values of a column in a table. To use this, the
WHERE condition is necessary.
Syntax: UPDATE table_name SET [column 1= value 1 , column n=value n] WHERE condition;
Example: UPDATE Student SET Name='Mahima' WHERE Roll_number=03;
DELETE: This command removes a particular row from a table. Note that
the WHERE condition is necessary to perform the delete operation.
One can fetch either the entire table or some data according to specified rules. The data returned
is stored in a result table. With the SELECT clause of a SELECT command statement, we
specify the columns that we want to be displayed in the query result and, optionally, which
column headings we prefer to see above the result table.
Syntax: SELECT * FROM table_name WHERE condition;
SELECT * FROM table_name;
Example: SELECT * FROM Student;
It provides the administrators, to remove and set database permissions to desired users as needed.
These commands are employed to grant, remove and deny permissions to users for retrieving and
manipulating a database. There are two relevant commands under this category: grant and
revoke.
GRANT
GRANT is a command used to provide access or privileges on the database objects to the users.
SYNTAX
REVOKE
Once you have granted privileges, you may need to revoke some or all of these privileges. To do
this, you can run a revoke command. You can revoke any combination of SELECT, INSERT,
UPDATE, DELETE, REFERENCES, ALTER, or ALL.
Object is the name of the database object that you are revoking privileges for. In the case of
revoking privileges on a table, this would be the table name. Username of the user that will have
these privileges revoked.
COMMIT: It's a SQL command used in the transaction tables or database to make the
current transaction or database statement permanent. It shows the successful completion
of a transaction. If we have successfully executed the transaction statement or a simple
database query, we want to make the changes permanent. We need to perform the commit
command to save the changes, and these changes become permanent for all users.
Syntax: COMMIT;
Example: INSERT INTO Student_details VALUES(02,’Rajat’,21,’Delhi’,9874008);
COMMIT;
ROLLBACK: Undoes any changes made to the database. ROLLBACK is the SQL
command that is used for reverting changes performed by a transaction. When a
ROLLBACK command is issued it reverts all the changes since the last COMMIT or
ROLLBACK.
Syntax: ROLLBACK;
Example: DELETE FROM Student_details WHERE Roll_number=4;
ROLLBACK;
SAVEPOINT: This command creates a point in your transaction to which you can roll
back. It is a command in SQL that is used with the rollback command. It is a command in
Transaction Control Language that is used to mark the transaction in a table.
SYNTAX
SAVEPOINT some_name;
The set operators work on complete rows of the queries, so the results of the queries must have
the same column name, same column order and the types of columns must be compatible.
Syntax:
• SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION ALL:
• The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL.
Syntax:
• SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2
INTERSECT:
The SQL INTERSECT operator is used to return the results of 2 or more SELECT statements.
The INTERSECT clause in SQL is used to combine two SELECT statements but the dataset
returned by the INTERSECT statement will be the intersection of the data sets of the two
SELECT statements.
Syntax:
SELECT column1 , column2 ….FROM table_names
INTERSECT
SELECT column1 , column2 ….FROM table_names
EXCEPT:
• EXCEPT is a set operator in SQL that returns the distinct rows that are present in the
result set of the first query but not in the result set of the second query.
• It is also known as the set difference operator. EXCEPT is used in conjunction with
the SELECT statement to compare the result sets of two or more queries.
Illustration:
• Table T1 includes data 1, 2, and 3.
• When we execute the EXCEPT query on these tables, we will get 1, which is unique data
from the T1, and it will not found in the T2.
Aggregate Functions in SQL
The aggregate functions are used to perform the calculation based on multiple rows and
return a single value according to the given query. All these aggregate functions are used
with a SELECT statement. It is also used to summarize the data.
• Syntax −
SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>
Count ():
• COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
• COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax: COUNT(*) or COUNT( [ALL|DISTINCT] expression )
Examples:
Count() Function with GROUP BY Clause
We can also use the count() function with the GROUP BY clause that returns the count of the
element in each group. For example, the following statement returns the number of employee in
each city:
Examples:
AVG ( ):
The AVG() aggregate function uses the name of the column as an argument and returns the
average of all the non NULL values in that column. It works only on numeric fields.When
applied to columns containing both non-numeric (ex - strings) and numeric values, only numeric
values are considered. If no numeric values are present, the function returns 0.
Syntax : AVG () or AVG ( [ALL|DISTINCT] expression )
Example:
You can take average of various records set using GROUP BY clause. Following example will
take average all the records related to a single person and you will have average typed pages by
every person.
Query: SQL> SELECT name, AVG(daily_typing_pages) FROM employee_tbl GROUP BY
name;
MIN ( ):
The MIN() function takes the name of the column as an argument and returns the minimum
value present in the column. MIN() returns NULL when no row is selected.
Syntax : MIN() or MIN( [ALL|DISTINCT] expression )
Example:
SQL> SELECT MIN(daily_typing_pages) FROM employee_tbl;
You can find all the records with minimum value for each name using GROUP BY clause as
follows −
SQL> SELECT id, name, work_date, MIN(daily_typing_pages) FROM employee_tbl GROUP
BY name;
You can use MIN Function along with MAX function to find out minimum value as well. Try
out the following example −
SQL> SELECT MIN(daily_typing_pages) least,MAX(daily_typing_pages) max FROM
employee_tbl;
MAX ( ):
The MAX() function takes the name of the column as an argument and returns the maximum
value present in the column. MAX() returns NULL when no row is selected.
Examples:
SQL> SELECT MAX(daily_typing_pages) FROM employee_tbl;
You can find all the records with maximum value for each name using GROUP BY clause as
follows −
SQL> SELECT id, name, MAX(daily_typing_pages) FROM employee_tbl GROUP BY name;
The ALL operator compares a value of the outer query's result with all the values of the inner
query's result and returns the row if it matches all the values.
The ANY operator compares a value of the outer query's result with all the inner query's result
values and returns the row if there is a match with any value.
Example
Consider the CUSTOMERS table having the following records −
Sql> select * from customers where id in (select id from customers where salary > 4500);
Subqueries with the 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.
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.
Sql> insert into customers_bkp select * from customers where id in (select id from customers);
Here, NOT NULL signifies that column should always accept an explicit value of the given data
type. There are two columns where we did not use NOT NULL, which means these columns
could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
IS NOT NULL Query
Now, let us try to retrieve the records present in the table that are not null using the IS NOT
NULL operator −
Sql> select id, name, age, address, salary from customers where salary is not null;
IS NULL Query
Let us try to retrieve the records present in the table that are null using the IS
NULL operator −
Sql> select id, name, age, address, salary from customer where salary is null;
Example
Assume the previously created table and let us try to update the NULL value(s) in the present in
the table using the UPDATE statement as shown below −
Sql> update customers set salary = 9000 where salary is null;
Triggers in SQL
A SQL trigger is a database object which fires when an event occurs in a database. For example,
a trigger can be set on a record insert in a database table.
Types of Triggers:
DML Triggers: These triggers fire in response to data manipulation language (DML) statements
like INSERT, UPDATE, or DELETE.
After Triggers: These triggers execute after the database has processed a specified event (such
as an INSERT, UPDATE, or DELETE statement). AFTER triggers are commonly used to
perform additional processing or auditing tasks after a data modification has occurred.
Instead Triggers: These triggers are used for views and fire instead of the DML statement
(INSERT, UPDATE, DELETE) on the view.
DDL Triggers: These triggers fire in response to data definition language (DDL) statements like
CREATE, ALTER, or DROP.
LOGON Triggers: These triggers fire when a user logs into the database.
LOGOFF Triggers: These triggers fire when a user logs out of the database.
Query 1:
CREATE TABLE student(Id integer PRIMARY KEY, first_name varchar(50), last_name
varchar(50), full_name varchar(50));
Here we will create a trigger to fill in the full name by concatenating the first and last names. So
while inserting the values, we will only feed the first name and last name, and we will expect the
trigger to automatically update each row with an additional column attribute bearing the full
name.
Query 2:
create trigger student_name after INSERT on student for each row BEGIN UPDATE student
set full_name = first_name || ' ' || last_name;
END;
Here we can understand from the trigger query we have set a trigger after an insert is made to the
table student. Once the insert is done, this procedure will be fired, which will run an update
command to update the students' full names.
Here we have inserted five students’ data, and since we have a trigger created in our system to
update the full_name, we are expecting the full name to be non-empty if we run a select query on
this table.
Here we can see since we had an update statement in the trigger procedure in query 2, the full
names are automatically updated immediately after the inserts are done.
Active Databases:
An active Database is a database consisting of a set of triggers. These databases are very
difficult to be maintained because of the complexity that arises in understanding the effect of
these triggers. In such database, DBMS initially verifies whether the particular trigger
specified in the statement that modifies the database is activated or not, prior to executing the
statement. If the trigger is active then DBMS executes the condition part and then executes the
action part only if the specified condition is evaluated to true. It is possible to activate more
than one trigger within a single statement. In such situation, DBMS processes each of the
trigger randomly. The execution of an action part of a trigger may either activate other triggers
or the same trigger that Initialized this action. Such types of trigger that activates itself is called
as ‘recursive trigger’.