0% found this document useful (0 votes)
22 views23 pages

Dbms

Uploaded by

apolloop6t9
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)
22 views23 pages

Dbms

Uploaded by

apolloop6t9
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/ 23

E-SCHOOL

DBMS concepts and SQL


Relational Database
A relational database is a collection of data items organized as logically related
tables.

Relational Database Management System


The software required to handle/manipulate the tables/relations is known as
Relational Database Management System (RDBMS). Example - Oracle , Sybase,
DB2, MSSQL, etc.
Table/Relation
A group of rows and columns form a table. The horizontal subset of the Table is
known as a Row/Tuple. The vertical subset of the Table is known as a
Column/an Attribute.
A relation in a database has the following characteristics:

 Names of columns are distinct and order of columns is immaterial


 The rows in the relation are not ordered
Degree
No. of columns of Table.
Cardinality
No. of Rows of Table
Domain
 Definition: The domain of a database attribute is the set of all allowable
values that attribute may assume.
E-SCHOOL
 Examples: A field for gender may have the domain {male, female, unknown}
where those three values are the only permitted entries in that column.

Key
An Attribute/group of attributes in a table that identifies a tuple uniquely is
known as a key.

Primary key

Primary key is a key in a relational database that is unique for each record. It is
a unique identifier, such as a driver license number, telephone number
(including area code), or vehicle identification number (VIN).

Candidate Keys
A table may have more than one such attribute/group of attributes that
identifies a tuple uniquely and are eligible for being a primary key, all such
attributes(s) are known as Candidate Keys.

Alternate Keys
A candidate key not selected as a primary key is called alternate or secondary
key.

Foreign Key
A Foreign Key is defined in a second table, but it refers to the primary key in
the first table. It is used to ensure referential integrity in an RDBMS.

Composite Primary key

A composite key is made by the combination of two or more columns in a table


that can be used to uniquely identify each row in the table
E-SCHOOL

Relational algebra
Relational algebra is a formal system for manipulating relations. Set of operations
that can be carried out on a relation:
 Selection : To select a horizontal subset of a relation
 Projection : To select vertical subset of a relation
 Cartesian product: It operates on two relations and is denoted by X. for
example Cartesian product of two relation R1 and R2 is represented by
R=R1X R2. The degree of R is equal to sum of degrees of R1 and R2. The
cardinality of R is product of cardinality of R1 and cardinality of R2
Example Cartesian Product

The table R1
Empno Ename Dept

1 Bill A

2 Sarah C

3 John A
The table R2
Dno Dname

A Marketing
E-SCHOOL

B Sales

C Legal
R1 X R2
Empno Ename Dept Dno Dname

1 Bill A A Marketing

1 Bill A B Sales

1 Bill A C Legal

2 Sarah C A Marketing

2 Sarah C B Sales

2 Sarah C C Legal

3 John A A Marketing

3 John A B Sales

3 John A C Legal

Union
UNION is used to combine the results of two or more Select statements.
However it will eliminate duplicate rows from its result set. In case of union,
number of columns and data type must be same in both the tables.
Example of UNION

The Second table,


The First table

ID Name
ID Name

1 abhi 2 adam

2 adam Chester
3

Union SQL query will be,

select * from First


E-SCHOOL
UNION

select * from second

The result table will look like,

ID NAME

1 Abhi

2 Adam

3 Chester

Intersect
Intersect operation is used to combine two SELECT statements, but it only
retuns the records which are common from both SELECT statements. In case
of Intersect the number of columns and datatype must be same. MySQL does
not support INTERSECT operator.
Example of Intersect
The First table,

ID NAME

1 Abhi

2 Adam

The Second table,

ID NAME

2 Adam

3 Chester

Intersect query will be,

select * from First

INTERSECT
E-SCHOOL
select * from second

The result table will look like

ID NAME

2 Adam

Difference
Minus operation combines result of two Select statements and return only those
result which belongs to first set of result. MySQL does not support INTERSECT
operator.

Example of Minus

The First table,

ID NAME

1 Abhi

2 Adam

The Second table,

ID NAME

2 Adam

3 Chester

Minus query will be,

select * from First

MINUS

select * from second

The result table will look like,


E-SCHOOL

ID NAME

1 Abhi

SQL- Structured Query Language


SQL commands classified by function:

Data Definition Language (DDL) - used to define or change table/database


