Module 4 DBMS
Module 4 DBMS
o SQL stands for Structured Query Language. It is used for storing and managing data in relational database
management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create, read, update and delete
relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their standard
database language.
o SQL allows users to query the database in a number of ways, using English-like statements.
Characteristics of SQL
o SQL is easy to learn.,SQL is used to access data from relational database management systems.
o SQL can execute queries against the database.SQL is used to describe the data.
o SQL is used to define the data in the database and manipulate it when needed.
o SQL is used to create and drop the database and table.SQL is used to create a view, stored procedure,
function in a database.
o SQL allows users to set permissions on tables, procedures, and views.
Command Description
DML commands are used for manipulating the data stored in the table and not the table itself.DML commands are
not auto-committed. It means changes are not permanent to database, they can be rolled back.
Command Description
These commands are to keep a check on other commands and their affect on the database. These commands can
annul changes made by other commands by rolling the data back to its original state. It can also make any
temporary change permanent.
Command Description
Data control language are the commands to grant and take back authority from any database user.
Command Description
Data query language is used to fetch data from tables based on conditions that we can easily apply.
Command Description
DDL
Data Definition Language helps you to define the database structure or schema. Let’s learn about DDL commands
with syntax.
CREATE CREATE statements is used to define the database structure schema:
Syntax:CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
For example:Create database university;Create table students;Create view for_students;
DROP : Drops commands remove tables and databases from RDBMS.
Syntax :DROP TABLE ;
For example:Drop object_typeobject_name;Drop database university;Drop table student;
ALTER : Alters command allows you to alter the structure of the database.
Syntax:To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify an existing column in the table:ALTER TABLE MODIFY(COLUMN DEFINITION....);
For example:Alter table guru99 add subject varchar;
TRUNCATE:This command used to delete all the rows from the table and free the space containing the table.
Syntax:TRUNCATE TABLE table_name;
Example:TRUNCATE table students;
DML
Data Manipulation Language (DML) allows you to modify the database instance by inserting, modifying, and
deleting its data. It is responsible for performing all types of data modification in a database.
There are three basic constructs which allow database program and user to enter data and information are:
Here are some important DML commands in SQL:
• INSERT
• UPDATE
• DELETE
INSERT:This is a statement is a SQL query. This command is used to insert data into the row of a table.
Syntax:INSERT INTO TABLE_NAME(col1, col2, col3,.... col N)VALUES (value1, value2, ….valueN);
Or INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
For example:INSERT INTO students (RollNo, FIrstName, LastName) VALUES ('60', 'Tom', Erichsen');
UPDATE:This command is used to update or modify the value of a column in the table.
Syntax:UPDATEtable_name SET [column_name1= value1,...column_nameN = valueN] [WHERE
CONDITION]
For example:UPDATE students SET FirstName = 'Jhon', LastName= 'Wick' WHERE StudID = 3;
DELETE:This command is used to remove one or more rows from a table.
Syntax:DELETE FROM table_name [WHERE condition];
For example:DELETE FROM students WHERE FirstName = 'Jhon';
DCL
DCL (Data Control Language) includes commands like GRANT and REVOKE, which are useful to give “rights &
permissions.” Other permission controls parameters of the database system.
DCL commands:Commands that come under DCL:
• Grant
• Revoke
Grant: This command is use to give user access privileges to a database.
Syntax:GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
For example:GRANT SELECT ON Users TO'Tom'@'localhost;
Revoke: It is useful to back permissions from the user.
Syntax:REVOKEprivilege_nameONobject_nameFROM {user_name |PUBLIC |role_name}
For example:REVOKE SELECT, UPDATE ON student FROM BCA, MCA;
TCL
Transaction control language or TCL commands deal with the transaction within the database.
Commit:This command is used to save all the transactions to the database.
Syntax: Commit;
For example:DELETE FROM Students WHERERollNo =25;
COMMIT;
Rollback :Rollback command allows you to undo transactions that have not already been saved to the database.
Syntax:ROLLBACK;
Example:DELETE FROM Students WHERE RollNo =25;
SAVEPOINT: This command helps you to sets a save point within a transaction.
Syntax:SAVEPOINT SAVEPOINT_NAME;
DQL
Data Query Language (DQL) is used to fetch the data from the database. It uses only one command:
SELECT:This command helps you to select the attribute based on the condition described by the WHERE clause.
Syntax:SELECT expressions FROM TABLES WHERE conditions;
For example:SELECTFirstName FROM Student WHERE RollNo> 15;
SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is known as relation
and row as tuple.Table is the simple form of data storage. A table is also considered as a convenient representation
of relations.
Employee
ID Int(11) NO PRI
NAME Varchar(20) NO
AGE Int(11) NO
SQL DROP TABLE:A SQL DROP TABLE statement is used to delete a table definition and all data from a
table.This is very important to know that once a table is deleted all the information available in the table is lost
forever, so we have to be very careful when using this command.Syntax :DROP TABLE "table_name";
SQL DELETE TABLE :The DELETE statement is used to delete rows from a table. If you want to remove a
specific row from a table you should use WHERE condition.
DELETE FROM table_name [WHERE condition]; But if you do not specify the WHERE condition it will
remove all the rows from the table.
DELETE FROM table_name;
Difference between DELETE and TRUNCATE statements :There is a slight difference b/w delete and truncate
statement. The DELETE statement only deletes the rows from the table based on the condition defined by
WHERE clause or delete all the rows from the table when condition is not specified.The TRUNCATE statement:
it is used to delete all the rows from the table and free the containing space.
TRUNCATE TABLE employee;
SQL RENAME TABLE :In some situations, database administrators and users want to change the name of the
table in the SQL database because they want to give a more relevant name to the table. Any database user can
easily change the name by using the RENAME TABLE and ALTER TABLE statement in Structured Query
Language.The RENAME TABLE and ALTER TABLE syntax help in changing the name of the table.
RENAME old_table _name To new_table_name ;
RENAME Employee To Coding_Employees ;
ALTER TABLE Student RENAME TO MCA_Student_Details ;
Defining constraints
Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the
type of data that can be stored in a particular column in a table using constraints.
• NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is
specified as NOT NULL then we will not be able to store null in this particular column any more.
• UNIQUE: This constraint when specified with a column, tells that all the values in the column must be
unique. That is, the values in any row of a column must not be repeated.
• PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this
constraint is used to specify a field in a table as primary key.
• FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And
this constraint is used to specify a field as Foreign key.
• CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it
helps to ensure that the value stored in a column meets a specific condition.
• DEFAULT: This constraint specifies a default value for the column when no value is specified by the user.
CREATE TABLE sample_table
(
column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name,
....
);
sample_table: Name of the table to be created.
data_type: Type of data that can be stored in the field.
constraint_name: Name of the constraint. for example- NOT NULL, UNIQUE, PRIMARY KEY etc.
1. NOT NULL –
If we specify a field in a table to be NOT NULL. Then the field will never accept null value. That is, you will be
not allowed to insert a new row in the table without specifying any value to this field.
For example, the below query creates a table Student with the fields ID and NAME as NOT NULL. That is, we
are bound to specify values for these two fields every time we wish to insert a new row.
3. PRIMARY KEY –
Primary Key is a field which uniquely identifies each row in the table. If a field in a table as primary key, then
the field will not be able to contain NULL values as well as all the rows should have unique values for this field.
So, in other words we can say that this is combination of NOT NULL and UNIQUE constraints.
A table can have only one field as primary key. Below query will create a table named Student and specifies the
field ID as primary key.
Foreign Key is a field in a table which uniquely identifies each row of a another table. That is, this field points
to primary key of another table. This usually creates a kind of link between the tables.
Consider the two tables as shown below:
Orders Customers
O_IDORDER_NOC_ID
1 2253 3 C_IDNAME ADDRESS
2 3325 3 1 RAMESH DELHI
3 4521 2 2 SURESH NOIDA
4 8532 1 3 DHARMESHGURGAON
As we can see clearly that the field C_ID in Orders table is the primary key in Customers table, i.e. it uniquely
identifies each row in the Customers table. Therefore, it is a Foreign Key in Orders table.
Syntax:
The SELECT statement is used to select data from a database.The data returned is stored in a result table, called
the result-set.SELECT Syntax :SELECT column1, column2, ...FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select
all the fields available in the table, use the following syntax:
The SELECT DISTINCT statement is used to return only distinct (different) values.Inside a table, a column
often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
The WHERE clause is used to filter records.It is used to extract only those records that fulfill a specified
condition.
Operator Description
Logical operators are used to specify conditions in the structured query language (SQL) statement.
They are also used to serve as conjunctions for multiple conditions in a statement.
ALL − It is used to compare a value with every value in a list or returned by a query. Must be preceded
by =, !=, >, < ,<=, or >= evaluates.
For example,select * from emp where salary>= ALL(1500,4000);
AND − Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE;
otherwise returns UNKNOWN.
example,select * from emp where job=’manager’ AND deptno=20;
OR − Return TRUE if either component condition is TRUE. Return FALSE if both are FALSE.
Otherwise, return UNKNOWN.
For example,select * from emp where job=’manager’ OR deptno=20;
IN − It is equivalent to any test. Equivalent to = ANY, The In operator is used to compare a value to a list
of literal values that have been specified.
For example,select * from emp where ename IN (‘bhanu’,’ward’);
NOT − Returns TRUE if the condition is FALSE. Returns FALSE, if it is TRUE. If it is UNKNOWN, it
remains UNKNOWN.
For example,select * from emp where NOT (job is NULL)
select * from emp where NOT(salary between 2000 AND 5000);
BETWEEN − It is used to define range limits.
For example,If we want to find all employees whose age is in between 40 and 50 the query is as follows
SQL Functions
SQL functions are similar to SQL operators in that both manipulate data items and both return a result. SQL
functions differ from SQL operators in the format in which they appear with their arguments. The SQL function
format enables functions to operate with zero, one, or more arguments.function(argument1, argument2, ...)
Aggregate functions:
These functions are used to do operations from the values of the column and a single value is returned.
1. AVG()
2. COUNT()
3. FIRST()
4. LAST()
5. MAX()
6. MIN()
7. SUM()
Students-Table
AVG(): It returns average value after calculating from values in a numeric column.
Syntax:SELECT AVG(column_name) FROM table_name;
Queries:Computing average marks of students.
SELECT AVG(MARKS) AS AvgMarks FROM Students;
Output: AvgMarks
80
COUNT(): It is used to count the number of rows returned in a SELECT statement. It can’t be used in MS
ACCESS.Syntax:SELECT COUNT(column_name) FROM table_name;
Queries:Computing total number of students.
SELECT COUNT(*) AS NumStudents FROM Stuents;
Output: NumStudents
5
FIRST(): The FIRST() function returns the first value of the selected column.
Syntax:SELECT FIRST(column_name) FROM table_name;
Queries:Fetching marks of first student from the Students table.
SELECT FIRST(MARKS) AS MarksFirst FROM Students;
Output: MarksFirst
90
LAST(): The LAST() function returns the last value of the selected column. It can be used only in MS
ACCESS.Syntax:SELECT LAST(column_name) FROM table_name;
Queries:Fetching marks of last student from the Students table.
SELECT LAST(MARKS) AS MarksLast FROM Students;
Output: MarksLast
82
MAX(): The MAX() function returns the maximum value of the selected column.
Syntax:ELECT MAX(column_name) FROM table_name;
Queries:Fetching maximum marks among students from the Students table.
SELECT MAX(MARKS) AS MaxMarks FROM Students;
Output: MaxMarks
95
MIN(): The MIN() function returns the minimum value of the selected column.
Syntax:SELECT MIN(column_name) FROM table_name;
Queries:Fetching minimum marks among students from the Students table.
SELECT MIN(MARKS) AS MinMarks FROM Students;
Output: MinMarks
50
SUM(): The SUM() function returns the sum of all the values of the selected column.
Syntax:SELECT SUM(column_name) FROM table_name;
Queries:Fetching summation of total marks among students from the Students table.
SELECT SUM(MARKS) AS TotalMarks FROM Students;
Output: TotalMarks
400
SELECT LOWER(‘GEEKSFORGEEKS’) AS
LOWER() Returns the argument “LowerName1”,LOWER(‘Geeks For Geeks’) AS
3. /LCASE() in lowercase “LowerName2” ;
Numeric Functions :
The number functions are those functions that accept numeric values and after performing the required
operations, return numeric values. Some useful numeric functions are being discussed below :
4. SIGN() This function returns sign of a given number. SELECT SIGN(-15) “Sign” ;
CURDATE()/
CURRENT_DATE()/
1 CURRENT_DATE Returns the current date. SELECT CURDATE() ;
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
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.
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.
SELECT * FROM First INTERSECTSELECT * FROM Second;
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.
Subquery
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the
WHERE clause.A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
• You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-
row operator, such as IN, ANY, or ALL.
• A subquery is also called an inner query or inner select, while the statement containing a subquery is also
called an outer query or outer select.
• The inner query executes first before its parent query so that the results of an inner query can be passed to
the outer query.
You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to perform the following tasks:
A correlated subquery is evaluated once for each row processed by the parent statement. The parent statement
can be a SELECT, UPDATE, or DELETE statement.
SELECT column1, column2, ....FROM table1 outer WHERE column1 operator (SELECT column1, column2
FROM table2 WHERE expr1 = outer.expr2);
A correlated subquery is one way of reading every row in a table and comparing values in each row against
related data. It is used whenever a subquery must return a different result or set of results for each candidate row
considered by the main query. In other words, you can use a correlated subquery to answer a multipart question
whose answer depends on the value in each row processed by the parent statement.
Nested Subqueries Versus Correlated Subqueries :
With a normal nested subquery, the inner SELECT query runs first and executes once, returning values to be
used by the main query. A correlated subquery, however, executes once for each candidate row considered by
the outer query. In other words, the inner query is driven by the outer query.
SQL group by
In SQL, The Group By statement is used for organizing similar data into groups. The data is further organized
with the help of equivalent function. It means, if different rows in a precise column have the same values, it will
arrange those rows in a group.
o The SELECT statement is used with the GROUP BY clause in the SQL query.
o WHERE clause is placed before the GROUP BY clause in SQL.
o ORDER BY clause is placed after the GROUP BY clause in SQL.
Syntax:
SELECT column1, function_name(column2) FROM table_name WHERE condition
GROUP BY column1, column2 ORDER BY column1, column2;
function_name: Table name.
Condition: which we used.
Group By single column: Group By single column is used to place all the rows with the same value. These
values are of that specified column in one group. It signifies that all rows will put an equal amount through a
single column, which is of one appropriate column in one group.
Consider the below query: SELECT SUBJECT, YEAR, Count (*) FROM Student
HAVING Clause
WHERE clause is used for deciding purpose. It is used to place conditions on the columns to determine the part of
the last result-set of the group. Here, we are not required to use the combined functions like COUNT (), SUM
(), etc. with the WHERE clause. After that, we need to use a HAVING clause.
Example:
SELECT NAME, SUM(SALARY) FROM Employee GROUP BY NAME HAVING SUM(SALARY)>23000;
The GROUP BY Clause is used to group the rows, which have the same values.The SELECT statement
in SQL is used with the GROUP BY clause.In the Group BY clause, the SELECT statement can
use constants, aggregate functions, expressions, and column names.The GROUP BY Clause is called when the
HAVING clause is used to reduce the results.
Before writing the queries for sorting the records, let us understand the syntax.
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or more
tables".The SQL JOIN clause takes records from two or more tables in a database and combines it together.
1. inner join,
2. left outer join,
3. right outer join,
4. full outer join, and
5. cross join.
In the process of joining, rows of both tables are combined in a single table.
Why SQL JOIN is used?
If you want to access more than one table through a select statement.
If you want to combine two or more table then SQL JOIN statement is used .it combines rows of that tables in one
table and one can retrieve the information by a SELECT statement.
The joining of two or more tables is based on common field between them.
SQL INNER JOIN also known as simple join is the most common type of join.
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
SQL INNER JOIN Keyword The INNER JOIN keyword selects records that have matching values in both
tables.
The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right
table (table2). The result is 0 records from the right side, if there is no match.
Tip: FULL OUTER JOIN and FULL JOIN are the same.
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of
other values.
ANY means that the condition will be true if the operation is true for any of the values in the range.
ANY Syntax
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
ALL means that the condition will be true only if the operation is true for all values in the range.
ALL Syntax With SELECT
SELECT ALL column_name(s)FROM table_name WHERE condition;
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Exists
The EXISTS operator in MySQL is a type of Boolean operator which returns the true or false result. It is used in
combination with a subquery and checks the existence of data in a subquery. It means if a subquery returns any
record, this operator returns true. Otherwise, it will return false. The true value is always represented numeric
value 1, and the false value represents 0. We can use it with SELECT, UPDATE, DELETE, INSERT statement.
Syntax
SELECT col_names FROM tab_name WHERE [NOT] EXISTS (SELECT col_names FROM tab_name
WHERE condition);
The NOT operator is used to negates the EXISTS operator. It returns true when the subquery does not return any
row. Otherwise, it returns false.
Generally, the EXISTS query begins with SELECT *, but it can start with the SELECT column, SELECT
a_constant, or anything in the subquery.
SQL Views
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in the
database. We can create a view by selecting fields from one or more tables present in the database. A View can
either have all the rows of a table or specific rows based on certain condition.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a single table,
multiple tables or another view.
CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column1, column2, ...FROM table_name
WHERE condition;
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met,
then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER
BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables then we will not be
allowed to update the view.
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.
Syntax:
REATE OR REPLACE VIEW view_name AS SELECT column1,coulmn2,..FROM table_name
WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this as:
*******************************************