0% found this document useful (0 votes)
5 views

Ls 7 - Relational Database and SQL 12 A C 2024 - 2025

fdfsd

Uploaded by

neer028849
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Ls 7 - Relational Database and SQL 12 A C 2024 - 2025

fdfsd

Uploaded by

neer028849
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

1

Lesson – 7
Relational Database & SQL

Learning Objective : To interpret & implement Database in SQL.


2

DATA – INFORMATION - DATABASE


• Data
• Raw facts and figures
• Information
• Processed Data
• Database
• Collection of related information.
• A logically organized collection of data (information) about an entity.
• Database is integrated as well as shared.
• Databases are persistent. ( Even if an application using the dB has terminated, it will be available for other applications)
• All files belonging to one organization will be treated as the database of that organization, School Database
• Some components of dB are : files, tables, records, fields
3

DATABASE MANAGEMENT SYSTEM (DBMS)


• DBMS (Database Management System)
• A computer program designated to manage a database.
• It enables you to store, modify and extract information from a database.
• Eg:- ORACLE, SyBASE, SQL
4

ADVANTAGES OF DATABASE
• Eliminates data redundancy ( Duplication of data is avoided)
• Provides data consistency (By Propagating Updates – the changes made to data are reflected automatically)
• Sharing of Data (same data may be shared among users for different purposes)
• Improves data integrity (By range checks , value matching to(Emp ID) , formats(Date))
• Enables privacy and security (ensured by access authorization checks)
• Improved backup and recovery system
• Enforces standardised database (Company / Industry/ National / International Standards are to be followed;
Standardization enables Data Migration)
COMPONENTS OF A DATABASE
Any person who can Manages the database and
access the database is seeks to meet the needs of
called Database user the database users.

Processes executed by Collection of


the computer. related
information
DATA MODELS
Hierarchical data model Network data model Relational data model

This model uses a tree like structure to A network database is a collection of Data is stored in the form of tables in
represent relationship among nodes and links, such that any node which rows are instances and columns
records. can be linked to any other node as fields.
multiple times.
7

RELATIONAL DATABASE
• RELATIONAL DATABASE .
• A relational model consists of a collection of tables, each of which is assigned a unique
name, i.e., it represents the database as a collection of relations or tables
• The most popular data model as it is scientific and stable model than hierarchical or network
model.
• In this model, data is organized in two-dimensional tables called relations. The tables or
relations are related to each other.
• A relational database is based on this relational model developed by E.F. Codd.
• In this type of database, the data and relations between them are organized into tables, having
logically related records containing the same fields. The contents of a table or relation can be
permanently saved for future use. Thus, this model is simple and has all the properties and
capabilities required to process data with storage efficiency.

Learning Objective : To understand concept of Database


RELATIONAL DATA MODEL
• Relation : A table having rows and columns.
• Domain : A pool of values from which actual value present in a given column are taken.

• Attributes : Columns of a relation.


• Tuples : Rows of a relation.

• Degree : No of attributes(columns) in a table.


• Cardinality : No of tuples (rows) in a table.
• View : A (virtual) table that does not really exist , but is derived from one or more underlying
base tables.
• Primary Key : An attribute or a group of attributes which are used to distinguish records in a
relation.
10

Learning Objective : To understand & implement Database in SQL.


Structure of Relational dB
• Primary key - It is a key field which uniquely identifies a particular record /tuple.
• Candidate key - Attributes that uniquely identifies an instance of an entity set. (Attributes that are eligible to become
the Primary Key)
• Alternate key – The candidate key(s) that has/have not been selected as the primary key.
• Foreign Key - A non-key attribute, whose value(s) are derived from the primary key of some other table, is foreign key
in its current table.

Roll no Name Address Mobileno Rfid no


12 Rahul V Dubai 050-1234567 s456
5 Rohan Dubai 050-9562411 s923
18 Rahul S Sharjah 055-4598125 s121

Candidate Keys - Roll no , Mobileno , Rfid no


Primary Key - Rfidno
Alternate key - Mobileno , Roll no
12

Emp_id

Learning Objective : To understand & implement Database in SQL


ADVANTAGES OF USING SQL

• Portable
• High speed
• Easy to learn & understand
• Used for RDBMS
• Acts as both programming language & interactive language
• Provides Client / Server Architecture
• Supports Object based programming
WHAT IS SQL?