structure(s) (e.g., CREATE, ALTER, DROP)
Data Manipulation Language (DML) - used to insert, update or delete data
(e.g., INSERT, UPDATE, DELETE)
Data Query Language (DQL) - used to retrieve data (e.g., Select)

Data Control Language (DCL) - used to control user access (e.g., GRANT,
REVOKE)
Transactional Language - used to control logical units of work (e.g., COMMIT,
ROLLBACk)

Data Types

CHAR(size) A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in characters - can
be from 0 to 255. Default is 1.

VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and


special characters). The size parameter specifies the maximum column length in
characters - can be from 0 to 65535.

INT(size) A medium integer. Signed range is from -2147483648 to


2147483647. Unsigned range is from 0 to 4294967295. The size parameter
specifies the maximum display width (which is 255).

FLOAT(p) A floating point number. MySQL uses the p value to determine


whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to
24, the data type becomes FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE().

DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-


01' to '9999-12-31'.
E-SCHOOL
Difference between char(n) and varchar(n)

char

It is a datatype in SQL which is used to store character string of fixed length


specified. If the length of string is less than set or fixed length then it is padded
with extra blank spaces so that its length became equal to the set length.
Storage size of CHAR datatype is of n bytes(set length). We should use this
datatype when we expect the data values in a column are of same length.

VARCHAR

It is a datatype in SQL which is used to store character string of variable length


but maximum of set length specified. If the length of string is less than set or
fixed length then it will store as it is without padded with extra blank spaces.
Storage size of VARCHAR datatype is equal to the actual length of the entered
string in bytes. We should use this datatype when we expect the data values in
a column are of variable length.

DDL

Creating a new table in the database


Syntax :

CREATE TABLE table_name


(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);

Example :

create table dept(

deptno int,

dname varchar(14),

loc varchar(13),

primary key (deptno)

);
E-SCHOOL
create table emp(

empno int,

ename varchar(10) Not Null,

job varchar(9),

mgr int,

hiredate date,

sal int,

comm int default 0,

deptno int,

primary key (empno),

foreign key (deptno) references dept (deptno)

);

CREATE TABLE student


(
rno int,
name char(25),
fees int,
dob date,
class char(3)
);

Adding a new column(s) in the table


Syntax :

ALTER TABLE table_name


ADD column_name datatype

Examples :

ALTER TABLE student ADD (grade CHAR(2));

Adding Primary key

Alter table student add primary key(rno)


E-SCHOOL
Adding Unique Constraint

Alter table student add unique(name)

Modifying the data type of a column


Syntax;

ALTER TABLE table_name MODIFY column_name datatype

Example:

ALTER TABLE student MODIFY (grade CHAR(1));

Drop a column
Syntax:

ALTER TABLE table_name drop column_name

Example:

ALTER TABLE student drop grade;

Drop a primary key

Syntax:

ALTER TABLE table_name drop primary key

Deleting a table
Syntax:

DROP TABLE table_name

Example:

DROP TABLE student;

DML
Inserting a new row at the bottom of the table
Syntax :
E-SCHOOL
INSERT INTO table_name
VALUES (value1,value2,value3,...);

You can also specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1,column2,column3,...)


VALUES (value1,value2,value3,...);

Examples

INSERT INTO student

VALUES(10, 'Alex', 7800, '1998-10-03','K12');

INSERT INTO student(rno, name, fees, dob, class)

values(11, 'Peter', 6700, '1997-11-15', 'K12');

Displaying the content from a table – SELECT


Example :

SELECT * FROM student;

rno name fees Dob class

10 Alex 7800 1998-10-03 K12

11 Peter 6700 1997-11-15 K12

12 Alisha 7800 1999-07-03 K11

13 John 6900 2000-12-13 K11

SELECT name FROM student;

Name

Alex

Peter

Alisha

John
E-SCHOOL
Relational Operator
=, <, >, <=, >=, <>
Logical Operator
AND, OR, NOT

SELECT * FROM student WHERE fees < 7000;

rno name fees Dob class

11 Peter 6700 1997-11-15 K12

13 John 6900 2000-12-13 K11

SELECT * FROM student WHERE fess > 7000 AND fees < 8000;

rno name fees Dob class

10 Alex 7800 1998-10-03 K12

12 Alisha 7800 1999-07-03 K11

SELECT * FROM student WHERE fees > 7000 OR class = 'K12';

