0% found this document useful (0 votes)
30 views85 pages

Module 3

The document outlines a course on Database Management Systems (DBMS) focusing on SQL commands for creating, manipulating, and querying databases. It covers essential topics such as data definition, data types, data manipulation language (DML), and aggregate functions, along with practical examples and syntax. The aim is to equip students with foundational knowledge and skills in SQL for effective database management.

Uploaded by

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

Module 3

The document outlines a course on Database Management Systems (DBMS) focusing on SQL commands for creating, manipulating, and querying databases. It covers essential topics such as data definition, data types, data manipulation language (DML), and aggregate functions, along with practical examples and syntax. The aim is to equip students with foundational knowledge and skills in SQL for effective database management.

Uploaded by

shreyasrs150
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Revolutionising B.

Tech
DATABASE MANAGEMENT SYSTEM
course code: 23TCSE304
Module-3
Welcome to DBMS

X
The primary objective of this course is to enable students to Have a broad understanding of database
concepts and database management system software and be able to write SQL commands to create
tables and views insert/update/delete data, and query data in a relational DBMS.
Table of Contents
1.Database and Table Definition,
2.data definition and data types,
3.Data Manipulation Language such as retrieval select
queries in SQL,
4.Sorting,
5.specifying constraints in SQL,
6.Aggregate functions,
7.Wildcard functions.
8.INSERT, DELETE, and UPDATE statements in SQL
Aim

To equip students in the fundamentals and


understanding of SQL and execution of SQL queries to
retrieve data and update database.
a. Explain the basics of SQL

b. Basic Retrieval Queries in SQL

c. DML and DDL commands

d. Basic SQL queries

Objectiv
es
introduction to SQL:

• SQL is a language to operate databases; it includes Database


Creation, Database Deletion, Fetching Data Rows, Modifying &
Deleting Data rows, etc.
• SQL stands for Structured Query Language which is a computer
language for storing, manipulating and retrieving data stored in a
relational database.
• SQL is not case sensitive.
1. Database and Table Definition
Database:
A database in SQL is a structured collection of data stored electronically in a computer system.
It is managed by a Database Management System (DBMS) and consists of various objects, such
as tables, views, indexes, procedures, etc.
A database is created using the CREATE DATABASE statement.
Syntax:
CREATE DATABASE database_name;
Example:
CREATE DATABASE CompanyDB;

Table:
A table in SQL is a collection of related data entries and consists of columns and rows.
Each column in a table represents a data attribute, and each row represents a data record.
Tables are defined using the CREATE TABLE statement.
Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
);
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100),
Position VARCHAR(50),
Salary INT
);

In the example above:


• ID, Name, Position, and Salary are columns.
• The INT, VARCHAR(100), VARCHAR(50), and INT specify the data types of the columns.
• PRIMARY KEY is a constraint that uniquely identifies each row in the table.
2. Data Definition And Data Types
• Data definition are commands used to create, modify and remove
database objects such as schemas, tables, views, indexes etc
• Datatype is used to define the values that a column can contain
• Each column in a database table is required to have a name and a data
type
• Data types mainly classified into three categories for every database.
 String Data types
 Numeric Data types
 Date and time Data types
MySQL String Data Types:
CHAR(Size): It is used to specify a fixed length string that can contain
numbers, letters, and special characters. Its size can be 0 to 255 characters.
Default is 1.

VARCHAR(Size): It is used to specify a variable length string that can


contain numbers, letters, and special characters. Its size can be from 0 to
65535 characters.

TEXT(Size): Holds a string with a maximum length of 65,535 bytes.

BINARY(size): Equal to CHAR(), but stores binary byte strings.


The size parameter specifies the column length in bytes. Default is 1
etc.,
MySQL Numeric Data Types:

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


Unsigned range is from 0 to 4294967295.

INTEGER(size): Equal to INT(size)

FLOAT(size, d): A floating point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in the d parameter.

BOOLEAN or BOOL: Zero is considered as false, nonzero values are considered as


true.

etc.,
MySQL DATE and TIME Data Types:

DATE:
A date. Format: YYYY-MM-DD.

TIME:

TIME is based on a 24-hour clock with default format of hh:mm:ss.

DATETIME:

