0% found this document useful (0 votes)
70 views36 pages

DBMS_2_UNIT- aktu

Uploaded by

paswanraja802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views36 pages

DBMS_2_UNIT- aktu

Uploaded by

paswanraja802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Unit_2 Relational Data Model and Languages

Relational data Model and Language: Relational Data Model Concepts, Integrity Constraints, Entity
Integrity, Referential Integrity, Keys Constraints, Domain Constraints, Relational Algebra, Relational
Calculus, Tuple and Domain Calculus. Introduction on SQL: Characteristics of SQL, Advantage of SQL.
SQL Data Type and Literals. Types of SQL Commands. SQL Operators and Their Procedure. Tables,
Views and Indexes. Queries and Sub Queries. Aggregate Functions. Insert, Update and Delete
Operations, Joins, Unions, Intersection, Minus, Cursors, Triggers, Procedures in SQL/PL SQL

Relation
A relation, also known as a table or file, is a subset of the Cartesian product of a list of domains characterized
by a name. And within a table, each row represents a group of related data values. A row, or record, is also
known as a tuple. The columns in a table is a field and is also referred to as an attribute.
The steps below outline the logic between a relation and its domains.
Given n domains are denoted by D1, D2, … Dn
And r is a relation defined on these domains

A Relational Database management System (RDBMS) is a database management system based on the
relational model introduced by E.F Codd. In relational model, data is stored in relations (tables) and is
represented in form of tuples (rows).
RDBMS is used to manage Relational database. Relational database is a collection of organized set of tables
related to each other, and from which data can be accessed easily. Relational Database is the most commonly
used database these days.
Relational Model:
RELATIONAL MODEL (RM) represents the database as a collection of relations. A relation is nothing but
a table of values. Every row in the table represents a collection of related data values. These rows in the table
denote a real-world entity or relationship.
The table name and column names are helpful to interpret the meaning of values in each row. The data are
represented as a set of relations. In the relational model, data are stored as tables. However, the physical
storage of the data is independent of the way the data are logically organized.
1. Attribute: Each column in a Table. Attributes are the properties which define a relation.
e.g., Student_Rollno, NAME,etc.
2. Tables – In the Relational model the relations are saved in the table format. It is stored
along with its entities. A table has two properties rows and columns. Rows represent
records and columns represent attributes.
3. Tuple – It is nothing but a single row of a table, which contains a single record.
4. Relation Schema: A relation schema represents the name of the relation with its
attributes.
5. Degree: The total number of attributes which in the relation is called the degree of the
relation.
6. Cardinality: Total number of rows present in the Table.
7. Column: The column represents the set of values for a specific attribute.
8. Relation instance – Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
9. Relation key - Every row has one, two or multiple attributes, which is called relation
key.
10. Attribute domain – Every attribute has some pre-defined value and scope which is
known as attribute domain

RDBMS: What is Table?


In Relational database model, a table is a collection of data elements organised in terms of rows and columns.
A table is also considered as a convenient representation of relations. But a table can have duplicate row of
data while a true relation cannot have duplicate data. Table is the most simplest form of data storage. Below is
an example of an Employee table.
D Name Age Salary
1 Adam 34 13000
2 Alex 28 15000

RDBMS: What is a Tuple?


A single entry in a table is called a Tuple or Record or Row. A tuple in a table represents a set of
related data. For example, the above Employee table has 4 tuples/records/rows.
Following is an example of single record or tuple.

1 Adam 34 13000

RDBMS: What is an Attribute?


A table consists of several records(row), each record can be broken down into several smaller parts of data
known as Attributes. The above Employee table consist of four attributes, ID, Name, Age and Salary.
Attribute Domain
When an attribute is defined in a relation (table), it is defined to hold only a certain type of values, which is
known as Attribute Domain.
Hence, the attribute Name will hold the name of employee for every tuple. If we save employee's address
there, it will be violation of the Relational database model.

