Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Self Unit 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

Introduction to SQL:

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.

SQL follows the following rules:

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:

• The schema for each relation.

• The types of values associated with each attribute.

• The integrity constraints.

• The set of indices to be maintained for each relation.

• The security and authorization information for each relation.

• The physical storage structure of each relation on disk.

We discuss here basic schema definition and basic types:

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.

• small int: A small integer (a machine-dependent subset of the integer type).

• 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.

• real, double precision: Floating-point and double-precision floating-point numbers with


machine-dependent precision.
• float(n): A floating-point number, with precision of at least n digits. Each type may include a
special value called the null value. A null value indicates an absent value that may exist but be
unknown or that may not exist at all. In certain cases, we may wish to prohibit null values from
being entered, as we shall see shortly.

Basic Structure of SQL Queries:

 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:

a)SELECT column1, column2,...


FROM table_name;

b) SELECT * FROM table_name; //This will return every value

o The WHERE Clause:


o The where clause specifies condition that the result must satisfy.
o Comparison results can be combined using the logical connectives and, or, not.
o Comparison can be applied to results of arithmetic expressions.

Where Syntax:

a) SELECT column1, column2,...


FROM table_name
WHERE condition;
b) SELECT * FROM Customers
WHERE CustomerID=1;
Note: The WHERE clause is not only used in SELECT statements, it is also used in
UPDATE, DELETE, etc.!

o The FROM Clause:


o The from clause is a source of a row set to be operated upon in a data
manipulation language(DML) statement.
The form is an SQL reserved word in SQL standard.
o The from clause is used in conjunction with SQL statements.

FROM syntax:

SELECT * FROM customer;

DDL (Data Definition Language):

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.

List of DDL commands:

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;

DLM (Data Manipulation Language):

Here are some tasks that come under DML:

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.

Syntax: SELECT * FROM <table_name>;

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:

INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>)

VALUES ('value1', 'value2');

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.

Syntax: UPDATE <table_name> SET <column_name = value> WHERE condition;

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.

Syntax: DELETE FROM <table_name> WHERE <condition>;


DCL (Data Control Language):

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.

Syntax: GRANT privilege_list ON Object_name TO user_name;

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.

Syntax: REVOKE privilege_list ON object_name FROM user_name;

Transaction Control Language (TCL):

TCL is used to run the changes made by the DML statement. TCL can be grouped into a logical
transaction.

The TCL commands are:

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.

Types of Set Operation


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 result set.

Syntax

SELECT column_name FROM table1


ID NAME

1 Jack
UNION
SELECT 2 Harry column_name
FROM t able2;
3 Jackson
Example:

The First table

ID NAME

3 Jackson

4 Stephan
The Second table
5 David

Union SQL query will be: SELECT * FROM First

UNION

SELECT * FROM Second;

The resultset table will look like:

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:

SELECT column_name FROM table1


UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

SELECT * FROM First


UNION ALL
SELECT * FROM Second;

The resultset table will look like:

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

SELECT column_name FROM table1


INTERSECT
SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

SELECT * FROM First


INTERSECT
SELECT * FROM Second;

The resultset table will look like:

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:

SELECT column_name FROM table1


MINUS
SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

SELECT * FROM First


MINUS
SELECT * FROM Second;

The resultset table will look like:

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.

Importance of NULL Value:

o It is important to understand that a NULL value differs from a zero value.


o A NULL value is used to represent a missing value, but it usually has one of three
different interpretations:
 The value unknown (value exists but is not known).
 Value not available (exists but is purposely withheld).
 Attribute not applicable (undefined for this tuple)
o It is often not possible to determine which of the meanings is intended. Hence, SQL
does not distinguish between the different meanings of NULL.

Principles of NULL values:

 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

then the query will be:

Query: SELECT Fname, Lname FROM Employee WHERE SSN IS NULL;

Ouput:
Aggregate Function:

SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table.

It returns a single value. 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

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

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

1.Example: COUNT ()

SELECT COUNT (*)


FROM PRODUCT_MAST;

Output:

10

2.Example: COUNT with WHERE

SELECT COUNT (*)


