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

Chapter 7 Relational Database and SQL

Chapter 7 discusses relational databases and SQL, explaining what a database is, its real-life applications, and the importance of databases and Database Management Systems (DBMS). It covers key concepts such as relational data models, SQL commands for data manipulation, and various data types and constraints in MySQL. Additionally, it details the types of SQL, including Data Definition Language (DDL) and Data Manipulation Language (DML), along with examples of commands used to interact with databases.

Uploaded by

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

Chapter 7 Relational Database and SQL

Chapter 7 discusses relational databases and SQL, explaining what a database is, its real-life applications, and the importance of databases and Database Management Systems (DBMS). It covers key concepts such as relational data models, SQL commands for data manipulation, and various data types and constraints in MySQL. Additionally, it details the types of SQL, including Data Definition Language (DDL) and Data Manipulation Language (DML), along with examples of commands used to interact with databases.

Uploaded by

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

Chapter 7: Relational Database and SQL

What is Database:

 A Database is a collection of data or


information, that is organized so that it can
be easily accessed, managed and updated.

 In Database, Data is organized into rows,


columns and tables, and it is indexed to make
it easier to find relevant information.

Use of database in Real life Applications:

Application Database to maintain data about


Banking Customer information, Account details, Loan details, Transaction
details, etc.
Inventory management Product details, customer information, Order details, Delivery data, etc.
Organization Resource Employee records, Salary details, Department information, Branch
management location.
Online Shopping Item description, User login details, User order details, etc.

Need of database or Database importance or Advantages of database:

 Elimination of data redundancy: It removes duplication of data because data are kept at one
place and all the application refers to the centrally maintained database.
 Sharing of data: Same database can be used by various platforms.
 Manages large amounts of data: A database stores and manages a large amount of data on a
daily basis. This would not be possible using any other tool such as a spreadsheet.
 Data is logically accurate: Through validation rule in database ,data accuracy can be
maintained.
 Easy to update data: In a database, it is easy to update data using various Data Manipulation
languages (DML) available. One of these languages is SQL.
 Security of data: There are user logins required before accessing a database. It allows only
authorized users to access the database.

What is DBMS:

 A DBMS refers to a software that is responsible for storing, maintaining and utilizing database
in an efficient way.
 A Database along with DBMS software is called Database System.
 Example of DBMS software are Oracle, MS SQL Server, MS Access, Paradox, DB2 and MySQL
etc.
Advantages of DBMS or Need of DBMS or Importance of DBMS:

 Database Maintenance: It helps in maintenance of data and database by addition, deletion,


modification, and regular updating of the tables and its records.
 Easy Retrieval: With the help of DBMS user can retrieves any particular information with the
help of different queries offers by DBMS software.
 Security of data: There are user logins required before accessing a database. It allows only
authorized users to access the database.

DBMS Model: Data model is a model or presentation which shows How data is organized ? or stored
in the database. Data models are categorized into four categories:

Relational Data Model:


In this model data is organized into Relations or Tables (i.e. Rows and Columns). A Row is also called a
Tuple or Record. A Column is also called Attribute or Field.

Basic Terminologies related to Relational Database:


Relation: The table is also called relation. It is
arranged in Rows and Columns.
Attribute/Field: Column of a table is called
Attribute or Field. Example Sid, Sname, Sage,
Sclass, Ssection.
Tuple / Entity / Record - Rows of a table is
called Tuple or Record.
Domain : It is collection of values from which
the value is derived for a column.
Degree - Number of columns (attributes) in a
table.
Cardinality - Number of rows (Records) in a table.

Keys in a Database:
Key plays an important role in relational database; it is used for identifying unique rows from table &
establishes relationship among tables on need.
Types of keys in DBMS:
Primary Key: A primary is a column or set of columns in a table that uniquely identifies tuples (rows)
in that table.
Candidate Key: A candidate key is one that is capable of becoming the primary key.
Alternate Key: Out of all candidate keys, only one gets selected as primary key, remaining keys are
known as alternate or secondary keys.
Foreign Key: Foreign keys are the columns of a table that points to the primary key of another table.
They act as a cross-reference between tables.

SQL (Structured Query Language)


What is SQL:
SQL is a language that is used to create, modify and access a database. SQL is being used by many
database management systems. The SQL language was originally developed at the IBM research
laboratory in 1970. Some of them are: MySQL, PostgreSQL, Oracle, SQLite, Microsoft SQL Server.
MySQL: MySQL is an open-source and freely available Relational Database Management System
(RDBMS) that uses Structured Query Language (SQL). It provides excellent features for creating,
storing, maintaining and accessing data, from database.
Advantages / Features of SQL / MySQL:

 Interactive Language : This language can be used for communicating with the databases and