Name
Adam
Alex
Stuart - 9/401, OC Street, Amsterdam
Ross
Constraints in Relational Model
While designing Relational Model, we define some conditions which must hold for data present in database
are called Constraints. These constraints are checked before performing any operation (insertion, deletion and
updation) in database. If there is a violation in any of constrains, operation will fail.

1. Domain constraints:

• Domain constraints can be defined as the definition of a valid set of values for an
attribute.
• 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:

• The entity integrity constraint states that primary key value can't be null.
• 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.
• A table can contain a null value other than the primary key field.

Example:
3. Referential Integrity Constraints:

• A referential integrity constraint is specified between two tables.


• 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

• Keys are the entity set that is used to identify an entity within its entity set
uniquely.
• 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:
RELATION ALGEBRA:
Relational algebra is a set of basic operations used to manipulate the data in relational model. These
operations enable the user to specify basic retrieval request. The result of retrieval is a new relation,
formed from one or more relation. These operations can be classified in two categories.

Basic/Fundamental Operations:
1. Select (σ)
2. Project (∏)
3. Union (𝖴)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)
Derived Operations:
1. Natural Join (⋈)
2. Left, Right, Full outer join (⟕, ⟖, ⟗)
3. Intersection (∩)
4. Division (÷)

Select Operator (σ)


Select Operator is denoted by sigma (σ) and it is used to find the tuples (or rows) in a relation (or table)
which satisfy the given condition. If you understand little bit of SQL then you can think of it as a where
clause in SQL, which is used for the same purpose.
Syntax of Select Operator (σ)
σ Condition/Predicate(Relation/Table name)
Select Operator (σ) Example
Table: CUSTOMER
-
Customer_Id Customer_Name Customer_City
-
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi
Query:
σ Customer_City="Agra" (CUSTOMER)
Output:
Customer_Id Customer_Name Customer_City
- -
C10100 Steve Agra
C10111 Raghu Agra

Project Operator (∏)


Project operator is denoted by ∏ symbol and it is used to select desired columns
(or attributes) from a table (or relation). Project operator in relational algebra is
similar to the Select statement in SQL.
Syntax of Project Operator (∏)
∏ column_name1, column_name2, .... , column_nameN(table_name)
Project Operator (∏) Example
In this example, we have a table CUSTOMER with three columns, we want to
fetch only two columns of the table, which we can do with the help of Project
Operator ∏.

Table: CUSTOMER

Customer_Id Customer_Name Customer_City


-
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi
Query:

∏ Customer_Name, Customer_City (CUSTOMER)


Output:

Customer_Name Customer_City

Steve Agra
Raghu Agra
Chaitanya Noida
Ajeet Delhi
Carl Delhi
Union Operator (𝖴):
Union operator is denoted by 𝖴 symbol and it is used to select all the rows (tuples) from two
tables (relations).
Lets discuss union operator a bit more. Let’s say we have two relations R1 and R2 both have
same columns and we want to select all the tuples(rows) from these relations then we can apply
the union operator on these relations.
Note: The rows (tuples) that are present in both the tables will only appear once in the union set.
In short you can say that there are no duplicates present after the union operation.
Syntax of Union Operator (𝖴)
table_name1 𝖴 table_name2 Union
Operator (𝖴) Example Table 1:
COURSE
Course_Id Student_Name Student_Id
-
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucy S931
Table 2: STUDENT
Student_Id Student_Name Student_Age

S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucy 17
S941 Carl 16
S951 Rick 18
Query:
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
Output:
Student_Name

Aditya
Carl
Paul
Lucy
Rick
Steve
Note: As you can see there are no duplicate names present in the output even
though we had few common names in both the tables, also in the COURSE table
we had the duplicate name itself.

Intersection Operator (∩)