The DATETIME data type specifies a date and time with fractional seconds
3. Data Manipulation Language such as
retrieval select queries in SQL
• SQL commands are instructions.
• It is used to communicate with the database. It is
also used to perform specific tasks, functions, and
queries of data.
• SQL can perform various tasks like create a table,
add data to tables, drop the table, modify the table,
set permission for users.
• Types of SQL Commands :
There are five types of SQL commands namely
DDL, DML, DQL, DCL (data control lang.), and
TCL (transaction control lang).
DDL : SQL CREATE DATABASE AND TABLE:
SQL CREATE TABLE statement is used to create table in a database.
Syntax:
Create database databasename;
Use databasename;
create table tablename (column1 data type, column2 data type,…,column_N
data type);
Example:
CREATE TABLE STUDENT
( ID INT, NAME VARCHAR (20) AGE INT, ADDRESS CHAR (25));
SQL> DESC STUDENT;
Alter – syntax
The basic syntax used to add a column to an already existing table is shown below
ALTER TABLE `table_name` ADD COLUMN `column_name` `data_type`;
ALTER TABLE `members` ADD COLUMN `credit_card_number`
VARCHAR(25);
The DROP command is used to
• Delete a database from MySQL server
DROP DATABASE <name>;', where <name> is the name of the
database
• Delete an object (like Table , Column)from a database.
ALTER TABLE `members` DROP COLUMN `credit_card_number`;
DROP TABLE `sample_table`;
The rename command is used to change the name of an existing database object(like
Table,Column) to a new name
RENAME TABLE old_table_name TO new_table_name;
ALTER TABLE table_name RENAME COLUMN old_column_name TO
new_column_name;
DML:SQL INSERT statement is a SQL query. It is used to insert a
single or a multiple records in a table. There are two ways to insert
data in a table:

1.By specifying column names


2.Without specifying column names

In the first method there is no need to specify the column


name, we need only their values.
Syntax
INSERT INTO table_name VALUES (value1, value2, value3....);
INSERT INTO table_name (column1, column2, column3....) VALUES
(value1, value2, value3.....);
The second method specifies both the column name and
values which you want to insert.
INSERT INTO student VALUES (6, PRATIK, 24, KANPUR);
DQL: SQL SELECT Statement
The SELECT statement is the most commonly used command in Structured
Query Language. It is used to access the records from one or more database
tables and views. It also retrieves the selected data that follow the conditions
we want.
SELECT Column_Name_1, Column_Name_2, ....., Column_Name_N FROM Table_
Name;
The following SQL query displays all the values of each column
from the above Student_records table:
SELECT * FROM Student_Records;
4. Sorting in SQL