used to manage database.
 Portability : SQL is compatible with other database programs like Dbase IV, FoxPro, MS Access,
DB2, MS SQL Server, Oracle, Sybase, MySQL.
 No coding needed : It is very easy to manage the database systems without any need to write
the substantial amount of code by using the standard SQL.
 Not case-sensitive language : SQL is not a case-sensitive language, both capital and small
letters are recognized.

Types of SQL:
1)Data Definition Languages (DDL) 2) Data Manipulation Languages (DML)
3) Data control Language (DCL) 4) Transaction Control Language (TCL)
Data Definition Languages Data Manipulation Languages
All the commands used to create, modify or All the commands used to create, modify contents
delete physical structure of an object like table of a table
Example of Command: create, alter, drop. Example of Command: Insert, Delete, Update.

Data Types in MySQL:


1.Numeric Data type:

 INTEGER – It stores up to 11 digit number without decimal.


 SMALLINT - It stores up to 5 digit number without decimal.
 FLOAT(x,y) - It stores number in decimal format, where x is the size of total number of digits
and y is numbers of decimals. Example of float(4,2): 95.50
2.Date & Time Data types:

 DATE – It stores date in YYYY-MM-DD format..


 TIME - It stores time in HH:MM:SS format.
3.String or Text Data types:

 CHAR(size) – It stores a fixed length string. (default is 1)


 VARCHAR(size) - It stores a variable length string.

DDL Commands in MySql


1. SHOW DATABASES: Getting listings of available databases
Mysql> show databases;
2. CREATE DATABASE: This command is used to create a database in RDBMS.
Mysql> create database school;

3. Use: After database creation we can open the database using USE command.
Mysql> Use school;
4. Drop database: To physically remove or delete a database along with all its table, DROP command
is used.
Mysql> Drop database school;

5. CREATE TABLE: CREATE TABLE command is used to create a table in a database.


mysql> create table student2
-> (rno int,
-> name varchar(20),
-> gender char(1),
-> marks int,
-> dob date)
6. SHOW TABLES: To verify that the table has been created in the database, SHOW TABLES command
in used.
mysql> show tables;

7. DESCRIBE: To view a table structure, DESCRIBE or DESC command is used.


mysql> describe student;

8. ALTER TABLE: To modify a table structure, ALTER TABLE command is used.


1. Add a column to an existing table:
alter table student add city varchar(20);

2. Adding a column with default value:


alter table student add city1 varchar(20) default 'delhi';

3. Modifying an existing column definition or data type:


alter table student modify name varchar(40);

4. Renaming existing column:


alter table student change city state varchar(40);

5. Removing or drop column:


mysql> alter table student drop state;

6. Deleting primary key constraints:


mysql> alter table student drop primary key;

7. Adding primary key constraints:


mysql> alter table student add primary key(id);

9. DROP TABLE Command: To remove or delete any table permanently, DROP TABLE command is
used.
mysql> drop table student;

10. Rename to Command: To rename any table’s name.


mysql> alter table student rename to student2;
DML Commands in MySql:
11. INSERT INTO: The INSERT INTO command is used to insert a new record/row/tuple in a table.
1. Inserting data for all the columns into table:
mysql> insert into student values(1,'raj','m',93,'2000-11-17');

