Sunteți pe pagina 1din 29

UNIT I

What is database?

The database is a collection of interrelated data which is used to store, retrieve and delete the
data efficiently. It organizes the data in the format of tables.

Example :

1. The college database organizes the data about the staff, students etc.

2. The Banking database organizes customer information, accounts, loans, and banking
transactions.

3. Airlines: For reservations and schedule information.

4. Telecommunication: For keeping records of calls made, generating monthly bills, maintaining
balances on prepaid calling cards.

What is Database Management System?

It is software which is used to manage the database. Example : MySQL, Oracle are very popular
commercial database which is used in different applications.

Purpose of Database Systems

o Controls database redundancy: It can control data redundancy because it stores all the
data in one single database file and that recorded data is placed in the database.
o Data sharing: The authorized users of an organization can share the data among multiple
users.
o Easily Maintenance: It can be easily maintainable due to the centralized nature of the
database system.
o Reduce time: It reduces development time and maintenance need.
o Backup: It provides backup and recovery subsystems which create automatic backup of
data from hardware and software failures and restores the data if required.
o multiple user interface: It provides different types of user interfaces like graphical user
interfaces, application program interfaces.

Views of Data
 Physical level - The lowest level of abstraction describes how the data are actually stored.
 Logical level - The next-higher level of abstraction describes what data are stored in the
database, and what relationships exist among those data.
 View level - The highest level of abstraction describes only part of the entire database. The
view level of abstraction exists to simplify their interaction with the system. The system may
provide many views for the same database.

1
Example: Let’s say we are storing customer information in a customer table.

 At physical level these records can be described as blocks of storage in memory. These
details are often hidden from the programmers.
 At the logical level these records can be described as fields and attributes. The programmers
generally work at this level.
 At view level, user just interacts with system with the help of GUI and enter the details at the
screen.
Data Models
The data model is a collection of conceptual tools for describing data, and data relationships. The
data models can be classified in different categories.

Entity-Relationship Model

The entity-relationship (E-R) data model uses a collection of basic objects, called entities, and
relationships among these objects.

 An entity is a thing or object in the real world.


 Entities are described by set of attributes
 A relationship is an association among several entities.
An E-R diagram has following components.
 Rectangle : which represents entity sets.
 Ellipse: which represents attributes
 Diamonds: which represents relationship among entities.
 Lines: which link attributes to entity sets and entity sets to relationships.

The banking database consists of customers and of the accounts that customers have. Their ER
diagram is shown below.

2
Relational Model.

The relational model uses a collection of tables to represent both data and the relationships
among those data. Each table has multiple columns, and each column has a unique name. A
sample relational database consists of two tables: one shows bank customers and other shows
accounts that belong to those customers.

Database Languages

A database system provides a data-definition language to specify the database schema and a
data-manipulation language to express database queries and updates.

3
Data Definition Language

A database schema is specified by a set of definitions expressed by a special language called a


data definition language. The compilation of DDL statement is a set of tables stored in a special
file called data dictionary. A data dictionary is a file that contains metadata, that is data about
data.

Data-Manipulation Language

A data-manipulation language (DML) is a language that enables users to access or manipulate


data. The types of access are:

 Retrieval of information stored in the database


 Insertion of new information into the database
 Deletion of information from the database
 Modification of information stored in the database

There are basically two types:

 Procedural DMLs require a user to specify what data are needed and. how to get
those data.
 Declarative DMLs (nonprocedural DMLs) require a user to specify what data are
needed without specifying how to get those data.

A query is a statement requesting the retrieval of information. The portion of a DML that
involves information retrieval is called a query language.

Database Architecture
The design of a DBMS depends on its architecture. It can be centralized or decentralized. The
architecture of a DBMS can be seen as either single tier or multi-tier. The tiers are classified as
follows :

 1-tier architecture
 2-tier architecture
 3-tier architecture
In 1-tier architecture, putting all of the required components for a software application or
technology on a single server or platform.

In two-tier architecture, the application is partitioned into a component that resides at the client
machine, which invokes database system functionality at the server machine through query
language statements.

In three-tier architecture, the client machine acts as a front end and does not contain any direct
database calls. Instead, the client end communicates with an application server, usually through
a forms interface. The application server in turn communicates with a database system to
access data.

4
Database Users and Administrators
A primary goal of a database system is to retrieve information from and store new information
into the database. People who work with a database can be categorized as database users or
database administrators.