Intersection operator is denoted by ∩ symbol and it is used to select common rows
(tuples) from two tables (relations).
Let’s say we have two relations R1 and R2 both have same columns and we want
to select all those tuples(rows) that are present in both the relations, then in that
case we can apply intersection operation on these two relations R1 ∩ R2.
Note: Only those rows that are present in both the tables will appear in the result
set.
Syntax of Intersection Operator (∩)
table_name1 ∩ table_name2
Intersection Operator (∩) Example
Let’s take the same example that we have taken above.
Table 1: COURSE

Course_Id Student_Name Student_Id


- -
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucy S931
Table 2: STUDENT

Student_Id Student_Name Student_Age


-
S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucy 17
S941 Carl 16
S951 Rick 18
Query:

∏ Student_Name (COURSE) ∩ ∏ Student_Name (STUDENT)


Output:

Student_Name

Aditya
Steve
Paul
Lucy

Set Difference (-)

Set Difference is denoted by – symbol. Let’s say we have two relations R1 and R2
and we want to select all those tuples (rows) that are present in Relation R1
but not present in Relation R2, this can be done using Set difference R1 – R2.

Syntax of Set Difference (-)


table_name1 - table_name2
Set Difference (-) Example
Lets take the same tables COURSE and STUDENT that we have seen above.

Query:
Lets write a query to select those student names that are present in STUDENT
table but not present in COURSE table.

∏ Student_Name (STUDENT) - ∏ Student_Name (COURSE)


Output:
Student_Name

Carl
Rick

Cartesian product (X)


Cartesian Product is denoted by X symbol. Lets say we have two relations R1 and R2 then the
cartesian product of these two relations (R1 X R2) would combine each tuple of first relation
R1 with the each tuple of second relation R2. I know it sounds confusing but once we take an
example of this, you will be able tounderstand this.
Syntax of Cartesian product (X)
R1 X R2
Cartesian product (X) Example
Table 1: R
Col_A Col_B

AA 100
BB 200
CC 300
Table 2: S
Col_X Col_Y

XX 99
YY 11
ZZ 101
Query:
Lets find the cartesian product of table R and S.
RXS
Output:
Col_A Col_B Col_X Col_Y
-
AA 100 XX 99
AA 100 YY 11
AA 100 ZZ 101
BB 200 XX 99
BB 200 YY 11
BB 200 ZZ 101
CC 300 XX 99
CC 300 YY 11
CC 300 ZZ 101
Note: The number of rows in the output will always be the cross product of
number of rows in each table. In our example table 1 has 3 rows and table 2 has 3
rows so the output has 3×3 = 9 rows.

Rename (ρ)
Rename (ρ) operation can be used to rename a relation or an attribute of a relation.
Rename (ρ) Syntax:
ρ(new_relation_name, old_relation_name)
Rename (ρ) Example
Let’s say we have a table customer, we are fetching customer names and we are
renaming the resulted relation to CUST_NAMES.
Table: CUSTOMER
Customer_Id Customer_Name Customer_City
- -
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi
Query:
ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Output:
CUST_NAMES

Steve
Raghu
Chaitanya
Ajeet
Carl

Relational Calculus:
Relational calculus is a non-procedural query language that tells the system what data
to be retrieved but doesn’t tell how to retrieve it.

Note: A non-procedural query language is a programming language that requires the programmer
to specify what the program should do, rather than how to do it. Non-procedural languages are also
known as declarative languages.
Tuple Relational Calculus (TRC):
Tuple Relational Calculus (TRC) is a non-procedural query language used in relational
databases, where queries are expressed using variables that represent tuples. Unlike SQL, where you
specify how to retrieve data (procedural), TRC specifies what data to retrieve without specifying the
exact procedures or steps to get the result.
In TRC, user describe the properties of the result, rather than how to compute it. The result of the
query is a set of tuples that satisfy the specified conditions.
In tuple calculus, a query is expressed as
{t|P(t)} OR {t|Condition(t)}..
Where:
• t is a tuple variable representing a tuple in the result.
• P(t) is a predicate (condition) that must be satisfied by the tuple t.
First_Name Last_Name Age
-
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28
Lets write relational calculus queries.
Query to display the last name of those students where age is greater than 30