syntax:
SELECT Column_Name_1, Column_Name_2, ....., column_Name_N
FROM table_name WHERE [Condition] ORDER BY[column_Name_
1, column_Name_2, ....., column_Name_N asc [desc ];
Recap Queries:

CREATE TABLE STUDENT ( USN VARCHAR (20) , AGE INT, NAME


CHAR(20), CITY CHAR (50));

DESC STUDENT; // Shows the structure of the table

INSERT INTO student (USN,AGE,Name,City) VALUES (’23CS45’, 21, ‘sachin’, ‘


Bangalore’);

INSERT INTO student VALUES (’23CS45’, 21, ‘sachin’, ‘ Bangalore’);

INSERT INTO student VALUES (’23CS45’, 21, ‘sachin’, ‘ Bangalore’),


(’23CS46’, 20, ‘ravi’, ‘Hyderabad’), (’23CS47’, 20, ‘deva’,
‘Bangalore’);
SELECT * FROM student;
SELECT USN,AGE, NAME FROM student;

SELECT * FROM student WHERE age=20;


SELECT USN,AGE, NAME FROM age>20;

SELECT * FROM student ORDER BY age desc ;


SELECT name, age FROM student WHERE age>20 ORDER BY age ;
5. specifying constraints in SQL
6. Group Function or aggregate function
An aggregate function in SQL performs a calculation on multiple
values and returns a single value.
An aggregate function ignores NULL values when it performs the
calculation, except for the count function
The functions that operates on group of tuples.
• Max
• Min
• Avg
• Sum
• Count
• select max(salary) from emp;
• Select max(salary) AS max_sal from emp;
PRODUCT_MAST
Syntaxs
PRODUCT COMPANY QTY RATE COST COUNT(*)
or
COUNT( [ALL|
Item1 Com1 2 10 20 DISTINCT]
SUM() expression )
or
Item2 Com2 3 25 75 SUM( [ALL|DISTINCT] expression )
Item3 Com1 2 30 60 AVG()
or
Item4 Com3 5 10 50 AVG( [ALL|
Item5 Com2 2 20 40 DISTINCT]
MAX() expression )
or
Item6 Cpm1 3 25 75 MAX( [ALL|
Item7 Com1 5 30 150 DISTINCT] expression )
MIN()
Item8 Com1 3 10 30 or
MIN( [ALL|DISTINCT] expression )
Item9 Com2 2 25 50
Item10 Com3 4 30 120
SELECT COUNT(*) FROM PRODUCT_MAST;
10
SELECT COUNT(*) FROM PRODUCT_MAST WHERE RATE>=20;
7
SELECT COUNT(DISTINCT COMPANY) FROM PRODUCT_MAST;
3
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY
COMPANY;
Com1 5
Com2 3
Com3 2
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY
COMPANY HAVING COUNT(*)>2;
Com1 5
Com2 3
SELECT SUM(COST) FROM PRODUCT_MAST;
670
SELECT SUM(COST) FROM PRODUCT_MAST WHERE QT
Y>3;
320
SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3 GRO
UP BY COMPANY;
Com1 150
Com2 170
SELECT COMPANY, SUM(COST) FROM PRODUCT_MAST
GROUP BY COMPANY HAVING SUM(COST)>=170;
Com1 335
Com3 170
SELECT AVG(COST) FROM PRODUCT_MAST;
67.00
SELECT MAX(RATE) FROM PRODUCT_MAST;
30
SELECT MIN(RATE) FROM PRODUCT_MAST;
10
SQL LOGICAL OPERATORS:

The Logical Operator is nothing but which returns the result in one form, i.e., either it will
display the query is true, or the query is false. The results displayed to combine or merge
more than one true or false data.

The Logical Operators in SQL are as follows:

• SQL AND OPERATOR


• SQL OR OPERATOR
• SQL NOT OPERATOR
• SQL BETWEEN OPERATOR
• SQL IN OPERATOR
• SQL LIKE OPERATOR
SQL - Operators
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement.
•Arithmetic operators
•Comparison operators
•Logical operators
•Operators used to negate conditions

SQL Arithmetic Operators:


SQL Comparison Operators:
Example QUERIES using operators:
 SELECT * FROM employees WHERE City = "Mumbai" AND Designation = “Professor";

 SELECT * FROM employees WHERE Salary BETWEEN 50000 AND 90000;

 SELECT * FROM employees WHERE Designation = "System Engineer" OR City = "Mumbai"


;

 SELECT * FROM employees WHERE City IN ("Mumbai", "Bangalore", "Pune");


// employee belongs to is either Mumbai,
Bangalore, or Pune.

 SELECT * FROM employees WHERE NOT Designation = "Professor";


7. SQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string
SQL LIKE Operator:
LIKE Operator in SQL displays only those data from the table which matches the pattern specified in
the query. Percentage (%) and underscore (_) are the two wildcard operators used with LIKE Operator
to perform pattern matching tasks.
• The percent sign (%) represents multiple characters- bl% finds bl, black, blue, and blob
• The underscore sign (_) represents single character- h_t finds hot, hat, and hit
• [] Represents any single character within the brackets h[oa]t finds hot and hat, but not hit
• ^ Represents any character not in the brackets h[^oa]t finds hit, but not hot and hat
• - Represents any single character within the specified range c[a-b]t finds cat and cbt
Example:
Write a query to retrieve only those records of employees from the employees table whose salary
starts with the digit 5.
Query:
SELECT * FROM employee WHERE Salary LIKE “5%";
The following SQL statement selects all employee with a emp Name ending with "a":
SELECT * FROM employee WHERE name LIKE “%a;
The following SQL statement selects all employee name that does NOT ending with "a":
SELECT * FROM employee WHERE name NOT LIKE “%a;
SELECT * FROM employee WHERE Salary LIKE “5%";
SELECT * FROM employee WHERE Salary LIKE “_0000";
In SQL, the GROUP BY clause is used to group rows by one or more columns
[or] In SQL, The Group By statement is used for organizing similar data into groups. .
Features
•GROUP BY clause is used with the SELECT statement.
•In the query, the GROUP BY clause is placed after the WHERE clause.
•In the query, the GROUP BY clause is placed before the ORDER BY clause if used.
•In the query, the Group BY clause is placed before the Having clause.
•Place condition in the HAVING clause.
Now,we are trying to group the
customers by their age and calculate the
average salary for each age using the
following query −

SELECT AGE, AVG(SALARY) as avg_salary


FROM CUSTOMERS GROUP BY age
SELECT NAME, SUM (SALARY) FROM Employee
GROUP BY NAME;
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition ;

Example:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
Basic Retrieval Queries in SQL
• SELECT statement
• One basic statement for retrieving information from a database
• SQL allows a table to have two or more tuples that are identical
in all their attribute values
• Unlike relational model (relational model is strictly set-theory based)
• Multiset or bag behavior

Slide 6- 54
The SELECT-FROM-WHERE Structure of Basic SQL Queries

• Basic form of the SELECT statement:

Slide 6- 55
The SELECT-FROM-WHERE Structure of Basic SQL Queries (cont’d.)

• Logical comparison operators


• =, <, <=, >, >=, and <>
• Projection attributes
• Attributes whose values are to be retrieved
• Selection condition
• Boolean condition that must be true for any retrieved tuple.
Selection conditions include join conditions when multiple relations
are involved.

Slide 6- 30
Basic Retrieval Queries

Slide 6- 31
Basic Retrieval Queries (Contd.)

Slide 6- 32
Ambiguous Attribute Names
• Same name can be used for two (or more) attributes in different
relations
• As long as the attributes are in different relations
• Must qualify the attribute name with the relation name to prevent
ambiguity

Slide 6- 33
Aliasing and Renaming
• Aliases or tuple variables
• Declare alternative relation names E and S to refer to the EMPLOYEE
relation twice in a query:

Query 8. For each employee, retrieve the employee’s first and last name and the first and last
name of his or her immediate supervisor.
• SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn;
• Recommended practice to abbreviate names and to prefix same or similar
attribute from multiple tables.

Slide 6- 34
Aliasing,Renaming and Tuple Variables (contd.)
• The attribute names can also be renamed
EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex,
Sal, Sssn, Dno)
• Note that the relation EMPLOYEE now has a variable name
E which corresponds to a tuple variable
• The “AS” may be dropped in most SQL implementations