Database Users and User Interfaces

There are four different types of database-system users, differentiated by the way they expect to
interact with the system. Different types of user interfaces have been designed for the different
types of users.
 Naive users are unsophisticated users who interact with the system by invoking one of the
application programs that have been written previously.
Example: A user who wishes to find her account balance, user may access a form, where she
enters her account number, an application program retrieves the account balance, using the given
account number, and passes this information back to the user.

 Application programmers are computer professionals who write application programs.


 Sophisticated users interact with the system without writing programs. Instead, they form
their requests either using a database query language or by using tools such as data analysis
software.
 Specialized users are sophisticated users who write specialized database applications that do
not fit into the traditional data-processing framework. Applications are computer-aided
design systems, knowledge-base and expert systems, systems that store data with complex
data types.
Database Administrator
DBMS have central control of both the data and the programs that access those data. A person
who has such central control over the system is called a database administrator ( DB A) . The
functions of a DBA include:

5
 Schema definition .The DBA creates the database schema by writing a set of data definition
statements.
 Storage structure and access-method definition. The DBA creates storage structure and
access methods by writing set of definitions.
 Schema and physical-organization modification .The DBA carries out changes to the
schema and physical organization to reflect the changing needs of the organization, or to alter
the physical organization to improve performance.
 Granting of authorization for data access. The database administrator regulate which
parts of the database various users can access.
The Entity-Relationship Model

The E-R data model employs three basic notions: entity sets, relationship sets, and attributes. The
entity-relationship (E-R) model uses a collection of basic objects, called entities, and
relationships among these objects.

Entity Sets

An entity is a thing or object in the real world. An entity set is a set of entities of the same type
that share the same properties, or attributes. An entity is represented by a set of attributes. Each
entity has a value for each of its attributes.

Example:

 The set of all persons who are customers at a given bank can be defined as the entity set
customer.
 The entity set loan represents the set of all loans awarded by a particular bank.
 Possible attributes of the customer entity set are customer-id, customer-name, customer-
street, and customer-city.
 Possible attributes of the loan entity set are loan-number and amount.
 A particular customer entity may have the value 321-72-31,23 for customer-id, the value
Jones for customer name, the value Main for customer-street, and the value Harrison for
customer-city.

6
Attributes
Entities are represented by means of their properties, called attributes. All attributes have
single value or multiple values.

Types of Attributes
 Simple attribute − attributes have values which cannot be divided further. For example, a
student's phone number is an atomic value of 10 digits.
 Composite attribute − This kind of attribute can be divided further to more than one simple
attribute. For example, address of a person. Here address can be further divided as Door#,
street, city, state and pin which are simple attributes.
 Derived attribute − Derived attributes are the one whose value can be obtained from other
attributes of entities in the database. For example, Age of a person can be obtained from date
of birth
 Single-value attribute − These attributes will have only one value. Rollno,
EMPLOYEE_ID, passport, driving license, etc have only single value for a person.
 Multi-value attribute − Multi-value attributes may contain more than one values. For
example, a person can have more than one phone number, email_address, etc.
Relationship
The association among entities is called a relationship. For example, we can define a relationship
that associates customer Hayes with loan L-15. This relationship specifies that Hayes is a
customer with loan number L-15.
ER Diagram Symbols

ER diagram is the pictorial representation of real world objects, it involves various symbols and
notation to draw the diagrams.

 Rectangles, which represent entity sets


 Ellipses, which represent attributes
 Diamonds, which represent relationship sets
 Lines, which link attributes to entity sets and entity sets to relationship sets
 Double ellipses, which represent multivalued attributes
 Dashed ellipses, which denote derived attributes

Consider the entity-relationship diagram in Figure, which consists of two entity sets, customer
and loan, related through a binary relationship set borrower. The attributes associated with
customer are customer-id, customer-name, customer-street, and customer-city. The attributes
associated with loan are loan-number and amount.

7
A composite attribute name, with component attributes first name,middle, and last name
replaces the simple attribute customer-name of customer. A multivalued attribute phone-
number, depicted by a double ellipse, and a derived attribute age, depicted by a dashed ellipse.

8
UNIT II

Relational Databases

A relational database is based on the relational model and uses a collection of tables, each of
which is assigned a unique name to represent both data and the relationships among those data.

Tables

The database uses tables to store data. A table is a collection of related data entries and contains
rows and columns to store data.