rno name fees Dob class

10 Alex 7800 1998-10-03 K12

11 Peter 6700 1997-11-15 K12

12 Alisha 7800 1999-07-03 K11

SELECT name, fees FROM student WHERE NOT (class = 'K12');

Name fees

Alisha 7800
E-SCHOOL

John 6900

SELECT name, fees FROM student WHERE class <> 'K12';

Name fees

Alisha 7800

John 6900

SELECT * FROM student WHERE rno IN(10, 12, 13);

rno name fees Dob class

10 Alex 7800 1998-10-03 K12

12 Alisha 7800 1999-07-03 K11

13 John 6900 2000-12-13 K11

SELECT * FROM student WHERE rno BETWEEN 11 AND 13;

rno name fees Dob class

11 Peter 6700 1997-11-15 K12

12 Alisha 7800 1999-07-03 K11

13 John 6900 2000-12-13 K11

Note:- Not In and Not Between are also available

SELECT name FROM student WHERE name LIKE 'A%';


E-SCHOOL

Name

Alex

Alisha

SELECT * name FROM student WHERE name LIKE '%a';

rno name fees Dob class

12 Alisha 7800 1999-07-03 K11

SELECT name FROM student WHERE Name LIKE '%e%' ;

Name

Alex

Peter

SELECT name FROM student WHERE Name LIKE '%e_' ;

It will display all names having e as second last character.


Distinct
Remove redundancy in display list

Select distinct class from student

Class

K12

K11

Arranging the data in ascending or descending order of one/multiple


columns (ORDER BY clause)
Syntax:
E-SCHOOL
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;

Example

SELECT * FROM student ORDER BY name;

Rno name fees Dob class

10 Alex 7800 1998-10-03 K12

12 Alisha 7900 1999-07-03 K11

13 John 6900 2000-12-13 K11

11 Peter 6700 1997-11-15 K12

SELECT * FROM student ORDER BY fees DESC;

rno name fees Dob class

12 Alisha 7900 1999-07-03 K11

10 Alex 7800 1998-10-03 K12

13 John 6900 2000-12-13 K11

11 Peter 6700 1997-11-15 K12

SELECT class, name, dob, fees FROM student ORDER BY class, name DESC;

Class name Dob fees

K11 John 2000-12-13 6900

K11 Alisha 1999-07-03 7900

K12 Peter 1997-11-15 6700


E-SCHOOL

K12 Alex 1998-10-03 7800

SELECT class, name, fees, fees*12 “annualfees” FROM student;

class name fees annualfees

K12 Alex 7800 93600

K12 Peter 6700 80400

K11 Alisha 7900 94800

K11 John 6900 82800

Using Single Row Functions:-


Select upper(name),lower(name),substr(name,2),substr(name,2,3) from
student

Upper(name) Lower(name) Substr(nam,2) Substr(name,2,3)

ALEX Alex lex lex

PETER Peter eter ete

ALISHA Alisha lisha lis

JOHN John ohn ohn

Using Date Functions


day() --- Returns day from a date

month() -- Returns month from a date

year() -- Returns year from a date

select day('1999-10-11'),month('1999-10-11'),year('1999-10-11');
+-------------------+---------------------+--------------------+
| day('1999-10-11') | month('1999-10-11') | year('1999-10-11') |
+-------------------+---------------------+--------------------+
| 11 | 10 | 1999 |
E-SCHOOL
+-------------------+---------------------+--------------------+

Using Aggregate Functions with SELECT


COUNT( ) To count the number of rows
SUM( ) To find the sum of values in the column
MAX( ) To find the maximum value in the column
MIN( ) To find the minimum value in the column
AVG( ) To find the average of values in the column
SELECT COUNT(*) FROM student;

COUNT(*)

SELECT COUNT(rno) FROM student;

COUNT(rno)

SELECT SUM(fees) FROM student;

SUM(fees)

29300

SELECT AVG(fees) FROM student;

AVG(fees)

7325.0000

SELECT MAX(fees), MIN(fees) FROM student;


E-SCHOOL

MAX(fees) MIN(fees)

7900 6700

Grouping data under given Column- (GROUP BY)


SELECT class, SUM(fees) FROM student GROUP BY class;

class SUM(fees)

K11 14800

K12 14500

SELECT class, MAX(fees), MIN(fees) FROM student GROUP BY class;

