Unit 2
Unit 2
Unit 2
SQL
o SQL stands for Structured Query Language. It is used for storing and managing data in relational database
management system (RDMS). In RDBMS data stored in the form of the tables.
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 several ways, using English-like statements.
o SQL is mostly used by engineers in software development for data storage. Nowadays, it is also used by
data analyst for following reason:
o Structure query language is not case sensitive. Generally, keywords of SQL are written in uppercase.
o Every SQL statement should end with a semicolon.
o Statements of SQL are dependent on text lines. We can use a single SQL statement on one or multiple
text line.
o Using the SQL statements, you can perform most of the actions in a database.
o SQL depends on tuple relational calculus and relational algebra.
o 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 how to interpret the task.
o In the process, various components are included. These components can be optimization Engine, Query
engine, Query dispatcher, classic, etc.
o All the non-SQL queries are handled by the classic query engine, but SQL query engine won't handle
logical files.
SQL Datatype
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
Datatype of SQL:
1. Binary Datatypes
There are Three types of binary Datatypes which are given below:
Data Description
Type
binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.
float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.
Data Description
type
char It has a maximum length of 8000 characters. It contains Fixed-length non-unicode characters.
varchar It has a maximum length of 8000 characters. It contains variable-length non-unicode characters.
Datatype Description
timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is also used to perform
specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set
permission for users.
There are four types of SQL commands: DDL, DML, DCL, TCL.
1. Data Definition Language (DDL)
o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
o All the command of DDL are auto-committed that means it permanently save all the changes in the
database.
Syntax:
In above statement, TABLE_NAME is the name of the table, COLUMN_NAMES is the name of the columns
and DATATYPES is used to define the type of data.
Example:
b. DROP: It is used to delete both the structure and record stored in the table.
The cascade constraint is an optional parameter which is used for tables which have foreign keys that reference
the table being dropped. If cascade constraint is not specified and used attempt to drop a table that has records in
a child table, then an error will occur. So by using cascade constraints, all child table foreign keys are dropped.
Example
c. ALTER: It is used to alter the structure of the database. This change could be either to modify the characteristics
of an existing attribute or probably to add a new attribute.
Following are the list of modifications that can be done using ALTER command.
o With the use of ALTER commands we can add or drop one or more columns form existing tables.
o Increase or decrease the existing column width by changing the data type
o Make an existing mandatory column to optional.
o Enable or disable the integrity constraints in a table. We can also add, modify or delete the integrity
constraints from a table.
o We can also specify a default value for existing column in a table.
With the use of ALTER table command we can add new columns existing table.
In the above syntax, where table_name corresponds to the name of the table, column-definition corresponds to
the valid specifications for a column name and data type.
EXAMPLE:
Example:
You can also add constraints to an existing table. For example: If you forget to add a primary key constraint to a
table during creation, you can add it using the ALTER TABLE statement.
Example:
Following points should be kept in mind while adding new columns/relationships to existing tables.
Syntax:
Example:
SQL does not allow column widths to be reduced even if all column values are of valid length. So the values
should be set to NULL to reduce the width of the columns. It is also not possible to reduce the width of the
ADHAR_NUM column from 18 to 12 even if all values in the ADHAR_NUM column are less than 12 characters,
unless all al values in the name column are null. You can modify the column form NULL to NOTNULL
constraints if there is no record in that column in the table.
Example:
You cannot only modify columns but you can also drop them entirely if it is no longer required in a table. Using
drop statement in alter command we can also remove the constraints form the table.
Example:
Example:
Example:
o You cannot drop columns in a table. If you want to drop a column from a table, the deletion is permanent
so you cannot undo the column if you accidentally drop the wrong column.
o You cannot drop a column whose username is SYS.
o If you want to drop a primary key column unless you drop the foreign keys that belong to it then use
cascade keyword for this.
Example:
Example:
RENAMING TABLE
SQL provides the facility to change the name of the table by using a ALTER TABLE statement.
Syntax:
Example:
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
Syntax:
Example:
Syntax:
Example:
o DML commands are used to modify the database. It is responsible for all form of changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all the changes in the
database. They can be rollback.
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table. To insert a
new row into a table you must be your on schema or INSERT privilege on the table.
Following are the list of points should be considered while inserting the data into tables.
o SQL uses all the columns by default if you do not specify the column name while inserting a row.
o The number of columns in the list of column name must match the number of values that appear in
parenthesis after the word "values".
o The data type for a column and its corresponding value must match.
Or
In the above syntax, TABLE_NAME is the name of the table in which the data will be inserted. The (col1, col2,
col3, col N) are optional and name of the columns in which values will be inserted. The value1 corresponds to the
value of be inserted in col1 and similarly value2 corresponds to the value of be inserted in col2 and so on.
For example:
For example:
1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS"), ("Raman", "DBMS"), ("Pr
iya", "DBMS");
b. UPDATE: This command is used to update or modify the value of a column in the table.
In the above syntax, table_name is the name of the table, the column_name is the name of column in the table to
be modified, and value1 corresponds to the valid SQL values. The "WHERE" is a condition that restricts the rows
updated for which the specified condition is true. If condition is not specified is not defined then SQL updates all
the rows in the table. It contains comparison and logical operators etc.
The following the list of points should be remembered while executing the UPDATE statement.
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
c. DELETE: It is used to remove one or more row from a table. To delete rows from the table, it must be in your
schema or you must have delete privilege.
In the above syntax, condition is used in the where clause to filter the records that are actually being removed.
You can remove zero or more rows from a table. If you do not use where condition then DELETE statement will
remove all the rows from the table. You can also use one or multiple conditions in WHERE clause.
For example:
d. SELECT: This is the same as the projection operation of relational algebra. It is used to select the attribute
based on the condition described by WHERE clause.
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
Syntax:
In the above syntax, obj_priv> is the DML statement like Insert, Delete , update and Select and <obj_name> is a
table, view etc. and username is the name of the authorized user.
Example
Syntax:
In the above syntax, obj_priv> is the DML statement like Insert, Delete , update and Select and <obj_name> is a
table, view etc. and username is the name of the user from whom the permission is revoked.
Example
These operations are automatically committed in the database that's why they cannot be used while creating tables
or dropping them.
a. Commit: Commit command is used to save all the transactions to the database. It makes your changes
permanent and ends the transaction.
1. COMMIT;
Example:
b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.
Rollback also serves to end the current transaction and begin a new one.
Consider a Situation where you have completed a series of INSERT, UPDATE or DELETE statements but have
not yet explicitly committed them and yiu encounter a problem such as computer failure, then SQL will
automatically rollback any uncommitted work.
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
To selectively ROLLBACK a group of statements within a large transaction use the following command is used.
1. Rollback TO <save_point_name>
Example:
SQL Operator
Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.
- It is used to subtract the right-hand operand from the left-hand operand. a-b will give
10
/ It is used to divide the left-hand operand by the right-hand operand. a/b will give
2
% It is used to divide the left-hand operand by the right-hand operand and returns a%b will
reminder. give 0
Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.
= It checks if two operands values are equal or not, if the values are queal then (a=b) is not
condition becomes true. true
!= It checks if two operands values are equal or not, if values are not equal, then (a!=b) is true
condition becomes true.
<> It checks if two operands values are equal or not, if values are not equal then (a<>b) is
condition becomes true. true
> It checks if the left operand value is greater than right operand value, if yes (a>b) is not
then condition becomes true. true
< It checks if the left operand value is less than right operand value, if yes then (a<b) is true
condition becomes true.
>= It checks if the left operand value is greater than or equal to the right operand (a>=b) is not
value, if yes then condition becomes true. true
<= It checks if the left operand value is less than or equal to the right operand (a<=b) is
value, if yes then condition becomes true. true
!< It checks if the left operand value is not less than the right operand value, if (a!=b) is not
yes then condition becomes true. true
!> It checks if the left operand value is not greater than the right operand value, (a!>b) is true
if yes then condition becomes true.
Operator Description
ALL It compares a value to all values in another value set.
BETWEEN It is used to search for values that are within a set of values.
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the database.
o A view can either have specific rows based on certain condition or all the rows of a table.
Advantages of View:
1. Complexity: Views help to reduce the complexity. Different views can be created on the same base table
for different users.
2. Security: It increases the security by excluding the sensitive information from the view.
3. Query Simplicity: It helps to simplify commands from the user. A view can draw data from several
different tables and present it as a single table.
4. Consistency: A view can present a consistent, unchanged image of the structure of the database. Views
can be used to rename the columns without affecting the base table.
5. Data Integrity: If data is accessed and entered through a view, the DBMS can automatically check the
data to ensure that it meets the specified integrity constraints.
6. Storage Capacity: Views take very little space to store the data.
7. Logical Data Independence: View can make the application and database tables to a certain extent
independent.
Disadvantages of View:
The DML statements which can be performed on a view created using single base table have certain restrictions
are:
1. You cannot INSERT if the base table has any not null column that do not appear in view.
2. You cannot INSERT or UPDATE if any of the column referenced in the INSERT or UPDATE contains
group functions or columns defined by expression.
3. You can't execute INSERT, UPDATE, DELETE statements on a view if with read only option is enabled.
4. You can't be created view on temporary tables.
5. You cannot INSERT, UPDATE, DELETE if the view contains group functions GROUP BY, DISTINCT
or a reference to a psuedocolumn rownum.
6. You can't pass parameters to the SQL server views.
7. You can't associate rules and defaults with views.
Sample table:
Student_Detail
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single table or multiple
tables.
Syntax:
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
Just like table query, we can query the view to view the data.
1. SELECT * FROM DetailsView;
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
View from multiple tables can be created by simply include multiple tables in the SELECT statement.
In the given example, a view is created named MarksView from two tables Student_Detail and Student_Marks.
Query:
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
Syntax
Example:
Views are highly significant, as they can provide advantages over tasks. Views can represent a subset of data
contained in a table. Consequently they can limit the degree of exposure of the underlying base table to the outer
world. They are used for security purpose in database and act as an intermediate between real table schemas and
programmability. They act as aggregate tables.
Types of Views:
1. Join View: A join view is a view that has more than one table or view in its from clause and it does not
use any Group by Clause, Rownum, Distinct and set operation.
2. Inline View: An inline view is a view which is created by replacing a subquery in the from clause which
defines the data source that can be referenced in the main query. The sub query must be given an alias
for efficient working.
SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database very fast.
o 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.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain topic, you first have to
refer to the index, which alphabetically lists all the topics and then referred to one or more specific page
numbers.
Syntax
Example
It is used to create a unique index on a table. It does not allow duplicate value.
Syntax
Syntax
Example
A Subquery is a query within another SQL query and embedded within the WHERE clause.
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING
clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators
like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner
query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to
perform the same function as ORDER BY command.
SQL subqueries are most frequently used with the Select statement.
Syntax
1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);
4 Alina 29 UK 6500.00
o SQL subquery can also be used with the Insert statement. In the insert statement, data returned from the
subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date functions.
Syntax:
Example
Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.
Syntax
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);
Example
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given
example updates the SALARY by .25 times in the EMPLOYEE table for all employee whose AGE is greater than
or equal to 29.
1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);
This would impact three rows, and finally, the EMPLOYEE table would have the following records.
1 John 20 US 2000.00
4 Alina 29 UK 1625.00
The subquery of SQL can be used in conjunction with the Delete statement just like any other statements
mentioned above.
Syntax
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given
example deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE is greater than or equal
to 29.
This would impact three rows, and finally, the EMPLOYEE table would have the following records.
1 John 20 US 2000.00
SQL Clauses
1. GROUP BY
o SQL GROUP BY statement is used to arrange identical data into groups. The GROUP BY statement is
used with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.
o The GROUP BY statement is used with aggregation function.
Syntax
1. SELECT column
2. FROM table_name
3. WHERE conditions
4. GROUP BY column
5. ORDER BY column
Sample table:
PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example:
Output:
Com1 5
Com2 3
Com3 2
2. HAVING
Syntax:
Example:
Com1 5
Com2 3
3. ORDER BY
Syntax:
Where
Table:
CUSTOMER
12 Kathrin US
23 David Bangkok
34 Alina Dubai
45 John UK
56 Harry US
1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME;
Output:
23 David Bangkok
56 Harry US
45 John UK
12 Kathrin US
1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME DESC;
Output:
12 Kathrin US
45 John UK
56 Harry US
23 David Bangkok
34 Alina Dubai
o SQL aggregation function is used to perform the calculations on multiple rows of a single column of a
table. It returns a single value.
o It is also used to summarize the data.
1. COUNT FUNCTION
o 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.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
7
Example: COUNT() with DISTINCT
Output:
Output:
Com1 5
Com2 3
Com3 2
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
3. 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
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function determines the largest value
of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function determines the smallest value
of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or more
tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Sample Table
EMPLOYEE
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. 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 both the tables where the condition satisfies.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right table. If there is no
matching join value, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. 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 both tables, it will return NULL.
Syntax
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. 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
Query
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
o In the union operation, all the number of datatype and columns must be same in both the tables on which
UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.
Syntax
Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing duplication and sorting
the data.
Syntax:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the common rows from
both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
Example:
ID NAME
3 Jackson
4. Minus
o 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 second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
Example
ID NAME
1 Jack
2 Harry
PL/SQL Cursor
When an SQL statement is processed, Oracle creates a memory area known as context area. A cursor is a pointer
to this context area. It contains all information needed for processing the statement. In PL/SQL, the context area
is controlled by Cursor. A cursor contains information on a select statement and the rows of data accessed by it.
PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger is stored into
database and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some event occurs.