Let's see the example of student table.

ID Name AGE COURSE


1 Ajeet 24 B.Com
2 aryan 20 BBA
3 Mahesh 21 BCA
4 Ratan 22 MCA
5 Vimal 26 BSC

Field
Every table is broken up into smaller entities called fields. A field is a column in a table that is
designed to maintain specific information about every record in the table. In the above example,
the field in the student table consists of id, name, age, and course.

Record

A row of a table is also called record. A record is also called as a row of data is each individual
entry that exists in a table. It contains the specific information of each individual entry in the
table. It is a horizontal entity in the table. For example: The above table contains 5 records. Let's
see one record/row in the table.

1 Ajeet 24 B.Com

Column

A column is a vertical entity in the table which contains all information associated with a specific
field in a table. For example: "name" is a column in the above table which contains all
information about student's name.
Ajeet

Aryan

Mahesh

Ratan

Vimal

9
What is Relational Model

The relational model 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.

Relational Model Concepts

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

Keys
Keys are very important part of Relational database model. They are used to establish and
identify relationships between tables and also to uniquely identify any record or row of data
inside a table.
A Key can be a single attribute or a group of attributes, where the combination may act as a key.
Keys help you uniquely identify a row in a table by a combination of one or more columns in
that table.
Let's try to understand about all the keys using a simple example.
Rollno name phone age Aadhar no
1 Ajith 9876723452 17 235645
2 Rajesh 9991165674 19 123456
3 Vimal 7898756543 18 789456
4 Prasanth 8987867898 19 456123
5 Kumar 9990080080 17 123456

10
The database has following types of Keys and each has their different functionality:

 Super Key
 Primary Key
 Candidate Key
 Alternate Key
 Foreign Key

1. Super Key
Super Key is defined as a set of attributes within a table that can uniquely identify each record
within a table. Super Key is a superset of Candidate key.
In the above-given example, Rollno and aadhar number are superkeys.

2. Primary Key

A column or group of columns in a table which helps us to uniquely identifies every row in that
table is called a primary key. The same value can't appear more than once in the table.

Rules for defining Primary key:

 Two rows can't have the same primary key value


 It must for every row to have a primary key value.
 The primary key field cannot be null.

In the above example, Rollno is a Primary Key.

For Example:- Suppose a table consist of Employee data with fields Employee_Name,
Employee_Address,Employee_Id and Employee_Designation so in this table only one field is
there which is used to uniquely identify detail of Employee that is Employee_Id.

3. Alternate key

Alternate key can be defined as a key that can be work as a primary key if required.

For Example:- Suppose a table consist of Employee data with fields Employee_Name,
Employee_Address, Employee_Id , Employee_Designation and Employee_PhoneNo in this case
Employee_PhoneNo can be the alternate key as it is also suitable to identify the record uniquely
but right now it is not primary key.

4. Candidate Key
Candidate keys are defined as the minimal set of fields which can uniquely identify each record
in a table. It is an attribute or a set of attributes that can act as a Primary Key for a table to
uniquely identify each record in that table. There can be more than one candidate key.
In our example, Rollno and phone both are candidate keys for table Student.

 A candiate key can never be NULL or empty. And its value should be unique.
 There can be more than one candidate keys for a table.
 A candidate key can be a combination of more than one columns(attributes).

11
5. Foreign key

A foreign key is a column which is added to create a relationship with another table. A foreign
key is an attribute value in a table that acts as the primary key in another table. Hence, the
foreign key is useful in linking together two tables.

The relation which is being referenced is called referenced relation and the corresponding
attribute is called referenced attribute and the relation which refers to the referenced relation is
called referencing relation and the corresponding attribute is called referencing attribute.

For Example, STUD_NO in STUDENT_COURSE is a foreign key to STUD_NO in STUDENT

relation.

Relational Algebra
Relational algebra is a procedural query language, which takes instances of relations as input
and yields instances of relations as output. It uses operators to perform queries. An operator can
be either unary or binary. They accept relations as their input and yield relations as their
output. Relational algebra is performed recursively on a relation and intermediate results are
also considered relations.
The fundamental operations of relational algebra are as follows −

 Select
 Project
 Union
 Set different
 Cartesian product
 Rename

The select, project and rename operations are called unary operations, because they operate on
one relation. The union, set difference and Cartesian product operate on pairs of relations and
therefore called binary operations.