Structured Query Language (SQL) is a language that enables you to create, modify and
access information from Relational Database Management Systems and are also used to
create interface between a user and database

It is the set of commands that is recognized by all Relational Database


Management Systems (RDBMS).
CLASSIFICATION OF SQL STATEMENTS

• Data Definition Language (DDL)


• Data Manipulation Language (DML)
DATA DEFINITION LANGUAGE (DDL)
• Data Definition Language specifies the dB schema (structure).
• It provides a set of definitions to specify the storage structure and access methods used by the database
system.
• It contains information for creating, altering and deleting the table.
1) CREATE (to create dB objects)
2) ALTER (to change or modify dB objects)
3) DROP (to remove/delete dB objects)
• The result of compilation of DDL Statements is a set of definitions which are stored in a special file called the
Data Dictionary. Whenever data is read or modified , the data directory is consulted.
• The dictionary contains information about database objects such as tables, indexes, columns, datatypes, and
views.
• A Data Directory is a file that contains ‘METADATA’ i.e data about data
DATA MANIPULATION LANGUAGE (DML)
• A language that enables users to access or manipulate data as organized by the
appropriate data model.
• Data manipulation means
1. Insertion of new information into the database
2. Deletion of information from the database
3. Modification of information in the database
• DML Commands
1) INSERT (to insert data into the table)
2) UPDATE (to modify data (tuple) in the table)
3) DELETE (to delete data (tuple) from the table)
DATA TYPES IN SQL
• String datatypes:
• CHAR
• VARCHAR
• Numeric datatype:
• INT or INTEGER
• FLOAT
• Date:
• DATE
19

CONSTRIANTS
The restrictions that are imposed on the table at the creation level to control the
insertion, updation or deletion operation done on table.
• NOT NULL – The column must not assume a null value (cannot be empty).
• UNIQUE – No two rows can have the same value in the specified column.
• PRIMARY KEY – A combination of UNIQUE & NOT NULL constraint. Only
one Primary Key per table is allowed.

NB :
• DEFAULT – Default value can be specified for the column. Eg: School char(6) Default=‘SIS Br’
• CHECK – Limits the value that can be inserted. Eg:- age INT CHECK(age<18)

Learning Objective : To understand & implement Database


LAB ACTIVITY
Create a Database : SCHOOL with Table : STUDENT

No Name Age Department DOA Fee Gender


1 ABEL 16 Science 2019-10-01 275 M
2 ZERIN 17 Commerce 2020-03-24 250 F
3 CLARA 16 Commerce 2019-12-12 200 F
4 FARAZ 16 Science 2019-01-07 275 M
5 DIANA 17 Commerce 2020-05-09 250 F
1. CREATING DATABASE

Learning Objective : To understand & implement Database in SQL. 21


1. To display existing Databases : show databases;

2. To create a new Database : CREATE DATABASE <databasename>;

Eg: -

3. To open an existing Database: USE <databasename>;

Eg:- use SCHOOL;


4. To view tables in a database : show tables;

5. Delete an existing Database : drop database <databasename> ;

Eg: -
2. CREATING TABLES

Learning Objective : To understand & implement Database in SQL. 24


6. To create table : CREATE TABLE <table_name>
(Column1 datatype,
Column2 datatype,
……………………… …..
ColumnN datatype);
7. To view structure of table : desc <table_name>;
describe <table_name>;
3. INSERTING VALUES INTO
TABLE

Learning Objective : To understand & implement Database in SQL. 27


8.a. To enter values in table : INSERT INTO <table_name>
VALUES (<give values separated by comma>);
6.b. Enter values in selected columns / in any order: (Give the column order & give values of only those columns.
Absence of value in other columns will be denoted by NULL)
INSERT INTO <table_name>
(columnA,columnB…,columnN)
VALUES ( valueA,valueB,…valueN) ;

6.c. Enter NULL values in columns:


(Enter NULL where values are missing)
INSERT INTO <table_name>
VALUES (value1,value2,NULL, NULL,valueN);
4. DISPLAY TABLE CONTENTS
SELECT Statement

Learning Objective : To understand & implement Database in SQL. 30


9.a.. To display the entire table contents : SELECT * FROM <table_name> ;
9.b.. Selecting particular columns : SELECT <column_names> FROM <table_name> ;
9.c.. Displaying certain rows : SELECT * FROM <table_name> where <condition(s)>;
9.d.. Selecting particular columns & rows : SELECT <column_names>
FROM <table_name>
where <condition> ;

