Unit 4 & 5 Notes - SQL
Unit 4 & 5 Notes - SQL
Unit 4: RELATIONAL DATABASE LANGUAGE (Introduction to SQL, Features of SQL, SQL Languages, DDL commands- Create,
Add, Drop, Constraints in SQL, DML Commands – Insert, Delete, Update)
Unit 5: DATA QUERY LANGUAGE (Where clause, Order by, Group by, DCL commands – Grant, Revoke, TCL Commands – Commit,
Roll Back, Savepoint, Aggregate Functions, Relational Algebra)
INTRODUCTION
Most of the problems faced at the time of implementation of any system are outcome of a poor database design. In many
cases it happens that system has to be continuously modified in multiple respects due to changing requirements of users.
It is very important that a proper planning has to be done.
A relation in a relational database is based on a relational schema, which consists of number of attributes.
A relational database is made up of a number of relations and corresponding relational database schema.
The goal of a relational database design is to generate a set of relation schema that allows us to store information without
unnecessary redundancy and also to retrieve information easily.
One approach to design schemas that are in an appropriate normal form. The normal forms are used to ensure that various
types of anomalies and inconsistencies are not introduced into the database.
WHAT IS RDBMS?
RDBMS stands for Relational Database Management System. RDBMS data is structured in database tables, fields and
records. Each RDBMS table consists of database table rows. Each database table row consists of one or more database
table fields.
RDBMS store the data into collection of tables, which might be related by common fields (database table columns).
RDBMS also provide relational operators to manipulate the data stored into the database tables. Most RDBMS use sql as
database querylanguage.The most popular RDBMS are MS SQL Server, DB2, Oracle and MySQL.
The relational model is an example of record-based model. Record based models are so named because the database is
structured in fixed format records of several types. Each table contains records of a particular type. Each record type
defines a fixed number of fields, or attributes. The columns of the table correspond to the attributes of the record types.
AIGS
Page 1
STRUCTURED QUERY LANGUAGE
The relational data model is the most widely used data model, and a vast majority of current database systems are based
on the relational model.
The relational model was designed by the IBM research scientist and mathematician, Dr.E.F.Cod. The relational model
originated from a paper authored by Dr.codd entitled “A Relational Model of Data for Large Shared Data Banks”,
written in 1970. This paper included the following concepts that apply to database management systems for relational
databases.
The relation is the only data structure used in the relational data model to represent both entities and relationships between them.
Rows of the relation are referred to as tuples of the relation and columns are its attributes. Each attribute of the column are drawn
from the set of values known as domain. The domain of an attribute contains the set of values that the attribute may assume.
From the historical perspective, the relational data model is relatively new .The first database systems were based on either network or
hierarchical models .The relational data model has established itself as the primary data model for commercial data processing
applications. Its success in this domain has led to its applications outside data processing in systems for computer aided design and
other environments.
A DBMS has to be persistent, that is it should be accessible when the program created the data ceases to exist or even the application
that created the data restarted. A DBMS also has to provide some uniform methods independent of a specific application for
accessing the information that is stored. RDBMS is a Relational Data Base Management System Relational DBMS.
This adds the additional condition that the system supports a tabular structure for the data, with enforced relationships between the
tables. This excludes the databases that don't support a tabular structure or don't enforce relationships between tables. You
can say DBMS does not impose any constraints or security with regard to data manipulation it is user or the programmer responsibility
to ensure the ACID PROPERTY of the database whereas the RDBMS is more with this regard because RDBMS define the integrity
constraint for the purpose of holding ACID PROPERTY.
The DBMS interfaces with application programs so that the data contained in the database can be used by multiple
applications and users. The DBMS allows these users to access and manipulate the data contained in the database in a
convenient and effective manner. In addition the DBMS exerts centralized control of the database, prevents unauthorized
AIGS
Page 2
STRUCTURED QUERY LANGUAGE
users from accessing the data and ensures privacy of data In this chapter we study the query language : Structured Query
Language (SQL) which uses a combination of Relational algebra and Relational calculus.It is a data sub language used to
organize, manage and retrieve data fromrelational database, which is managed by Relational Database Management
System (RDBMS).
Vendors of DBMS like Oracle, IBM, DB2, Sybase, and Ingress use SQL as programming language for their database.SQL
originated with the system R project in 1974 at IBM's San Jose ResearchCentre.Original version of SQL was SEQUEL
which was an Application Program Interface (API) to the system R project.
The predecessor of SEQUEL was named SQUARE.SQL-92 is the current standard and is the current version. The SQL language can be used
in two ways
⯌ Interactively or
⯌ Embedded inside another program
The SQL is used interactively to directly operate a database and produce the desired results. The user enters SQL command that is
immediately executed. Most databases have a tool that allows interactive execution of the SQL language. These include SQL Base's
SQL Talk, Oracle's SQL Plus, and Microsoft's SQL server 7 Query Analyzer.
The second way to execute a SQL command is by embedding it in another language such as Cobol, Pascal, BASIC, C, Visual Basic,
Java, etc. The result of embedded SQL command is passed to the variables in the host program, which in turn will deal with them.
The combination of SQL with a fourth-generation language brings together the best of two worlds and allows creation of user
interfaces and database access in one application.
AIGS
Page 3
STRUCTURED QUERY LANGUAGE
What is SQL?
• SQL stands for Structured Query Language. It is used for storing and managing data in RelationalDatabase Management
System (RDBMS).
• It is a standard language for Relational Database System. It enables a user to create, read, update and delete relational
databases and tables.
• All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their standard database
language.
• SQL allows users to query the database in a number of ways, using English-like statements.
• Structure query language is not case sensitive. Generally,keywords of SQL are written in uppercase.
• Statements of SQL are dependent on text lines. We canuse a single SQL statement on one or multiple text line.
• Using the SQL statements, you can perform most of theactions in a database.
AIGS
Page 4
What is SQL Process?
• When an SQL command is executing for any RDBMS, then the system figure out the best way to carry out the request and
the SQL engine determines that howto interpret the task.
• In the process, various components are included. These components can be optimization Engine, Queryengine, Query
dispatcher, classic, etc.
• All the non-SQL queries are handled by the classicquery engine, but SQL query engine won't handle logical files.
AIGS
Page 5
What is SQL Process?
AIGS
Page 6
What is Advantages of SQL?
• High speed
• No coding needed
• Well defined standards
• Portability
• Interactive language
• Multiple data view
AIGS
Page 7
What is SQL Datatype?
• SQL Datatype is used to define the values that acolumn can contain.
• Every column is required to have a name and datatype in the database table.
AIGS
Page 8
SQL Commands
• SQL commands are instructions. It is used to communicate with the database. It is also used toperform specific tasks, functions,
and queries of data.
• SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set permission for users.
AIGS
Page 9
Types of SQL Commands
• There are five types of SQL commands: DDL, DML,DCL, TCL, and DQL.
AIGS
Page 10
Data Definition Language (DDL)
• DDL changes the structure of the table like creating atable, deleting a table, altering a table, etc.
• All the command of DDL are auto-committed thatmeans it permanently save all the changes in the database.
• Here are some commands that come under DDL:
CREATE
ALTER
DROP
TRUNCATE
AIGS
Page 11
Data Definition Language (DDL)- CREATE
CREATE It is used to create a new table in the database.
Syntax:
REATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,. ...................................................................................... ]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);
AIGS
Page 12
Data Definition Language (DDL)- Drop
Drop: It is used to delete both the structure and recordstored in the table.
Syntax:
DROP TABLE ;
Example:
DROP TABLE EMPLOYEE;
AIGS
Page 13
Data Definition Language (DDL)- ALTER
ALTER: It is used to alter the structure of the database. This changecould be either to modify the characteristics of an existing attribute
or probably to add a new attribute.
Syntax:
ALTER TABLE table_name ADD column_name COLUMN-definition;ALTER TABLE MODIFY(COLUMN
DEFINITION................................................................................................. );
Example:
ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20)); ALTER TABLE STU_DETAILS MODIFY (NAME
VARCHAR2(20));
AIGS
Page 14
Data Definition Language (DDL)- TRUNCATE
TRUNCATE: It is used to delete all the rows from the table and freethe space containing the table.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
AIGS
Page 15
Data Manipulation Language
• DML commands are used to modify the database. It isresponsible for all form of CHANGES in the database.
• The command of DML is not auto-committed that means it can't permanently save all the changes in thedatabase. They can be
rollback.
AIGS
Page 16
Data Manipulation Language - INSERT
INSERT: The INSERT statement is a SQL query. It is used to insertdata into the row of a table.
Syntax:
Example:
AIGS
Page 17
Data Manipulation Language - UPDATE
Update: This command is used to update or modify the value of acolumn in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]
Example:
UPDATE students
SET User_Name = 'Sonoo'WHERE Student_Id = '3'
AIGS
Page 18
Data Control Language
DCL commands are used to GRANT and TAKE BACKauthority from any database user.
Revoke
AIGS
Page 19
Data Control Language - Grant
GRANT: It is used to give user access privileges to a database.
Example:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
Example:
AIGS
Page 20
Transaction Control Language
TCL commands can only use with DML commands likeINSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used while creatingtables or dropping them.
Here are some commands that come under TCL:
COMMIT
ROLLBACK
SAVEPOINT
AIGS
Page 21
Transaction Control Language - COMMIT
Commit: Commit command is used to save all the transactions tothe database.
Syntex:
COMMIT;
Example:
DELETE FROM CUSTOMERSWHERE AGE = 25;
COMMIT;
AIGS
Page 22
Transaction Control Language - Rollback
Rollback: Rollback command isused to undo transactions that SAVEPOINT: It is used to roll thetransaction back to a certain
have not already been saved to the database. point without rolling back the entire transaction.
Syntex: Syntex:
ROLLBACK; SAVEPOINT SAVEPOINT_NAME;
Example:
DELETE FROM CUSTOMERSWHERE AGE = 25;
ROLLBACK;
AIGS
Page 23
Data Query Language
DQL is used to fetch the data from the database.It uses only one command:
SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to select the attribute based onthe
condition described by WHERE clause.
Syntax:
SELECT expressions FROM TABLES WHERE conditions;
Example:
SELECT emp_name FROM employee WHERE age > 20;
AIGS
Page 24
SQL Operator
AIGS
Page 25
SQL Comparison Operators:
Operator Description
It is used to divide the left-hand operand by the right-handoperand and returns reminder.
%
AIGS
Page 26
SQL Arithmetic Operators
Operator Description
= It checks if two operands values are equal or not, if the values arequeal then condition becomes true.
!= It checks if two operands values are equal or not, if values are notequal, then condition becomes true.
It checks if two operands values are equal or not, if values are notequal then condition becomes true.
<>
It checks if the left operand value is greater than right operand value, if yes then condition becomes true.
>
It checks if the left operand value is less than right operand value, ifyes then condition becomes true.
<
It checks if the left operand value is greater than or equal to the rightoperand value, if yes then condition
>= becomes true.
AIGS
Page 27
SQL Arithmetic Operators
Operator Description
<= It checks if the left operand value is less than or equal to the rightoperand value, if yes then condition
becomes true.
!< It checks if the left operand value is not less than the right operandvalue, if yes then condition becomes true.
!> It checks if the left operand value is not greater than the right operandvalue, if yes then condition becomes
true.
AIGS
Page 28
SQL Logical Operators
Operator Description
AIGS
Page 29
Example:
SQL> CREATE TABLE EMPLOYEE ( EMP_ID INT
NOT NULL,
EMP_NAME VARCHAR (25) NOT NULL, PHONE_NO
INT NOT NULL,
ADDRESS CHAR (30),
PRIMARY KEY (ID)
);
• DESC EMPLOYEE;
• DELETE FROM table_name WHERE condition
• DROP TABLE "table_name";
• SELECT * FROM table_name;
• INSERT INTO TABLE_NAME VALUES (value1, value2, value 3, .... Value N);
• INSERT INTO TABLE_NAME[(col1, col2, col3,.... col N)] VALUES (value1, value2, value 3, ....
Value N);
• UPDATE table_name SET column_name = value WHERE condition;
AIGS
Page 30
Example:
• UPDATE table_name SET column_name = value1, column_name2 = valueWHERE condition;
• DELETE FROM table_name WHERE some_condition;
AIGS
Page 31
Views in SQL
• Views in SQL are considered as a virtual table. A viewalso contains rows and columns.
• To create the view, we can select the fields from oneor more tables present in the database.
• A view can either have specific rows based on certaincondition or all the rows of a table.
AIGS
Page 32
Creating view
A view can be created using the CREATE VIEW statement. We cancreate a view from a single table or multiple tables.
Syntax
CREATE VIEW view_name ASSELECT
column1, column2.....
FROM table_nameWHERE
condition;
Creating View from a single table
CREATE VIEW DetailsView ASSELECT
NAME, ADDRESS
FROM Student_Details WHERE
STU_ID < 4;
AIGS
Page 33
Creating View from multiple tables
View from multiple tables can be created by simply includemultiple tables in the SELECT statement.
In the given example, a view is created named MarksView fromtwo tables Student_Detail and Student_Marks.
AIGS
Page 34
SQL Index
• Indexes are special lookup tables. It is used to retrieve data from the database very fast.
• An Index is used to speed up select queries and where clauses. But it shows down the data input with insert and update
statements. Indexes can be created or dropped without affecting the data.
• An index in a database is just like an index in the back of a book.
AIGS
Page 35
Unique Index statement
Syntax
CREATE UNIQUE INDEX index_name ON table_name (column1, colum
n2, ...);
Example
CREATE UNIQUE INDEX websites_idx ON websites (site_name);
AIGS
Page 36
SQL Sub Query
A Subquery is a query within another SQL query and embeddedwithin the WHERE clause.
Important Rule:
• A subquery can be placed in a number of SQL clauses like WHERE clause,FROM clause, HAVING clause.
• You can use Subquery with SELECT, UPDATE, INSERT, DELETE statementsalong with the operators like =, <, >, >=,
<=, IN, BETWEEN, etc.
• A subquery is a query within another query. The outer query is known asthe main query, and the inner query is known as a
subquery.
• Subqueries are on the right side of the comparison operator.
• A subquery is enclosed in parentheses.
• In the Subquery, ORDER BY command cannot be used. But GROUP BYcommand can be used to perform the
same function as ORDER BY command.
AIGS
Page 37
Subqueries with the Select Statement
SQL subqueries are most frequently used with the Select statement.
Syntax:
SELECT column_nameFROM
table_name
Example:
SELECT *
FROM EMPLOYEE WHERE ID IN
(SELECT IDFROM EMPLOYEE
WHERE SALARY > 4500);
AIGS
Page 38
Subqueries with the INSERT Statement
• SQL subquery can also be used with the Insert statement. In the insert statement, data returned from the subquery is used to
insert into anothertable.
• In the subquery, the selected data can be modified with any of thecharacter, date functions.
Syntax:
INSERT INTO table_name (column1, column2, column3 ............................................................ )
SELECT * FROM table_name WHERE VALUE OPERATOR
Example:
INSERT INTO EMPLOYEE_BKP SELECT *
FROM EMPLOYEEWHERE ID IN
(SELECT ID FROM EMPLOYEE);
AIGS
Page 39
Subqueries with the UPDATE Statement
The subquery of SQL can be used in conjunction with the Update statement. When a subquery is used with the Update statement,
then either single or multiple columns in a table can be updated.
Syntax:
UPDATE table SET column_name = new_value WHERE VALUE OPERATOR(SELECT COLUMN_NAME
FROM TABLE_NAME WHERE condition);
Example:
Let's assume we have an EMPLOYEE_BKP table available which is backup ofEMPLOYEE table. The given example updates the
SALARY by .25 times in theEMPLOYEE table for all employee whose AGE is greater than or equal to 29.
UPDATE EMPLOYEE
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKPWHERE AGE >= 29);
AIGS
Page 40
Subqueries with the DELETE Statement
The subquery of SQL can be used in conjunction with the Deletestatement just like any other statements mentioned above.
Syntax:
DELETE FROM TABLE_NAME WHERE VALUE OPERATOR
(SELECT COLUMN_NAME FROM TABLE_NAME WHERE condition);
Example:
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given example deletes the
records from the EMPLOYEEtable for all EMPLOYEE whose AGE is greater than or equal to 29.
AIGS
Page 41
SQL Clauses
AIGS
Page 42
GROUP BY
• SQL GROUP BY statement is used to arrange identical data intogroups.
• The GROUP BY statement is used with the SQL SELECTstatement.
• The GROUP BY statement follows the WHERE clause in aSELECT statement and precedes the ORDER BY
clause.
• The GROUP BY statement is used with aggregation function.
Example
Syntax
SELECT column FROM table_name SELECT COMPANY, COUNT(*)FROM
WHERE conditionsGROUP BY PRODUCT_MAST GROUP BY COMPANY;
columnORDER BY column
AIGS
Page 43
HAVING
• HAVING clause is used to specify a search condition for a groupor an aggregate.
• Having is used in a GROUP BY clause. If you are not using GROUP BY clause then you can use HAVING function
like aWHERE clause
Syntax
SELECT column1, column2 FROM table_name Example
SELECT COMPANY, COUNT(*)FROM
WHERE conditions PRODUCT_MAST GROUP BY COMPANY
GROUP BY column1, column2HAVING HAVING COUNT(*)>2;
conditions
ORDER BY column1, column2;
AIGS
Page 44
ORDER BY
• The ORDER BY clause sorts the result-set in ascending ordescending order.
• It sorts the records in ascending order by default. DESC keyword is used to sort the records in descending order.
Example
Syntax
SELECT column1, column2FROM SELECT *
table_name WHERE condition FROM CUSTOMER ORDER BY
ORDER BY column1, column2... ASC|DESC; NAME;OR
SELECT *
FROM CUSTOMER ORDER BY NAME
DESC;
AIGS
Page 45
SQL Aggregate Functions
AIGS
Page 46
COUNT FUNCTION
• COUNT function is used to Count the number of rows in a databasetable. It can work on both numeric and non-numeric data
types.
• COUNT function uses the COUNT(*) that returns the count of all therows in a specified table. COUNT(*) considers duplicate
and Null.
Syntax
COUNT(*) or COUNT( [ALL|DISTINCT] expression )
Example
AIGS
Page 47
SUM FUNCTION
• Sum function is used to calculate the sum of all selectedcolumns. It works on numeric fields only.
Syntax
AIGS
Page 48
AVG FUNCTION
• The AVG function is used to calculate the average value of the numeric type. AVG function returns the average of all non-Null
values.
Syntax
Example
SELECT AVG(COST) FROM PRODUCT_MAST;
AIGS
Page 49
MAX FUNCTION
• MAX function is used to find the maximum value of a certain column. Thisfunction determines the largest value of all
selected values of a column.
Syntax
AIGS
Page 50
SQL JOIN
SQL, JOIN means "to combine two or more tables". In SQL, JOIN clause is used tocombine the records from two or more tables in a
database.
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
AIGS
Page 51
INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the condition is satisfied. It returns the
combination of all rows from boththe tables where the condition satisfies.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 INNER JOIN
table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENTFROM EMPLOYEE
AIGS
Page 52
LEFT JOIN
The SQL left join returns all the values from left table and the matching valuesfrom the right table. If there is no matching join value, it
will return NULL. Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 LEFT JOIN
table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENTFROM EMPLOYEE
AIGS
Page 53
RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched values from the left table. If
there is no matching in bothtables, it will return NULL.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 RIGHT JOIN
table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENTFROM EMPLOYEE
AIGS
Page 54
FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join.Join tables have all the records from both tables. It puts
NULL on the place of matches not found.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 FULL JOIN
table2
ON table1.matching_column = table2.matching_column;
Example
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENTFROM EMPLOYEE
AIGS
Page 55
SQL Set Operation
The SQL Set operation is used to combine the two ormore SQL SELECT statements
AIGS
Page 56
Union Operation
• The SQL Union operation is used to combine the result of two or more SQLSELECT queries.
• In the union operation, all the number of datatype and columns must besame in both the tables on which UNION operation
is being applied.
• The union operation eliminates the duplicate rows from its resultset.
Syntax
SELECT column_name FROM table1UNION
AIGS
Page 57
Intersect Operation
• It is used to combine two SELECT statements. The Intersect operation returnsthe common rows from both the SELECT
statements.
• In the Intersect operation, the number of datatype and columns must be thesame.
• It has no duplicates and it arranges the data in ascending order by default.
Syntax
SELECT column_name FROM table1INTERSECT
AIGS
Page 58
MINUSOperation
• It combines the result of two SELECT statements. Minus operator is used to display the rows which are present in the first query
but absent in the secondquery.
• It has no duplicates and data arranged in ascending order by default.
Syntax
SELECT column_name FROM table1MINUS
AIGS
Page 59