12
Table 1 : STUDENT
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

1. Select Operation (σ)


Selection operator is used to select tuples from a relation based on some condition.

Syntax: σp(r) or σ (Cond)(Relation Name)


 σ (sigma) stands for selection predicate.
 r stands for relation.
 p is prepositional logic formula which may use connectors like and, or, and not.
 Use relational operators like − =, ≠, ≥, < , >, ≤.
 It selects tuples that satisfy the given condition from a relation.
Example: Extract students whose age is greater than 18 from STUDENT relation.

σ (AGE>18)(STUDENT)
RESULT:
ROLL_NO NAME ADDRESS PHONE AGE
3 SUJIT ROHTAK 9156253131 20

2. Project Operator (∏)


Projection operator is used to project particular columns from a relation. It is denoted by letter pi.
Syntax: ∏(Column 1,Column 2….Column n)(Relation Name)

Where Column 1,Column 2….Column n are attribute names of relation r.


Duplicate rows are automatically eliminated, as relation is a set.
Example: Extract ROLL_NO and NAME from STUDENT relation.

∏ (ROLL_NO,NAME)(STUDENT)

RESULT:

ROLL_NO NAME
1 RAM
2 RAMESH
3 SUJIT
4 SURESH

13
3. Rename(ρ)
Rename (ρ) operation can be used to rename a relation or an attribute of a relation. Rename
operator is used to give another name to a relation. It is denoted by letter rho.
Syntax: ρ(Relation2, Relation1)
To rename STUDENT relation to STUDENT1, we can use rename operator like:
ρ(STUDENT1, STUDENT)
4. Union Operator (∪)

Union operator is denoted by ∪ symbol and it is used to select all the rows (tuples) from two
tables (relations).

Syntax rUs
Where r and s are either database relations

Let’s say we have two relations R and S 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. The
rows (tuples) that are present in both the tables will only appear once in the union set.
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: ∏ Student_Name (COURSE) ∪ ∏ Student_Name (STUDENT)

14
Output:

Student_Name
------------
Aditya
Carl
Paul
Lucy
Rick
Steve

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 (-) table_name1 - table_name2

Query: 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. Let’s 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.

Syntax (X) R1 X R2

Example

Table 1: R

Col_A Col_B
----- ------
AA 100
BB 200
CC 300

15
Table 2: S

Col_X Col_Y
----- -----
XX 99
YY 11
ZZ 101
Query: Lets find the cartesian product of table R and S. R X S

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.

https://beginnersbook.com/2019/02/dbms-relational-algebra/
https://www.guru99.com/relational-algebra-dbms.html
Additional operations are −

 Set intersection
 Division
 Natural join
Intersection Operator (∩)

Intersection operator is denoted by ∩ symbol and it is used to select common rows (tuples) from
two tables (relations).

Lets 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: table_name1 ∩ table_name2

16
Example
Lets 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

NATURAL JOIN (⋈)

Natural join can only be performed if there is a common attribute (column) between the
relations. The name and type of the attribute must be same.

Example

Consider the following two tables

Courses
HoD
CID Course Dept
Dept Head
CS01 Database CS
CS Alex
ME01 Mechanics ME
ME Maya
EE01 Electronics EE
EE Mira

17
Natural Join only if there is at least one common attribute that exists between two
relations.

Courses ⋈ HoD

Dept CID Course Head

CS CS01 Database Alex

ME ME01 Mechanics Maya

EE EE01 Electronics Mira

Division Operation

Division, denoted as , is suited to queries that include the phrase ``for all''.

STUDENT_SPORTS ALL_SPORTS

ROLL_NO SPORTS

1 Badminton SPORTS

2 Cricket Badminton

2 Badminton Cricket

4 Badminton

 To apply division operator as STUDENT_SPORTS÷ ALL_SPORTS


 The attributes in resulting relation will have attributes {ROLL_NO,SPORTS}-
{SPORTS}=ROLL_NO
ROLL_NO

Integrity

Data integrity as a process, used to ensure validity and accuracy of all data contained in a
database. For instance, error checking and validation methods may be referred to as data integrity
processes.

18
Integrity Constraints

o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o 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.
o Thus, integrity constraint is used to guard against accidental damage to the database.

Types of Integrity Constraint


1. Domain constraint
2. Entity integrity constraint
3. Referential integrity constraint
4. Key constraint

1. Domain constraints

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

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