2. We can insert data by specifies both the column names and the values to be inserted:
mysql> insert into student (rollno, name, gender, marks,dob) values(2,NULL,'m',93,'2000-11-
17');
3. Inserting data into specific columns of table:
mysql> insert into student (rollno, name, gender,dob) values(2,NULL,'m','2000-11-17');

4. Inserting NULL values into a table:


insert into student (rollno, name, gender, marks, dob) values(2,'Ravi',NULL,93,'2000-11-17');
Note*- Null means unavailable or undefined value.
12. SQL SELECT Statement: The SELECT command in SQL is used to fetch/get data from one or more
database tables. It is used to select rows and columns from a database or relation.
1. To Fetch/Select full table data:
mysql> select * from students;

2. To Fetch/Select specific attributes from table:


mysql> select name, city from students;

3. To Fetch/Select specific row from table using WHERE Clause:


mysql> select * from students where rollno=3;

4. To re-ordering of column while displaying query result:


mysql> select name, rollno from students where rollno=3;

5. To eliminating duplicate/Redundant data using DISTINCT Clause:


mysql> select distinct city from students;

13. Modifying data in table: The UPDATE command in SQL is used to modify data in table using the
WHERE clause and the new data is written in place of old data using the SET keyword.
1. To Update single or multiple columns:
mysql> update students set city="Fatehpur" where rollno=1;

mysql> update students set name="janvi", gender='f' where name='deep';

2. Updating to NULL values:


mysql> update students set dob=Null where city='delhi';

3. Updating using an expression or formula:


mysql> update students set percent= percent+5 where (rollno=2 or rollno=4);
14. Removing data from a table: The DELETE command in SQL is used to delete rows from a table
using WHERE clause.
delete from students2 where rollno=3;

15. Removing all data from a table: The TRUNCATE command in SQL is used to delete all rows from a
table free the space containing table.
truncate table students2;

16. Constraints in MySQL:


 The constraint in MySQL is used to specify the rule that allows or restricts what values/data
will be stored in the table.
 They provide a suitable method to ensures data accuracy inside the table.
 It also helps to limit the type of data that will be inserted inside the table.
Creating Table with Constraints
The following constraints are commonly used in SQL:
1. Primary key Constraint:
 It is used to uniquely identify each record in a table.
 Primary Key values must not be NULL.
 There must be a single column only having Primary Key Constraint.
2. Unique Constraint:
 The purpose of a unique key is to ensure that the information in the column for each row
must be unique.
 Unique key Constraint can have NULL values.
3. Not Null Constraint:
 The column having NOT NULL constraint cannot contain NULL values, but it can be repeat.
4. Default Constraint:
 Default constraint is used to assign the default value to a column, when user does not
provide any value.
 However, if a user provide any value, then it will be overwrite.
5. Check Constraint:
 The CHECK constraint ensures that all the values in a column satisfies certain conditions.
Example:
mysql> create table student3
-> (rno int primary key,
-> accno int unique,
-> name varchar(30) not null,
-> city varchar(30) default 'delhi',
-> marks int check (marks<=100));
17. Operators in MySQL:
There are mainly three types of operators in MySQL.
Arithmetic Operators: Arithmetic operators used to perform simple arithmetic operations like
addition (+), Subtraction (-), multiplication (*), division(/), Modulus (%).
Example: mysql> select name, salary, salary+5000 from emp;
Relational Operators:

 A relational (comparison) Operators Description


operators is a mathematical = Equal to
symbol which is used to > Greater than
compare two values or < Less than
expression. And give results >= Greater than or equal to
in ‘true’ or ‘false’ <= Less than or equal to
 It is used to compare two <>,!= Not equal to
values of the same or compatible data types.
 They are used with WHERE clause.
Example: mysql> select * from emp where age>=22;

Logical Operators:
The SQL logical operators are the operators used to combine multiple conditions and filter data on the
basis of the condition specified in an SQL statement. Logical operators are also known as Boolean
operators.
There are three types of operators are:
AND operators: The AND operator displays a record and returns a true if all conditions (usually two
conditions) specified in the WHERE clause are true.
Example: mysql> select * from emp where salary > 20000 and age < 25;
OR operators: The OR operator displays a record and returns a true if either of the conditions (usually
two conditions) specified in the WHERE clause is true.
Example: mysql> select * from emp where salary > 20000 or age > 25;
NOT operators: NOT operators is also termed as a negation operator. This operator takes only one
condition and gives the reverse of it as the result.
Example: mysql> select * from emp where not age > 22;
18. Some Special Operators in MySQL:
Between
This operator defines the range of values that the column values must fall into make the condition
True. The range includes both the upper Values as well as Lower Values.
Example: select * from emp where salary between 15000 and 20000;
Not Between
The NOT BETWEEN operators works opposite to the BETWEEN operators. It retrieves the rows which
do not satisfy the BETWEEN condition.
The range not includes both the upper Values as well as Lower Values.
Example: select * from emp where salary not between 15000 and 20000;
IN
This operator selects values that match any values in the given list. The SQL IN condition is used to
help reduce the need for multiple OR conditions in a SELECT statement.
Example: select * from emp where salary in (15000,20000);
NOT IN
The NOT IN operators works opposite to IN operator. It matches, finds and returns the rows that do
not match the list.
Example: select * from emp where salary not in (15000,20000);
IS NULL
THE IS NULL is used to search for null values in a column.
mysql> select * from emp where salary is null;
IS NOT NULL
THE IS NOT NULL is used to search for not null values in a column.
mysql> select * from emp where salary is not null;

19. Conditions Based on Pattern -Like

Like
The LIKE operators is used to search for a specified pattern in a column. This operator is used with the
columns of types CHAR and VARCHAR.
SQL provides two Wild Card Characters that are used while comparing the strings with LIKE operators:

 Percent(%) The % character matches any substring.


 Underscore(_) The _ character matches any one character.
To display those records where name is begins with character “D”.
mysql> select * from emp where name like "D%";
To display those records where name is ends with the letter “a”
mysql> select * from emp where name like "%a";
To display those records where name contains any character anywhere in it.
mysql> select * from emp where name like "%i%";
To display those records where name contains the letter ‘a’ at the second place.
mysql> select * from emp where name like "_a%";
To display those records where name contains the letter ‘a’ at the second last position.
mysql> select * from emp where name like '%a_';
To display those records where name contains only 5 characters.
mysql> select * from emp where name like '_ _ _ _ _';
Not Like
The NOT LIKE operator gives just opposite data of LIKE operators.

20. Aggregate Functions in MySQL:


An aggregate function performs a calculation on multiple values and returns a single value. For
example, you can use the AVG() aggregate function that takes multiple numbers and returns the
average value of the numbers. Following is the list of aggregate functions supported by mysql.
SUM(): SUM() function is used to find the total value of any column or expression based on a column.
mysql> select sum(age) from emp;
MIN(): MIN() function is used to find the lowest value among the given set of values of any column or
expression based on the column.
mysql> select min(age) from emp;
MAX(): Max() function is used to find the highest value among the given set of values of any column
or expression based on the column.
mysql> select max(age) from emp;
AVG(): AVG() function is used to find the average value of any column or expression based on column.
mysql> select avg(age) from emp;
COUNT(): COUNT() function is used to count the number of values in a column. COUNT() returns the
number of non-null values in that column. If the argument is asterisk (*) then count() counts the
number of records/rows including Null values.
mysql> select count(age) from emp;
mysql> select count(*) salary from emp;
mysql> select count(distinct age) from emp;
Aggregate Functions & NULL values:
In case of NULL values none of the aggregate functions takes NULL into consideration. NULL values are
simply ignored by all aggregate functions.
21. PUTTING TEXT IN THE QUERY
With this option, we can include some user-defined
columns at runtime. These columns are displayed with
a valid text, symbols and comments in the output only.
This makes the query output more presentable by
giving a formatted output.
Example:
select rno , name , 'has scored' , marks from student;
22. ALIASES
SQL aliases are used to give an alternate name or temporary name, to a column in a table. Name
changes temporarily and does not changes the actual name in the database. They are created to make
column name more readable.
For Column:
select name as "Employee name" from emp;
23. ORDER BY
The SQL ORDER BY clause is used to sort the data in ascending order or descending order based on
one or more columns. This clause sorts the records in the ascending order (ASC) by default. And in
order to sort the records in descending order, DESC keyword is to be used.
select * from emp order by age;
select * from emp order by age desc;
select * from student order by stream asc ,name desc ;
24. GROUP BY
The GROUP BY clause combines all those records that have identical values in a particular field.
Grouping can be done with aggregate functions, such as SUM, AVG, MAX, MIN, and COUNT.
mysql> select stream, count(*) from student group by stream;
mysql> select stream, count(*),sum(marks) from student group by stream;
mysql> select gender, count(*),sum(marks),max(marks) from student group by gender;
25. HAVING clause
The purpose of HAVING clause with GROUP BY is to aggregate functions to be used along with the
specified condition because the aggregate functions are not allowed to be used with WHERE clause.
mysql> select stream, count(*) from student group by stream having count(*)>3;

26. SQL Joins:


SQL JOIN clause is used to combine rows from two or more tables, based on a common field between
them.
The types of SQL joins are as follows:
1.Cartesian product (Cross Product) 2.Equi Join 3.Natural Join
Cartesian Product (Cross Product)
The Cartesian product is also termed as cross product or cross-join. The Cartesian product is a binary
operation and is denoted by X.
The number of tuples in the new relation(table) is equal to the product of the number of tuples of the
two tables on which Carterian product is performed.
For example: mysql> select * from emp,dep;
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 common filed, primary key and foreign key.
Here, column with the same name appears two times.
mysql> select * from emp,dep where emp.d_no=dep.d_no;
or
mysql> select * from emp join dep on emp.d_no=dep.d_no;
Natural Join
The SQL Natural Join is a type of Equi Join and is structured in such a way that columns with the same
name of associated tables will appear only once.
In NATURAL JOIN, the join condition is not required, it automatically joins based on the common
column value.
mysql> select * from emp natural join dep;

You might also like