FROM PRODUCT_MAST;
WHERE RATE>=20;
Output:

3.Example: COUNT () with DISTINCT

SELECT COUNT (DISTINCT COMPANY)


FROM PRODUCT_MAST;

Output:

4.Example: COUNT () with GROUP BY

SELECT COMPANY, COUNT (*)


FROM PRODUCT_MAST
GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2

5.Example: COUNT () with HAVING

SELECT COMPANY, COUNT (*)


FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT (*)>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: SUM ()
or
SUM([ALL|DISTINCT] expression)

1.Example: SUM ()

SELECT SUM(COST)
FROM PRODUCT_MAST;

Output:

670

2.Example: SUM () with WHERE

SELECT SUM(COST)
FROM PRODUCT_MASTWHERE QTY>3;

Output:

320

3.Example: SUM () with GROUP BY

SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;

Output:

Com1 150
Com2 170

4.Example: SUM () with HAVING

SELECT COMPANY, SUM(COST)


FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING SUM(COST)>=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

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:

S_ID S_NAME S_ADDRESS S_PHONE S_AGE

S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18


Course:

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.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’

Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’

STEP 2: Using C_ID of step 1 for finding S_ID

Select S_ID from STUDENT_COURSE where C_ID IN (SELECT C_ID from COURSE

where C_NAME = ‘DSA’ or C_NAME=’DBMS’);

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:

Select S_NAME from STUDENT where S_ID IN

(Select S_ID from STUDENT_COURSE where C_ID IN

(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

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:

Select S_ID from STUDENT where S_ID NOT IN

(Select S_ID from STUDENT_COURSE where C_ID IN


(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

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:

Select S_NAME from STUDENT S where EXISTS

(select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);

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 is the process of granting someone to do something. It means it a way to


check if the user has permission to use a resource or not.
 It defines that what data and information one user can access. It is also said as AuthZ.
 The authorization usually works with authentication so that the system could know who
is accessing the information.
 Authorization is not always necessary to access information available over the internet.
Some data available over the internet can be accessed without any authorization, such
as you can read about any technology from here.

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:

2. Entity integrity constraints

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:

3. Referential Integrity Constraints:

o A referential integrity constraint is specified between two tables.


o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.

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:

Sql Join Expression:

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.

Types of SQL JOIN


1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN

Sample Table
EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT

PROJECT_NO EMP_ID DEPARTMENT

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

SELECT table1.column1, table1.column2, table2.column1,....


FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

SELECT table1.column1, table1.column2, table2.column1,....


FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

SELECT table1.column1, table1.column2, table2.column1,....


FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

SELECT table1.column1, table1.column2, table2.column1,....


FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Query

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram

Student_Marks

STU_ID NAME MARKS AGE

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:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;
2. Creating View from a single table
In this example, we create a View named DetailsView from the table Student_Detail.

Query:

CREATE VIEW DetailsView AS


SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;

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
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:

CREATE VIEW MarksView AS


SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of View MarksView:

1. SELECT * FROM MarksView;

NAME ADDRESS MARKS

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

DROP VIEW view_name;


Modification of Databases intermediate:

Modification of the Database The modification of a database has three commands, namely:
DELETE INSERT UPDATE

Sql Datatypes and schema:

Data types mainly classified into three categories for every database.

o String Data types


o Numeric Data types
o Date and time Data types

Data Types in MySQL, SQL Server and


Oracle Databases
MySQL Data Types
A list of data types used in MySQL database. This is based on MySQL 8.0.

MySQL String Data Types

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.

MEDIUMTEXT It holds a string with a maximum length of 16,777,215.

LONGTEXT It holds a string with a maximum length of 4,294,967,295 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.

MySQL Numeric Data Types

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.

INTEGER(size) It is equal to INT(size).

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.

MySQL Date and Time Data Types

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.

Ex: Create SCHEMA sales;

Create object with schema:

CREATE TABLE sales.product {

Product_id INT PRIMARY KEY,

name varchar(255) NOT NULL,

price DECIMAL(10,2) NOT NULL,

quantity INT NOT NULL,


created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

You might also like