{ t.Last_Name | Student(t) AND t.age > 30 }


In the above query you can see two parts separated by | symbol. The second part is where we define the
condition and in the first part we specify the fields which we want to display for the selected tuples.
The result of the above query would be:
Last_Name
-
Singh
Query to display all the details of students where Last name is ‘Singh’
{ t | Student(t) AND t.Last_Name = 'Singh' }
Output:
First_Name Last_Name Age
-
Ajeet Singh 30
Chaitanya Singh 31

Domain Relational Calculus (DRC):


Domain Relational Calculus (DRC) is another form of relational calculus, similar to Tuple Relational
Calculus (TRC), but it focuses on the domain of the attributes rather than entire tuples. Instead of using
tuple variables, DRC uses variables that represent values from individual attributes (columns) in a relation.

In DRC, queries specify conditions on individual fields or domains of relations, and the result is a set of
domain variables (values) that satisfy these conditions.

In domain relational calculus the records are filtered based on the domains. Again we take the
same table to understand how DRC works.Table: Student
First_Name Last_Name Age
Ajeet Singh 30
Chaitanya Singh 31
Rajeev Bhatia 27
Carl Pratap 28

Query to find the first name and age of students where student age is greater than27
{< First_Name, Age > | ∈ Student 𝖠 Age > 27}
Note:
The symbols used for logical operators are: 𝖠 for AND, ∨ for OR and ┓ for NOT.
Output:
First_Name Age

Ajeet 30
Chaitanya 31
Carl 28

Introduction to SQL
Structure Query Language (SQL) is a database query language used for storing and managing data in Relational
DBMS. SQL was the first commercial language introduced for E.F Codd's Relational model of database. Today
almost all RDBMS (MySql, Oracle, Infomix, Sybase, MS Access) use SQL as the standard database query
language. SQL is used to perform all types of data operations in RDBMS.

SQL Command
SQL defines following ways to manipulate data stored in an RDBMS.
DDL: Data Definition Language
This includes changes to the structure of the table like creation of table,altering table, deleting a
table etc.
All DDL commands are auto-committed. That means it saves all thechanges permanently in the
database.
Command Description
Create to create new table or database
Alter for alteration
Truncate delete data from table
Drop to drop a table
Rename to rename a table

DML: Data Manipulation Language


DML commands are used for manipulating the data stored in the table and not the table itself.
DML commands are not auto-committed. It means changes are not permanent to database, they can
be rolled back.
Command Description
Insert to insert a new row
Update to update existing row
delete to delete a row
merge merging two rows or two tables

TCL: Transaction Control Language


These commands are to keep a check on other commands and their affect on the database. These
commands can annul changes made by other commands by rolling the data back to its original state.
It can also make any temporary change permanent.
Command Description
commit to permanently save
rollback to undo change
savepoint to save temporarily

DCL: Data Control Language


Data control languages are the commands to grant and take back authority from any database user.
Command Description
grant grant permission of right
revoke take back permission.

DQL: Data Query Language: Data query language is used to fetch data from tables based on conditions that we
can easily apply.
Command Description
select retrieve records from one or more table
SQL Syntax
A database is a organized collection of data. Data is stored in relational database in form of tables. To
create, retrieve, update and delete from relational database, we use SQL queries.
SQL Statements
SQL statement tells the database that what information you would like toretrieve or what operation
you want to perform on the data.
For example:
Consider this table: STUDENT
STUDENT_NAME STU_AGE STU_ADDRESS
- -
Ajeet 30 Chennai
Chaitanya 31 Noida
Steve 29 Agra
Rahul 30 Gurgaon
SQL statement to fetch STUDENT_NAME from the table STUDENT:
SELECT STUDENT_NAME FROM STUDENT;