https://www.javatpoint.com/dbms-functional-dependency

20
UNIT III

SQL is Structured Query Language, which is a computer language for storing, manipulating
and retrieving data stored in a relational database.

Basic Data Types


o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
The SQL standard supports a variety of built-in types, including:
1. char (n): A fixed-length character string with user-specified length n.
2. varchar (n): A variable-length character string with user-specified maximum length n.
3. int: An integer value.
4. smallint: A small integer value.
5. 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.,
6. real, double precision : Floating-point and double-precision floating-point numbers.
7. float (n): A floating-point number, with precision of at least n digits.
8. Date: It is used to store the year, month, and days value.
9. Time: It is used to store the hour, minute, and second values.
10. Timestamp: It stores the year, month, day, hour, minute, and the second value.

Database Objects
A database object is any defined object in a database that is used to store or reference data.A
nything which we make from create command is known as Database Object. It can be used to
hold and manipulate the data. Some of the examples of database objects are : view, sequence,
indexes, etc.
 Table – Basic unit of storage; composed rows and columns
 View – Logically represents subsets of data from one or more tables
 Sequence – Generates primary key values
 Index – Improves the performance of some queries
 Synonym – Alternative name for an object

21
DDL: Data Definition Language

DDL stands for Data Definition Language.

 It is a language used for defining and modifying the data and its structure.
 It is used to build and modify the structure of your tables and other objects in the database.

DDL commands are as follows,

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

Create command
 CREATE command is used for creating objects in the database.
 It creates a new table.
 Have to specify the details of the columns of the tables along with their datatypes.
Syntax:
CREATE TABLE <table_name>
(
column_name1 datatype,
column_name2 datatype,
.
.
column_name_n datatype
);
Example :
CREATE TABLE Student(
studentid INT,
name VARCHAR(20),
age INT,
phoneno NUMBER(10)
);

22
The above command will

 create a new table with name Student in the current database with 4 columns,
namely student_id, name,age and phoneno.
 Student_id will only store integer.
 Name will hold upto 20 characters
 Age will again store only integer value
 Phone number will store number values.

ALTER COMMAND
alter command is used for altering the table structure, such as,

 to add a column to existing table


 to rename any existing column
 to change datatype of any column or to modify its size.
 to drop a column from the table.

1. Add a new Column

Using ALTER command we can add a column to any existing table.

Syntax:

ALTER TABLE table_name ADD(column_name datatype);

Example

ALTER TABLE student ADD( address VARCHAR(20));

The above command will add a new column address to the table student, which will hold data of
type varchar of length 20.

2. Modify an existing Column

ALTER command can also be used to modify data type of any existing column.

Syntax

ALTER TABLE table_name modify(column_name datatype);

Example

ALTER TABLE student MODIFY( address varchar(30));

The above command will modify the address column of the student table, to now hold upto 30
characters.

3. Rename a Column

Using ALTER command you can rename an existing column.

23
Syntax

ALTER TABLE <table_name> RENAME

old_column_name TO new_column_name;

Example

ALTER TABLE student RENAME

address TO location;

The above command will rename address column to location.

4. Drop a Column

ALTER command can also be used to drop or remove columns.

Syntax

ALTER TABLE <table_name> DROP(column_name);

Example

ALTER TABLE student DROP( address);

The above command will drop the address column from the table student.

 To view the changed structure of table, use 'DESCRIBE' command.


 For example:
 DESCRIBE TABLE employee;

DROP command
 DROP command completely removes a table from the database.
 It also destroys the table structure and the data stored in it.

Syntax

DROP TABLE <table_name>; or DROP DATABASE <database_name>;


Example

DROP TABLE student;

The above query will delete the Student table completely.

 It can also be used on Databases, to delete the complete database. For example, to drop a
database,

DROP DATABASE Test;

The above query will drop the database with name Test from the system.

24
RENAME command
RENAME command is used to set a new name for any existing table.

Syntax

RENAME TABLE old_table_name to new_table_name

Example

RENAME TABLE student to students_info;

The above query will rename the table student to students_info.

TRUNCATE command
 TRUNCATE command is used to delete all the rows from the table permanently.
 But this command will not destroy the table's structure.
 It removes all the records from a table, including all spaces allocated for the records.
 This command is same as DELETE command, but TRUNCATE command does not
generate any rollback data.
Syntax

TRUNCATE TABLE table_name

Example

TRUNCATE TABLE student;