Multiple conditions
35

9.e. Selecting Distinct Data / Elimination Redundant Data :


SELECT DISTINCT(<column name>) FROM <tablename>;

The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement.

Learning Objective : To understand & implement Database in SQL.


01.06.2021 36

9.f.1. Selecting Columns with value NULL.


SELECT <column names>
FROM <tablename>
WHERE <columnname> IS NULL;

9.f.2. Selecting Columns with value NOT NULL.


SELECT <column names>
FROM <tablename>
WHERE <columnname> IS NOT NULL;

Learning Objective : To understand & implement Database in SQL.


01.06.2021 37

9.g Selecting using LIKE Operator :


SELECT <column names> NB : To match a pattern with the help of ‘%’ or ‘_’.
FROM <tablename> ‘%’ is used for any number of characters.
WHERE <columnname> LIKE ‘S%’; ‘_’ is used to match fixed no of characters.

Eg: - All names ending in ‘A’ Eg: - All names ending in ‘N’

Eg: - All names with character ‘r’. Eg: - All names with 2 characters before ‘n’.

Learning Objective : To understand & implement Database in SQL.


01.06.2021 38

9.g Selecting by specifying a range of column values.


1. BETWEEN Operator -
SELECT <column names> FROM <tablename>
WHERE <columnname> BETWEEN <value1> AND <value2>; BETWEEN is Inclusive of value1
and value2

2. Using > , < , <=, >= Operator -


SELECT <column names> FROM <tablename>
WHERE <columnname> > <value1> AND <columnname> < <value2>;

Use >= and <= to make the


selection inclusive of value1 and
value2

Learning Objective : To understand & implement Database in SQL.


01.06.2021 39

9.h Displaying in SORTED order of a Column.


SELECT <column names>
FROM <tablename> Ascending order by default.
ORDER BY <columnname>

Learning Objective : To understand & implement Database in SQL.


40

9.h SELECT by Date , Month, Year


• SELECT <column names> FROM <tablename>WHERE YEAR(<columnname> ) = <year>

• SELECT <column names> FROM <tablename>WHERE MONTH(<columnname> ) = <month>

• SELECT <column names> FROM <tablename>WHERE BETWEEN <range>

Eg 2. SELECT a year – YEAR( )


Eg 1. SELECT month – MONTH( )

Eg 3. SELECT dates within a range. - BETWEEN

Learning Objective : To understand & implement Database in SQL.


41

10. Deleting records from Table


10.a . DELETE rows according to condition :
DELETE
FROM <tablename>
WHERE <CONDITION>;

10.b . DELETE all contents from a table :


DELETE
FROM <tablename>;

OR
TRUNCATE TABLE <tablename> ;

Learning Objective : To understand & implement Database in SQL.


42

11. UPDATE Records


UPDATE <tablename>
SET <Formula>
WHERE <condition> ;

Learning Objective : To understand & implement Database in SQL.


43

12. MODIFYING THE TABLE STRUCTURE : ALTER - This command is used to modify the definition of a
table by modifying the definition of its columns.
a) Adding a new column.
ALTER TABLE <tablename>
ADD(<column_name><datatype>);

b) Deleting a column.
ALTER TABLE <tablename>
DROP COLUMN <columnname> ;

Learning Objective : To understand & implement Database in SQL.


44

12. MODIFYING THE TABLE STRUCTURE - ALTER


c) Renaming a column
Method 1 : ALTER TABLE <tablename>
RENAME COLUMN <old column name> TO <new column name>;
Does not work
for all versions
of MySQL.
Method 2 : ALTER TABLE <tablename>
CHANGE COLUMN <old column name> TO <new column name> <datatype>;

RENAME COLUMN v/s CHANGE clause


▪ the CHANGE clause can also be used to
alter the data types of a column.
▪ The RENAME clause only changes the name
of the column.

Learning Objective : To understand & implement Database in SQL.


45

13.Rename TABLE - ALTER

ALTER TABLE <tablename>


RENAME TO <new tablename>;

Learning Objective : To understand & implement Database in SQL.


46

14a. Remove Primary key - ALTER

ALTER TABLE <tablename>


DROP PRIMARY KEY;

mysql> ALTER TABLE student


DROP PRIMARY KEY;

14b. Assign Primary key - ALTER