class MAX(fees) MIN(fees)

K11 7900 6900

K12 7800 6700

SELECT class, MAX(dob) FROM student GROUP BY class HAVING COUNT(*)>1;

class MAX(dob)

K11 2000-12-13

K12 1998-10-03

Note:- Above query will display the records of classes where minimum 2
students are studying. It could not be done using where clause as in test
expression using where we cannot use aggregate functions. Because where
work row wise where as having works after grouping.

Working with more than one table (Joins)

Equi Join
E-SCHOOL
It is also known as an inner join. It is the most common join. It is based on
matched data as per the equality condition. The equi join uses the comparison
operator(=).

Syntax:

SELECT col1, col2, col3...


FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;

Table - product

product_id product_name supplier_name unit_price

100 Camera Nikon 300

101 Television Onida 100

102 Refrigerator Videocon 150

103 Ipod Apple 75

104 Mobile Nokia 50

Table - order_items

order_id product_id total_units customer

5100 104 30 Infosys

5101 102 5 Satyam

5102 103 25 Wipro

5103 101 10 TCS

SELECT order_id, product_name, unit_price, supplier_name, total_units

FROM product, order_items

WHERE order_items.product_id = product.product_id and customer=’Satyam’;

OR

SELECT order_id, product_name, unit_price, supplier_name, total_units


E-SCHOOL
FROM product p, order_items o

WHERE p.product_id = o.product_id and customer=’Satyam’;

Natural Join
Natural Join joins two tables based on same attribute name and datatypes. The
resulting table will contain all the attributes of both the table but keep only one
copy of each common column.
SELECT *

FROM product natural join order_items

We do not specify attribute name to be matched in natural join.

Subquery:- A Subquery or Inner query or Nested query is a query within


another SQL query and embedded within the WHERE clause.

Example:- Write a query to display names of students having fees greater than
John’s fees

Solution:- Select name from student where fees>(select fees from student
where name=’John’)

name

Alex

Alisha

Modifying the existing content of the table


Syntax:

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

Example

Update student set fees=fees+1000

It will update fees of all students.


E-SCHOOL
UPDATE student

SET fees = '7900'

WHERE rno = 12 ;

SELECT * FROM student;

rno name fees Dob class

10 Alex 7800 1998-10-03 K12

11 Peter 6700 1997-11-15 K12

12 Alisha 7900 1999-07-03 K11

13 John 6900 2000-12-13 K11

Deleting a row/rows from a table


Syntax:
DELETE FROM table_name
WHERE some_column=some_value;

Example:

DELETE FROM Student WHERE rno = 13;

Delete From Student;

Note. Second query will delete all records.

View - In SQL, a view is a virtual table based on the result-set of an SQL


statement.

A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.

Example

create view v_emp as select ename,sal from emp

create view v_emp as select emp.*,dname,loc from emp,dept where


emp.deptno=dept.deptno
E-SCHOOL
Data Dictionary- In database management systems, a file that defines the
basic organization of a database. A data dictionary contains a list of all files in
the database, the number of records in each file, and thenames and types of
each field. Most database management systems keep the data dictionary hidden
from users to prevent them from accidentally destroying its contents.

Normalization:-
Database normalization is the process of organizing the attributes and tables of
a relational database to minimize data redundancy.
The three main types of normalization are listed below:-

First Normal Form


This rule defines that all the attributes in a relation must have atomic values.

We re-arrange the relation (table) as below, to convert it to First Normal Form.

Second Normal Form


A table is in 2NF if

 Table is in 1NF
 All non-key attributes of the table should be functionally dependent on
the whole key (Composite key), not on only one part of it.

Third Normal Form


A table is in 3NF if

 Table is 2 NF
E-SCHOOL
 Every non-key attribute should be fully functionally dependent on a single
key attribute

In above table Stu_Name is functionally dependent on Stu_Id and Proj_Name is


on Proj_ID. If you want to convert it in 2NF then table must be like:-

Now in both the tables 2NF Rules are satisfied.

Difference between char and varchar


According to Oracle documentation

The difference is that CHAR (n) will ALWAYS be n bytes long. If the string length
is <n, it will be blank padded upon insert to ensure a length of n. A VARCHAR
(n) on the other hand will be 1 to n bytes long. A shorter string stored as
VARCHAR2 will NOT be blank padded.

You might also like