To fetch the complete table:


SELECT * FROM STUDENT;

SQL is NOT case sensitive:


SQL is not a case sensitive language. For example: Both the following statements would work
fine and produce the same output:
select * from student;
&
SELECT * FROM STUDENT;

Syntax of Most Important SQL CommandsSQL


SELECT Statement
The SELECT statement is used to select data from a database. The data returned isstored in a
result table, called the result-set.
To fetch the data from table
SELECT column_name1, column_name2....column_nameN
FROM table_name;

SQL WHERE Clause


The WHERE clause is used to filter records. The WHERE clause is used to extractonly those
records that fulfill a specified condition.
TO fetch the specific rows from the table that meets the given condition.
SELECT column_name1, column_name2....column_nameN
FROM table_name
WHERE CONDITION;

SQL ORDER BY Clause


The ORDER BY keyword is used to sort the result-set in ascending or descendingorder.
The ORDER BY keyword sorts the records in ascending order by default. To sortthe records in
descending order, use the DESC keyword.
To fetch the records in a particular order
SELECT column_name1, column_name2....column_nameN
FROM table_name
ORDER BY column_name1, column_name2, .... {ASC|DESC};

SQL GROUP BY Clause


The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".

SELECT COUNT(column_name) FROM table_name


WHERE CONDITION
GROUP BY column_name;

SQL DISTINCT Clause


The SELECT DISTINCT statement is used to return only distinct (different)values.
Inside a table, a column often contains many duplicate values; and sometimes youonly want to
list the different (distinct) values.

To fetch distinct values of column from the table.


SELECT DISTINCT column_name1, column_name2 ... column_nameN
FROM table_name;
SQL CREATE TABLE Statement
To create the table in the database.
CREATE TABLE table_name( CREATE TABLE Persons (
column_name1 data_type, PersonID int,
column_name2 data_type, LastName varchar(255),
..... FirstName varchar(255),
..... Address varchar(255), City
column_nameN data_type, varchar(255)
PRIMARY KEY(column(s)) );
);

SQL INSERT INTO Statement: The INSERT INTO statement is used to insert new records
in a table.To insert a record into the table.
INSERT INTO table_name( column_name1, column_name2 ....column_nameN)
VALUES (value_1, value_2 .... value_N);

Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country


89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B
90 Wilman Kala Matti Keskuskatu 45 Helsinki 21240 Finland
Karttunen
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country
89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B
90 Wilman Kala Matti Keskuskatu 45 Helsinki 21240 Finland
Karttunen
91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
92 Cardinal Tom B. Skagen 21 Stavanger 4006 Norway
Erichsen

SQL UPDATE Statement


The UPDATE statement is used to modify the existing records in a table.
To update data in table.
UPDATE table_name
SET column_name1 = value_1, column_name2 =
value_2 ... column_nameN=value_N
WHERE CONDITION;

Below is a selection from the "Customers" table in the Northwind sample database:

Custo CustomerName ContactName Address City PostalCode Country


merID
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la MéxicoD.F. 05021 Mexico


Emparedados Constitución
yhelados 2222

3 Antonio Moreno Antonio Mataderos 2312 MéxicoD.F. 05023 Mexico


Taquería Moreno

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds Christina Berguvsvägen 8 Luleå S-958 22 Sweden


snabbköp Berglund
The following SQL statement updates the first customer (CustomerID = 1) with a
new contact person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
Customer Customer Contact Address City Postal Countr
ID Name Name Code y
1 Alfreds Alfre Obere Str. Frankfu 12209 German
Futterki d 57 rt y
ste Schm
idt
2 Ana Trujillo Ana Trujillo Avda. de Méxi 05021 Mexico
Emparedado la co
s yhelados Constituci D.F.
ón 2222
3 Antonio Anto Matader Méxi 05023 Mexico
Moreno nio os2312 co
Taquería More D.F.
no
4 Around the Thom 120 London WA1 1DP UK
Horn as Hanover
Hard Sq.
y
5 Berglun Christi Berguvsväg Luleå S-958 22 Sweden
ds na en8
snabbk Berglu
öp nd

