Self Unit 3
Self Unit 3
Self Unit 3
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.
o Structure query language is not case sensitive. Generally, keywords of SQL are written in
uppercase.
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.
SQL process:
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 data Definition:
The set of relations in a database must be specified to the system by means of a data-definition
language (DDL). The SQL DDL allows specification of not only a set of relations, but also
information about each relation, including:
1. Basic Types The SQL standard supports a variety of built-in types, including:
• char (n): fixed-length character string with user-specified length n. The full form, character,
can be used instead.
• varchar(n): A variable-length character string with user-specified maximum length n. The full
form, character varying, is equivalent.
• int: An integer (a finite subset of the integers that is machine dependent). The full form,
integer, is equivalent.
• numeric (p, d): A fixed-point number with user-specified precision. The number consists of p
digits (plus a sign), and d of the p digits are to the right of the decimal point. Thus, numeric (3,1)
allows 44.5 to be stored exactly, but neither 444.5 or 0.32 can be stored exactly in a field of this
type.
SQL is based on set relational operations with certain modification and enhancements.
A typical SQL query has the form:
THE SELECT CLAUSE
THE FORM CLAUSE
THE WHERE CLAUSE
o The SELECT clause:
o The select clause list the attributes described in the result of a query.
o SQL allows duplicates in relations as well as in query results.
o The Select clause can contain arithmetic expressions involving the operations +,
-, * and / operating on constants o attributes of tuples.
Select Syntax:
Where Syntax:
FROM syntax:
o DDL stands for Data Definition Language. It is used to define database structure or
pattern.
o It is used to create schema, tables, indexes, constraints, etc. in the database.
o Using the DDL statements, you can create the skeleton of the database.
o Data definition language is used to store the information of metadata like the number of
tables and schemas, their names, indexes, columns in each table, constraints, etc.
a) CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
Syntax: CREATE TABLE table_name
(column_1 datatype,
column_2 datatype,
column_3 datatype,
.... );
b) DROP: This command is used to delete objects from the database.
Syntax: DROP TABLE table_name;
c) ALTER: This command is used to add, delete or change columns in the existing table. The
user needs to know the existing table name and can do add, delete or modify tasks
easily.
Syntax: ALTER TABLE table_name
ADD column_name datatype; {This syntax is to add column}
d) TRUNCATE: This is used to remove all records from a table, including all spaces allocated
for the records are removed.
Syntax: TRUNCATE TABLE table_name;
e) Rename: It is used to rename an object.
Syntax: RENAME TABLE Employee To EMP;
a) SELECT Command – This command is used to get data out of the database. It helps users of
the database to access from an operating system, the significant data they need. It sends a
track result set from one tables or more.
b) INSERT Command – This command is used to enter the information or values into a row. We
can connect one or more records to a single table within a repository using this instruction. This
is often used to connect an unused tag to the documents.
Syntax:
c)UPDATE Command – This command is used to alter existing table records. Within a table, it
modifies data from one or more records. This command is used to alter the data which is
already present in a table.
d)DELETE Command – It deletes all archives from a table. This command is used to erase some
or all of the previous table’s records. If we do not specify the ‘WHERE’ condition then all the
rows would be erased or deleted.
DCL includes commands such as GRANT and REVOKE which mainly deal with the rights,
permissions, and other controls of the database system.
a) GRANT: This command is used to grant permission to the user to perform a particular
operation on a particular object. If you are a database administrator and you want to restrict
user accessibility such as one who only views the data or may only update the data. You can
give the privilege permission to the users according to your wish.
b) REVOKE: This command is used to take permission/access back from the user. If you want to
return permission from the database that you have granted to the users at that time you need
to run REVOKE command.
TCL is used to run the changes made by the DML statement. TCL can be grouped into a logical
transaction.
1.COMMIT: This command is used to save the data permanently. Whenever we perform any of
the DML command like -INSERT, DELETE or UPDATE, these can be rollback if the data is not
stored permanently. So in order to be at the safer side COMMIT command is used.
Syntax: commit;
2. ROLLBACK: This command is used to get the data or restore the data to the last savepoint or
last committed state. If due to some reasons the data inserted, deleted or updated is not
correct, you can rollback the data to a particular savepoint or if savepoint is not done, then to
the last committed state.
Syntax: rollback;
3. SAVEPOINT: This command is used to save the data at a particular point temporarily, so that
whenever needed can be rollback to that particular point.
Syntax: Savepoint A;
SET OPERATIONS:
o SQL supports few set operations which can be performed on the table data.
o These are used to get meaningful results from data stored in the table
under different special conditions.
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 result set.
Syntax
1 Jack
UNION
SELECT 2 Harry column_name
FROM t able2;
3 Jackson
Example:
ID NAME
3 Jackson
4 Stephan
The Second table
5 David
UNION
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
Null Values:
In SQL there may be some records in a table that do not have values or data for every field and
those fields are termed as a NULL value. NULL values could be possible because at the time of
data entry information is not available. So SQL supports a special value known as NULL which is
used to represent the values of attributes that may be unknown or not apply to a tuple. SQL
places a NULL value in the field in the absence of a user-defined value. For example, the
Apartment_number attribute of an address applies only to addresses that are in apartment
buildings and not to other types of residences.
So, NULL values are those values in which there is no data value in the particular field in the
table.
Setting a NULL value is appropriate when the actual value is unknown, or when a value
is not meaningful.
A NULL value is not equivalent to a value of ZERO if the data type is a number and is not
equivalent to spaces if the data type is a character.
A NULL value can be inserted into columns of any data type.
A NULL value will evaluate NULL in any expression.
Suppose if any column has a NULL value, then UNIQUE, FOREIGN key, and CHECK
constraints will ignore by SQL.
Example:
Suppose we have to find the Fname and Lname of the Employee having no Super_ssn
Ouput:
Aggregate Function:
SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table.
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
COUNT(*)
or
COUNT([ALL|DISTINCT] expression)
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
1.Example: COUNT ()
Output:
10
Output:
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: SUM ()
or
SUM([ALL|DISTINCT] expression)
1.Example: SUM ()
SELECT SUM(COST)
FROM PRODUCT_MAST;
Output:
670
SELECT SUM(COST)
FROM PRODUCT_MASTWHERE QTY>3;
Output:
320
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;
Output:
Com1 150
Com2 170
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
AVG ()
or
AVG([ALL|DISTINCT] expression)
Example:
SELECT AVG(COST)
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
MAX ()
or
MAX([ALL|DISTINCT] expression)
1.Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
Output:
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
MIN ()
or
MIN([ALL|DISTINCT] expression)
1.Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
Nested Sub_Queries:
In nested queries, a query is written inside a query. The result of inner query is used in
execution of outer query. We will use STUDENT, COURSE, STUDENT_COURSE tables for
understanding nested queries.
Student:
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS
Student_Course:
S_ID C_ID
S1 C1
S1 C3
S2 C1
S3 C2
S4 C2
S4 C3
There are mainly two types of nested queries:
1.Independent Nested Queries: In independent nested queries, query execution starts from
innermost query to outermost queries. The execution of inner query is independent of outer
query, but the result of inner query is used in execution of outer query. Various operators like
IN, NOT IN, ANY, ALL etc are used in writing independent nested queries.
IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can write it
with the help of independent nested query and IN operator. From COURSE table, we can find
out C_ID for C_NAME ‘DSA’ or DBMS’ and we can use these C_IDs for finding S_IDs from
STUDENT_COURSE TABLE.
Select S_ID from STUDENT_COURSE where C_ID IN (SELECT C_ID from COURSE
The inner query will return a set with members C1 and C3 and outer query will return those
S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case). So, it will return S1,
S2 and S4.
Note: If we want to find out names of STUDENTs who have either enrolled in ‘DSA’ or ‘DBMS’, it
can be done as:
NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’ nor in
‘DBMS’, it can be done as:
The innermost query will return a set with members C1 and C3. Second inner query will return
those S_IDs for which C_ID is equal to any member of set (C1 and C3 in this case) which are S1,
S2 and S4. The outermost query will return those S_IDs where S_ID is not a member of set (S1,
S2 and S4). So it will return S3.
2.Co-related Nested Queries: It is a subquery that uses values from outer query. In co-related
nested queries, the output of inner query depends on the row which is being currently
executed in outer query.
e.g.; If we want to find out S_NAME of STUDENTs who are enrolled in C_ID ‘C1’, it can be done
with the help of co-related nested query as:
For each row of STUDENT S, it will find the rows from STUDENT_COURSE where S.S_ID = SC.
S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists in STUDENT_COURSE
SC with C_ID=’C1’, then inner query will return true and corresponding S_ID will be returned as
output.
Authorization:
What is Authorization?
Authorization Techniques:
Role-based access control: RBAC or Role-based access control technique is given to
users as per their role or profile in the organization. It can be implemented for
system-system or user-to-system.
JSON web token: JSON web token or JWT is an open standard used to securely
transmit the data between the parties in the form of the JSON object. The users are
verified and authorized using the private/public key pair.
SAML: SAML stands for Security Assertion Markup Language. It is an open standard
that provides authorization credentials to service providers. These credentials are
exchanged through digitally signed XML documents.
OpenID authorization: It helps the clients to verify the identity of end-users on the
basis of authentication.
OAuth: OAuth is an authorization protocol, which enables the API to authenticate
and access the requested resources.
Integrity Constraints:
Integrity constraints are a set of rules. It is used to maintain the quality of information.
Integrity constraints ensure that the data insertion, updating, and other processes have
to be performed in such a way that data integrity is not affected.
Thus, integrity constraint is used to guard against accidental damage to the database.
Types of Integrity Constraint
1. Domain constraints
o Domain constraints can be defined as the definition of a valid set of values for an
attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc.
The value of the attribute must be available in the corresponding domain.
Example:
o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
o A table can contain a null value other than the primary key field.
Example:
Example:
4. Key constraints:
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o An entity set can have multiple keys, but out of which one key will be the primary key. A
primary key can contain a unique and null value in the relational table.
Example:
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.
Sample Table
EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE
PROJECT
101 1 Testing
102 2 Development
103 3 Designing
104 4 Development
1. INNER JOIN
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
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
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
Views:
Views in SQL Views in SQL are considered as a virtual table. A view also contains rows and
columns.
To create the view, we can select the fields from one or more tables present in the
database.
A view can either have specific rows based on certain condition or all the rows of a table.
Advantages of View:
Complexity: Views help to reduce the complexity. Different views can be created on the
same base table for different users.
Security: It increases the security by excluding the sensitive information from the view.
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.
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.
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.
Storage Capacity: Views take very little space to store the data.
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.
6. You can't pass parameters to the SQL server views.
7. You can't associate rules and defaults with views.
Types of Views:
There are two 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.
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:
Query:
Just like table query, we can query the view to view the data.
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
3. Creating View from multiple tables
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
A view can be deleted using the Drop View statement.
Syntax
Modification of the Database The modification of a database has three commands, namely:
DELETE INSERT UPDATE
Data types mainly classified into three categories for every database.
CHAR(Size) It is used to specify a fixed length string that can contain numbers, lette
characters. Its size can be 0 to 255 characters. Default is 1.
VARCHAR(Size) It is used to specify a variable length string that can contain numbers, lette
characters. Its size can be from 0 to 65535 characters.
BINARY(Size) It is equal to CHAR() but stores binary byte strings. Its size parameter specif
length in the bytes. Default is 1.
VARBINARY(Size) It is equal to VARCHAR() but stores binary byte strings. Its size paramete
maximum column length in bytes.
TEXT(Size) It holds a string that can contain a maximum length of 255 characters.
TINYTEXT It holds a string with a maximum length of 255 characters.
ENUM(val1, val2, It is used when a string object having only one value, chosen from a list of po
val3,...) contains 65535 values in an ENUM list. If you insert a value that is not in t
value will be inserted.
SET( val1,val2,val3,.. It is used to specify a string that can have 0 or more values, chosen from a
..) values. You can list up to 64 values at one time in a SET list.
BLOB(size) It is used for BLOBs (Binary Large Objects). It can hold up to 65,535 bytes.
BIT(Size) It is used for a bit-value type. The number of bits per value is specified in size. Its s
64. The default value is 1.
INT(size) It is used for the integer value. Its signed range varies from -2147483648 to 21
unsigned range varies from 0 to 4294967295. The size parameter specifies the ma
that is 255.
FLOAT(size, d) It is used to specify a floating point number. Its size parameter specifies the to
digits. The number of digits after the decimal point is specified by d parameter.
FLOAT(p) It is used to specify a floating point number. MySQL used p parameter to determ
use FLOAT or DOUBLE. If p is between 0 to24, the data type becomes FLOAT (). If
53, the data type becomes DOUBLE().
DOUBLE(size, It is a normal size floating point number. Its size parameter specifies the total nu
d) The number of digits after the decimal is specified by d parameter.
DECIMAL(size, It is used to specify a fixed point number. Its size parameter specifies the total nu
d) The number of digits after the decimal parameter is specified by d parameter.
value for the size is 65, and the default value is 10. The maximum value for d is 30,
value is 0.
DEC(size, d) It is equal to DECIMAL(size, d).
BOOL It is used to specify Boolean values true and false. Zero is considered as false, and
are considered as true.
DATE It is used to specify date format YYYY-MM-DD. Its supported range is from '
'9999-12-31'.
DATETIME(fsp) It is used to specify date and time combination. Its format is YYYY-MM-DD
supported range is from '1000-01-01 00:00:00' to 9999-12-31 23:59:59'.
TIMESTAMP(fsp) It is used to specify the timestamp. Its value is stored as the number of seconds
epoch('1970-01-01 00:00:00' UTC). Its format is YYYY-MM-DD hh:mm:ss. Its supp
from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC.
TIME(fsp) It is used to specify the time format. Its format is hh:mm:ss. Its supported ra
838:59:59' to '838:59:59'
YEAR It is used to specify a year in four-digit format. Values allowed in four digit forma
2155, and 0000.
Schema: A Schema is a collection of database object, including tables, views, and stored
procedures.