ALTER TABLE <tablename>


ADD PRIMARY KEY<column_name>;

mysql> ALTER TABLE student


ADD PRIMARY KEY(no);

Learning Objective : To understand & implement Database in SQL.


47

AGGREGATE FUNCTIONS IN MYSQL

• SUM() Returns the sum of the column

• MIN() Returns the minimum value in the given column or set of values

• MAX() Returns the maximum in the given column or set of values

• AVG() Returns the average value of data in the given column or set of values

• COUNT() Returns the total number of values / records as per the given column

NULL values are ignored by all the aggregate functions (Except count(*))

Learning Objective : To understand & implement Database in SQL.


48

COUNT(attribute_name) V/S COUNT (*)


• count(*) will return number of rows in the table.
• count(attribute_name) will return number of non-null rows for that particular
column.

Learning Objective : To understand & implement Database in SQL.


49

15.a. Select categorized by a group – GROUP BY Clause

• Used to apply a SQL SELECT query on a group of records instead of whole table.
• A grouped column is generally that column of the table which has repeating values.

SELECT <COLUMN NAMES>


FROM <tablename>
GROUP BY <column_name> ;

Learning Objective : To understand & implement Database in SQL.


50

15.b. Select categorized by a group satisfying a condition – HAVING Clause

• Used to apply a SQL SELECT query on a group of records i.e after the GROUP BY
• A grouped column is generally that column of the table which has repeating values.

SELECT <COLUMN NAMES>


FROM <tablename>
GROUP BY <column_name>
HAVING <condition>;

Learning Objective : To understand & implement Database in SQL.


51

SQL JOIN
➢ An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.
➢ While querying for a join, more than one table is considered in FROM clause.

➢ The process/function of combining data from multiple tables is called a JOIN.


➢ SQL can extract data from two or even more than two related tables by performing either a physical or virtual
join on the tables using WHERE clause.
➢ The types of SQL joins are as follows:
1) CARTESIAN PRODUCT ( or CROSS JOIN)
2) EQUI-JOIN
3) NATURAL JOIN

Learning Objective : To understand & implement Database in SQL.


52

CROSS JOIN (CARTESIAN PRODUCT)


➢ The Cartesian product is also termed as cross product or cross-join.
➢ The Cartesian product is denoted by (X).

Eg: - select * from books CROSS JOIN issued;


(same result is produced by SELECT * FROM books, issued;)

Learning Objective : To understand & implement Database in SQL.


53

EXAMPLE
• SELECT NAME,GNAME FROM STUDENT,GAMES;

➢ Degree of the new relation = Sum of the degrees of two relations


➢ Cardinality = Product of cardinality of two relations

Learning Objective : To understand & implement Database in SQL.


Cartesian Product : 54

select * from books CROSS JOIN issued;

Learning Objective : To understand & implement Database in SQL.


Cartesian Product : 55

select book_name, type, quantity_issued from books CROSS JOIN issued;

Learning Objective : To understand & implement Database in SQL.


56

EQUI JOIN
➢ An Equi join is a simple SQL join condition that uses the equal to sign (=) as a comparison
operator for defining a relationship between two tables on the basis of a common field.
➢ Syntax for Equi Join: SELECT <COLUMN1>, <COLUMN2> ….
FROM <TABLE1> <TABLE2>
WHERE <TABLE1.COLUMN1> = <TABLE2.COLUMN1> ;

Table Alias names helps in case of tables with


lengthy names.
Table student and fees are given names A & B

SELECT A.Rollno, Name, Fee


FROM student A, fees B
WHERE A.RollNo = B.RollNo ;

Learning Objective : To understand & implement Database in SQL.


Equi Join : 57

select * from books B, issued I where B.book_id = I.book_id;

Learning Objective : To understand & implement Database in SQL.


58

NATURAL JOIN
• A natural join is a type of join that combines tables based on common columns
(same name and type) in both tables.
• Features:
• There is no need to specify the column names to join.
• The resultant table does not contain repeated columns.
• It is possible to perform a natural join on more than two tables.
➢ Syntax : SELECT <COLUMN1>, <COLUMN2> ….
FROM <TABLE1> NATURAL JOIN <TABLE2>;

Learning Objective : To understand & implement Database in SQL.


Natural Join : 59

select * from books NATURAL JOIN issued;

Learning Objective : To understand & implement Database in SQL.

You might also like