UPDATE Multiple Records


It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the contactname to "Juan" for all records
where country is "Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country

1
Alfreds Futterkiste Alfred Obere Str. 57 Frankfurt 12209 Germany
Schmidt
Ana Trujillo Juan Avda. de la México
2 Emparedados y Constitución D.F. 05021 Mexico
helados 2222

Antonio Moreno Juan Mataderos 2312 México


3 Taquería D.F. 05023 Mexico

Around the Horn Thomas Hardy 120 Hanover London


4 Sq. WA1 1DP UK

Berglunds Christi na Berguvsvägen 8 Luleå


5 snabbköp Berglund S-958 22 Sweden

UPDATE Customers
SET ContactName='Juan'; } What will happen?
SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will be deleted!

To delete rows from table.


DELETE FROM table_name
WHERE CONDITION;
Below is a selection from the "Customers" table sample database:

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds Christina Berguvsvägen 8 Luleå S-958 22 Sweden


snabbköp Berglund

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

The "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222

3 Antonio Moreno Antonio Mataderos México 05023 Mexico


Taquería Moreno 2312 D.F.

4 Around the Horn Thomas Hardy 120 Hanover London WA1 1DP UK
Sq.
5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden
snabbköp Berglund 8

Delete All Records


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:
DELETE FROM Customers;

SQL DROP TABLE Statement


The SQL DROP TABLE statement is used to remove a table definition and all the data.
NOTE − You should be very careful while using this command because once a table is deleted
then all the information available in that table will also be lost forever.

To delete the table completely from database.


DROP TABLE table_name;

SQL TRUNCATE TABLE Statement


To delete all the records from the table.
TRUNCATE TABLE table_name;

Difference between DROP and TRUNCATE in SQL:


S.NO DROP TRUNCATE
1. The DROP command is used to remove table Whereas the TRUNCATE
definition and its contents. command is used to delete all the
rows from the table.
2. In the DROP command, table space is freed While the TRUNCATE command
from memory. does not free the table space from
memory.
3. DROP is a DDL(Data Definition Language) Whereas the TRUNCATE is also a
command. DDL(Data Definition Language)
command.
4. In the DROP command, view of table does not While in this command, view of
exist. table exist.
5. In the DROP command, integrity constraints While in this command, integrity
will be removed. constraints will not be removed.
6. In the DROP command, undo space is not used. While in this command, undo space
is used but less than DELETE.

SQL Data Types


The data type of a column defines what value the column can hold: integer, character, money,
date and time, binary, and so on.
An SQL developer must decide what type of data that will be stored inside each column when
creating a table. The data type is a guideline for SQL to understand what type of data is expected
inside of each column, and it also identifies how SQL will interact with the stored data.
Data types mainly classified into three categories for every database.

o String Data types


o Numeric Data types
o Date and time Data types

String Data Types

CHAR(Size) It is used to specify a fixed length string that can contain numbers, letters,
and special 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, letters,
and special 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 specifies
the column length in the bytes. Default is 1.
VARBINARY(Size) It is equal to VARCHAR() but stores binary byte strings. Its size parameter
specifies the 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.
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
val3,...) possible values. It contains 65535 values in an ENUM list. If you insert a value
that is not in the list, a blank value will be inserted.
SET( It is used to specify a string that can have 0 or more values, chosen from a list of
val1,val2,val3, ... ) possible values. You can list up to 64 values at one time in a SET list.

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
size can be 1 to 64. The default value is 1.