The above query will delete all the records from the table student.

DML

 DML stands for Data Manipulation Language.


 DML commands are used for manipulating the data stored in the table and not the table itself.
 It is a language used for selecting, inserting, deleting and updating data in a database.
 It is used to retrieve and manipulate data in a relational database.

DML commands are as follows,

Command Description

insert Creates a record

update Modifies a record

delete Deletes records

Select Retrieves records from tables.

25
INSERT command
Insert command is used to insert data into a table. Using this command, you can add one or more
records to any single table in a database.

Syntax
INSERT INTO <table_name> VALUES (`value1`, `value2`, . . . , `value n`);

Example
Consider a table student with the following fields.
studentid name age

INSERT INTO student VALUES(101, 'Adam', 15);

The above command will insert a new record into student table.
studentid name age

101 Adam 15

UPDATE command
 UPDATE command is used to modify the records present in existing table.
 This command updates existing data within a table.
 It changes the data of one or more records in a table.
Syntax:

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

Example: Lets take a sample table student,


student_id name age

101 Adam 15

102 Alex 20

UPDATE student SET age=18 WHERE student_id=102;

studentid S_Name age

101 Adam 15

102 Alex 18

In the above statement, if we do not use the WHERE clause, then our update query will
update age for all the columns of the table to 18.

26
DELETE command
DELETE command is used to used to delete data from a table. Itdelete some or all records from
the existing table.
Syntax:
DELETE FROM <table_name> WHERE <condition>;
Example :
1. DELETE FROM student WHERE s_id=103;
The above command will delete the record where s_id is 103 from the table student.
2. DELETE FROM student;
The above command will delete all the records from the table student.
SELECT COMMAND
 SELECT command is used to retrieve data from the table.
 This command allows database users to retrieve the specific information.
 It returns a result set of records from one or more tables.
Syntax: SELECT * FROM <table_name>;
Example : SELECT * FROM student;
The above query will show all the records of student table, that means it will show
complete dataset of the table.
studentid name age address
101 Adam 15 Chennai
102 Alex 18 Delhi
103 Abhi 17 Banglore
104 Ankit 22 Mumbai

SELECT s_id, name, age FROM student;

The above query will fetch information of studentid, name and age columns of
the student table and display them,
studentid name age

101 Adam 15

102 Alex 18

103 Abhi 17

104 Ankit 22

27
DCL

 DCL stands for Data Control Language.


 DCL is used to control user access in a database.
 This command is related to the security issues.
 Using DCL command, it allows or restricts the user from accessing data in database.

DCL commands are as follows,


Command Description

grant Gives a privilege to user.

Granting permission of right

revoke take back permission.

Takes back privileges granted from user.

1. GRANT COMMAND

 GRANT command gives user's access privileges to the database.


 This command allows specified users to perform specific tasks.

Syntax:

GRANT <privilege list>

ON <relation name or view name>

TO <user/role list>;
Example: GRANT SELECT, UPDATE ON STUDENT TO SOME_USER, ANOTHER_USER;

2. REVOKE COMMAND

 REVOKE command is used to cancel previously granted or denied permissions.


 This command withdraws access privileges given with the GRANT command.
 It takes back permissions from user.

Syntax:

REVOKE <privilege list>

ON <relation name or view name>

FROM <user name>;


Example: REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

28
TCL - Transaction Control Language.

 TCL stands for Transaction Control Language.


 This command is used to manage the changes made by DML statements.
 TCL allows the statements to be grouped together into logical transactions.

TCL commands are as follows:

Command Description

commit to permanently save

rollback to undo change

savepoint to save temporarily

Commit: Commit command is used to save all the transactions to the database.

Syntax: COMMIT;

Example:

DELETE FROM CUSTOMERS WHERE AGE = 25;


COMMIT;

Rollback: Rollback command is used to undo transactions that have not already been saved to
the database.

Syntax: ROLLBACK; ROLLBACK TO SAVEPOINT <savepoint_name>;

Example:

DELETE FROM CUSTOMERS WHERE AGE = 25;


ROLLBACK;

SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.

Syntax: SAVEPOINT SAVEPOINT_NAME;

Select a particular record based on a conditionWe can use the WHERE clause to set a condition,

SELECT * FROM student WHERE name = 'Abhi';

The above query will return the following result,

103 Abhi 17 Rohtak


OLUT

29

S-ar putea să vă placă și