Slide 6- 61
Unspecified WHERE Clause and Use of the Asterisk
• Missing WHERE clause
• Indicates no condition on tuple selection
• Effect is a CROSS PRODUCT
• Result is all possible tuple combinations

Slide 6- 36
Unspecified WHERE Clause and Use of the Asterisk (cont’d.)
• Specify an asterisk (*)
• Retrieve all the attribute values of the selected tuples
• The * can be prefixed by the relation name; e.g., EMPLOYEE *

Slide 6- 37
Tables as Sets in SQL
• SQL does not automatically eliminate duplicate tuples in query results
• For aggregate operations duplicates must be accounted
• Use the keyword DISTINCT in the SELECT clause
• Only distinct tuples should remain in the result

Slide 6- 38
Tables as Sets in SQL (cont’d.)
• Set operations
• UNION, EXCEPT (difference), INTERSECT
• Corresponding multiset operations: UNION ALL, EXCEPT ALL,
INTERSECT ALL)
• Type compatibility is needed for these operations to be valid

Slide 6- 39
Substring Pattern Matching and Arithmetic Operators
• LIKE comparison operator
• Used for string pattern matching
• % replaces an arbitrary number of zero or more characters
• underscore (_) replaces a single character
• Examples: WHERE Address LIKE ‘%Houston,TX%’;
• WHERE Ssn LIKE ‘_ _ 1_ _ 8901’;
• BETWEEN comparison operator
E.g., in Q14 :
WHERE(Salary BETWEEN 30000 AND 40000)
AND Dno = 5;
Slide 6- 40
Arithmetic Operations
• Standard arithmetic operators:
• Addition (+), subtraction (–), multiplication (*), and
division (/) may be included as a part of SELECT