INT(size) It is used for the integer value.

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 total
number of 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 determine
whether to use FLOAT or DOUBLE. If p is between 0 to24, the data type becomes
FLOAT (). If p is from 25 to 53, the data type becomes DOUBLE().
MySQL Date and Time Data Types

DATE It is used to specify date format YYYY-MM-DD. Its supported range is from
'1000-01-01' to '9999-12-31'.

DATETIME(fsp) It is used to specify date and time combination. Its format is YYYY-MM-DD
hh:mm:ss. Its supported range is from '1000-01-01 00:00:00' to 9999-12-31
23:59:59'.

Literals: Literals are the notations or idea to represent/express a non-changing value. In


MySQL, literals are similar to the constant. We can use a literal while declaring a variable or
executing the queries.

String Literals:
String literals are always surrounded by single quotes (').
For example:
'TechOnTheNet.com'
'This is a literal'
'XYZ'
'123'

These string literal examples contain of strings enclosed in single quotes.

Integer Literals:
Integer literals can be either positive numbers or negative numbers, but do not
contain decimals. If you do not specify a sign, then a positive number is assumed.
Here are some examples of valid integer literals:
536
+536
-536

Decimal Literals:
Decimal literals can be either positive numbers or negative numbers and contain
decimals. If you do not specify a sign, then a positive number is assumed. Here are
some examples of valid decimal literals:
24.7
+24.7
-24.7
Datetime Literals:
Datetime literals are character representations of datetime values that are enclosed
in single quotes. Here are some examples of valid datetime literals:
'April 30, 2015'
'2015/04/30'
'2015/04/30 08:34:25'

Operator in SQL: Operator is a reserved word or a character used primarily in an SQL


statement WHERE clause to perform operations, such as comparisons and arithmetic operations.
In another word operators are used inside an expression or condition to specify particular
operations. Generally there are three types of operators in SQL:
1. SQL Arithmetic Operators
2. SQL Comparison Operators
3. SQL Logical Operators

SQL Arithmetic Operators:


Let's assume two variables "a" and "b". Here "a" is valued 50 and "b" valued 100.
Example:

Operators Descriptions Examples


+ It is used to add containing values of both operands a+b will give 150

- It subtracts right hand operand from left hand operand a-b will give -50
* It multiply both operand's values a*b will give 5000
/ It divides left hand operand by right hand operand b/a will give 2
% It divides left hand operand by right hand operand and returns reminder b%a will give 0

SQL Comparison Operators:


Let's take two variables "a" and "b" that are valued 50 and 100.

Operato Description Example


r
= Examine both operands value that are equal or not,if yes (a=b) is not
condition become true. true
!= This is used to check the value of both operands equal or not,if (a!=b) is
not condition become true. true
<> Examines the operand's value equal or not, if values are not (a<>b) is
equal condition is true true
> Examine the left operand value is greater than right Operand, if (a>b) is not
yes condition becomes true true
< Examines the left operand value is less than right Operand, if (a<=""
yes condition becomes true td="">
>= Examines that the value of left operand is greater than or equal to the value (a>=b) is not
of right operand or not, if yes condition become true true
<= Examines that the value of left operand is less than or equal to the value of (a<=b) is true
right operand or not, if yes condition becomes true
!< Examines that the left operand value is not less than the right operand value (a!<="" td="">
!> Examines that the value of left operand is not greater than the value of right (a!>b) is true
operand

SQL Logical Operators:


This is the list of logical operators used in SQL.

Operator Description
ALL This is used to compare a value to all values in another value set.
AND This operator allows the existence of multiple conditions in an SQL
statement.
ANY This operator is used to compare the value in list according to the
condition.
BETWEEN This operator is used to search for values, that are within a set of values.
IN This operator is used to compare a value to that specified list value.
NOT The NOT operator reverse the meaning of any logical operator.
OR This operator is used to combine multiple conditions in SQL statements
EXISTS The EXISTS operator is used to search for the presence of a row in a
specified table.
LIKE This operator is used to compare a value to similar values using
wildcard operator.
Views: Views in SQL are kind of virtual tables. A view also has rows and columns as they are in
a real table in the database. We can create a view by selecting fields from one or more tables
present in the database. A View can either have all the rows of a table or specific rows based on
certain condition.

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;
NAME ADDRESS
Just like table query, we can query the view to view the data.
Stephan Delhi
SELECT * FROM DetailsView;
Kathrin Noida
Output:
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:


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

If we want to delete the View MarksView, we can do this as:


DROP VIEW MarksView;

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.

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.

1. Create Index statement


It is used to create an index on a table. It allows duplicate value.

Syntax

CREATE INDEX index_name


ON table_name (column1, column2, ...);
Example
CREATE INDEX idx_name
ON Persons (LastName, FirstName);

2. Unique Index statement: It is used to create a unique index on a table. It does not
allow duplicate value.

Syntax
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);

Example
CREATE UNIQUE INDEX websites_idx
ON websites (site_name);
3. Drop Index Statement
It is used to delete an index in a table.

Syntax
DROP INDEX index_name;

Example
DROP INDEX websites_idx;

SQL JOIN: SQL Join is used to fetch data from two or more tables, which is joined to appear
as single set of data. It is used for combining column from two or more tables by using values
common to both tables.
JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to itself,
which is known as, Self Join.

Types of JOIN:
Following are the types of JOIN that we can use in SQL:
• Inner
• Outer
• Left
• Right
Sample Table:

INNER JOIN
Let’s say we wanted to get a list of those customers who placed an order and the details of the
order they placed. This would be a perfect fit for an inner join, since an inner join returns records
at the intersection of the two tables.

Sayntax
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;
Left Join
If we wanted to simply append information about orders to our customers table,
regardless of whether a customer placed an order or not, we would use a left join. A left
join returns all records from table A and any matching records from table B.

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;
Right Join
Right join is a mirror version of the left join and allows to get a list of all orders,
appended with customer information.

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;

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;
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further
into,
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join

LEFT Outer Join


The left outer join returns a result set table with the matched data from the two tables
and then the remaining rows of the left table and null from the right table's columns.
Syntax for Left Outer Join is,
SELECT column-name-list FROM
table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
To specify a condition, we use the ON keyword with Outer Join.
Left outer Join Syntax for Oracle is,
SELECT column-name-list FROM
table-name1, table-name2 on table-name1.column-name = table-name2.column-name(+);
Left Outer Join query will be,

SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id = class_info.id);

The result set table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null

RIGHT Outer Join:


The right outer join returns a resultset table with the matched data from the two tables
being joined, then the remaining rows of the right table and null for the
remaining left table's columns.
Syntax for Right Outer Join is,
SELECT column-name-list FROM
table-name1 RIGHT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
Right outer Join Syntax for Oracle is,
SELECT column-name-list FROM
table-name1, table-name2
ON table-name1.column-name(+) = table-name2.column-name;

Example of Right Outer Join


Once again the class table,

Right Outer Join query will be,

SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id =


class_info.id);

The resultant table will look like,

ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
null null 7 NOIDA
null null 8 PANIPAT

RIGHT Outer Join:


The right outer join returns a resultset table with the matched data from the two tables being
joined, then the remaining rows of the right table and null for the remaining left
table's columns.
Syntax for Right Outer Join is,
SELECT column-name-list FROM
table-name1 RIGHT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
Right outer Join Syntax for Oracle is,
SELECT column-name-list FROM
table-name1, table-name2
ON table-name1.column-name(+) = table-name2.column-name;
Example of Right Outer Join
Once again the class table,

Right Outer Join query will be,


SELECT * FROM class RIGHT OUTER JOIN class_info ON (class.id = class_info.id);
The resultant table will look like,

ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
null null 7 NOIDA
null null 8 PANIPAT

You might also like