• Query 13. Show the resulting salaries if every employee working on


the ‘ProductX’ project is given a 10 percent raise.

SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal


FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND
P.Pname=‘ProductX’;

Slide 6- 67
Ordering of Query Results
• Use ORDER BY clause
• Keyword DESC to see result in a descending order of values
• Keyword ASC to specify ascending order explicitly
• Typically placed at the end of the query

ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC

Slide 6- 68
8. INSERT, DELETE, and UPDATE Statements in SQL
• Three commands used to modify the database:
• INSERT, DELETE, and UPDATE
• INSERT inserts a tuple (row) in a relation (table)
• UPDATE may update a number of tuples (rows) in a relation
(table) that satisfy the condition
• DELETE may also update a number of tuples (rows) in a relation
(table) that satisfy the condition, used to delete tuples from
tables

Slide 6- 44
The INSERT Command
• Specify the relation name and a list of values for the tuple. All
values including nulls are supplied.

• The variation below inserts multiple tuples where a new table is


loaded values from the result of a query.

Slide 6- 46
DELETE
• Removes tuples from a relation
• Includes a WHERE-clause to select the tuples to be deleted
• Referential integrity should be enforced
• Tuples are deleted from only one table at a time (unless CASCADE is
specified on a referential integrity constraint)
• A missing WHERE-clause specifies that all tuples in the relation are to
be deleted; the table then becomes an empty table
• The number of tuples deleted depends on the number of tuples in the
relation that satisfy the WHERE-clause

Slide 6- 48
• Removes tuples from a relation
• Includes a WHERE clause to select the tuples to be deleted. The number
of tuples deleted will vary.

Slide 6- 49
UPDATE
• Used to modify attribute values of one or more selected tuples
• A WHERE-clause selects the tuples to be modified
• An additional SET-clause specifies the attributes to be modified
and their new values
• Each command modifies tuples in the same relation
• Referential integrity specified as part of DDL specification is
enforced

Slide 6- 50
UPDATE (contd.)
• Example: Change the location and controlling department
number of project number 10 to 'Bellaire' and 5, respectively

U5: UPDATE PROJECT


SET PLOCATION = 'Bellaire',
DNUM = 5
WHERE PNUMBER=10

Slide 6- 51
UPDATE (contd.)
• Example: Give all employees in the 'Research' department a 10% raise in salary.
U6: UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research')

• In this request, the modified SALARY value depends on the original SALARY
value in each tuple

• The reference to the SALARY attribute on the right of = refers to the old
SALARY value before modification
• The reference to the SALARY attribute on the left of = refers to the new
SALARY value after modification
Slide 6- 75
Summary
• SQL
• A Comprehensive language for relational database management
• Data definition, queries, updates, constraint specification, and view
definition
• Covered :
• Data definition commands for creating tables
• Commands for constraint specification
• Simple retrieval queries
• Database update commands

Slide 6- 55
Assessments

Here are some assessments you can use to evaluate your understanding of the fundamentals of DBMS.

• Quizzes

• SQL queries

• Create of tables with constraints


Activities

Here are some activities that can help you understand the fundamentals of DBMS.
• Hands on
• Group discussion about queries
• Quiz
• Case studies
Summary

Outcomes:

a. Comprehend the fundamental concepts of SQL


b. SQL queries execution
c. Updates the database
d. DML queries
Terminal Questions
Terminal Questions

1. Explain data types in SQL.


2. How to create and insert records in table using SQL with syntax and examples.
3. Write short notes about aggregate functions in SQL.
4. Write SQL queries for the following statements for the STUDENT table.
(i) Retrieve name of the students belongs to CSE department (b) retrieve name and
USN of the students those who got A grade in exam. (c) Retrieve number of
students in each department. (d) retrieve name of the students starts with R.
5. Explain Group By statement with example.
6. Explain Alter command with all the cases.
7. How to retrieve data from the table using sql statement with condition.
8. Explain order by statement with examples.
9. How to delete and update records in the table with syntax and examples.
10. Write short notes on sorting functions.
11. Write short notes on operators in SQL.
12. Explain wildcard characters in LIKE operator.
Thank you

You might also like