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

Module 4 _DBMS

The document provides study material for the Database Management Systems course (22ISE42) for the academic year 2023-24, focusing on SQL concepts including data definition, querying, and update behaviors. It covers key topics such as SQL syntax, table creation, data types, constraints, and the use of the WHERE clause in queries. Additionally, it explains nested queries and the differences between correlated and uncorrelated subqueries.

Uploaded by

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

Module 4 _DBMS

The document provides study material for the Database Management Systems course (22ISE42) for the academic year 2023-24, focusing on SQL concepts including data definition, querying, and update behaviors. It covers key topics such as SQL syntax, table creation, data types, constraints, and the use of the WHERE clause in queries. Additionally, it explains nested queries and the differences between correlated and uncorrelated subqueries.

Uploaded by

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

22ISE42 - DATABASE MANAGEMENT SYSTEMS

DEPARTMENT OF INFORMATION SCIENCE AND ENGINEERING

Study Material for Academic Year 2023-24(Even Semester)

COURSE NAME : DATABASE MANAGEMENT

SYSTEMS

COURSE CODE : 22ISE42

SEMESTER IV

1
22ISE42 - DATABASE MANAGEMENT SYSTEMS

MODULE - IV

2
22ISE42 - DATABASE MANAGEMENT SYSTEMS

MODULE – IV
SQL - Introduction, data definition in SQL, table, and key and foreign key revisit, update
behaviors. Querying in SQL – basic select-from-where block and its semantics, nested
queries - correlated and uncorrelated, notion of aggregation, aggregation functions group
by and having clauses, embedded SQL.

SQL – INTRODUCTION:
 The name SQL is presently expanded as Structured Query Language. Originally, SQL
was called SEQUEL (Structured English QUEry Language) and was designed and
implemented at IBM Research.
 SQL is a comprehensive database language:
 It has statements for data definitions, queries, and updates. Hence, it is both a DDL and
a DML.

SQL DATA DEFINITION IN SQL:


 SQL uses the terms table, row, and column for the formal relational model terms
relation, tuple, and attribute, respectively.

Schema and Catalog Concepts in SQL:


 An SQL schema (database) is
identified by a schema name
andincludes an authorization
identifier to indicate the user or
account who owns the schema.
 Schema elements include tables,
types, constraints, views, domains,
that describe the schema.
 A schema is created via the CREATE
SCHEMA statement, which can
include all the schema elements’
definitions.
 For example, the following
statement creates a schema called COMPANY owned by the user with authorization
identifier ‘Jsmith’. Note that each statement in SQL ends with a semicolon.

CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;

6.1.2 The CREATE TABLE Command in SQL


 The CREATE TABLE command is used to specify a new relation by giving it a name and
specifying its attributes and initial constraints.
 Each attribute is given a name, a data type to specify its domain of values, and possibly
attribute constraints, such as NOT NULL.
 The key, entity integrity constraints (no primary key can take NULL value), and
referential integrity constraints (two relations to maintain the consistency among the

3
22ISE42 - DATABASE MANAGEMENT SYSTEMS

tuples) can be specified within the CREATE TABLE statement while the attributes are
declared, or they can be added later using the ALTER TABLE command.

Figure 6.1 shows sample data definition statements in SQL for the COMPANY
relational database schema shown in Figure 3.7.

Base Table and Virtual relations: The relations declared through CREATE TABLE statements
are called base tables (or base relations); this means that the table and its rows are actually
created and stored as a file by the DBMS. Base relations are distinguished from virtual
relations, created through the CREATE VIEW statement, which may or may not correspond
to an actual physical file.
Syntax:
CREATE VIEW [Male students] AS
SELECT StudentName, StudentContact
FROM Student
WHERE Gendre = 'MALE';

4
22ISE42 - DATABASE MANAGEMENT SYSTEMS

We can query the view above as follows:


SELECT * FROM [Brazil Customers];

Attribute Data Types and Domains in SQL:


The basic data types available for attributes include numeric, character string, bit string,
Boolean, date, and time.
■ Numeric data types include integer numbers of various sizes (INTEGER or INT) and
floating-point (real) numbers of various precision (FLOAT or REAL).
■ Character-string data types are either fixed length (padded with extra blank spaces) —
CHAR(n) or CHARACTER(n), where n is the number of characters—or varying length (padded
with no extra blank spaces)— VARCHAR(n), where n is the maximum number of characters.
When specifying a literal string value, it is placed between single quotation marks
(apostrophes). For example, ‘Sai Prakash’.
■ Bit-string data types are either of fixed length n—BIT(n)—or varying length— BIT
VARYING(n), where n is the maximum number of bits. Literal bit strings are placed between
single quotes but preceded by a B to distinguish them from character strings; for example,
B‘10101’.
■ A Boolean data type has the traditional values of TRUE or FALSE or NULL.
■ The DATE data type has ten positions, and its components are YEAR, MONTH, and DAY in
the form YYYY-MM-DD. The TIME data type has at least eight positions, with the components
HOUR, MINUTE, and SECOND in the form HH:MM:SS. Only valid dates and times should be
allowed by the SQL implementation. This implies that months should be between 1 and 12
and days must be between 01 and 31; furthermore, a day should be a valid day for the
corresponding month. Literal values are represented by single-quoted strings preceded by
the keyword DATE or TIME; for example, DATE ‘2014-09-27’ or TIME ‘09:12:47’.

TABLE, AND KEY AND FOREIGN KEY REVISIT:


Syntax for creating a Table:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

Example:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City char(55)
);

5
22ISE42 - DATABASE MANAGEMENT SYSTEMS

OUTPUT:
Persons
PersonID LastName FirstName Address City

SQL Constraints: SQL constraints are used to specify rules for the data in a table.
Constraints can be column level or table level. Column level constraints apply to a column,
and table level constraints apply to the whole table.

The following constraints are commonly used in SQL:


 NOT NULL - Ensures that a column cannot have a NULL value
 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row
in a table
 FOREIGN KEY - Uniquely identifies a row/record in another table

SQL NOT NULL Constraint: By default, a column can hold NULL values.
Example for NOT NULL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

SQL UNIQUE Constraint:


CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL PRIMARY KEY on CREATE TABLE:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

SQL FOREIGN KEY Constraint:


A FOREIGN KEY is a field (or collection of fields) in one table, that
refers to the PRIMARY KEY in another table. The table with the foreign key
is called the child table, and the table with the primary key is called the
referenced or parent table.
Look at the following two tables:

6
22ISE42 - DATABASE MANAGEMENT SYSTEMS

Persons Table
PersonID LastName FirstName Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20
Orders Table
OrderID OrderNumber PersonID

1 77895 3

2 44678 3

3 22456 2

4 24562 1
 Notice that the "PersonID" column in the "Orders" table points to
the "PersonID" column in the "Persons" table.
 The "PersonID" column in the "Persons" table is the PRIMARY KEY in
the "Persons" table. The "PersonID" column in the "Orders" table is
a FOREIGN KEY in the "Orders" table.
 The FOREIGN KEY constraint prevents invalid data from being
inserted into the foreign key column, because it has to be one of
the values contained in the parent table.
The following SQL creates a FOREIGN KEY on the "PersonID" column when
the "Orders" table is created in MySQL:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

UPDATE BEHAVIORS: The SQL UPDATE statement is used to modify the data that is
already in the database. The condition in the WHERE clause decides that which row is
to be updated.
Syntax
1. UPDATE table_name
2. SET column1 = value1, column2 = value2, ...
3. WHERE condition;

7
22ISE42 - DATABASE MANAGEMENT SYSTEMS

Sample Table
EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

Updating single record: Update the column EMP_NAME and set the value to 'Emma'
in the row where SALARY is 500000.
Syntax:
1. UPDATE table_name
2. SET column_name = value
3. WHERE condition;

Query:
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Emma'
3. WHERE SALARY = 500000;

Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Emma Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

8
22ISE42 - DATABASE MANAGEMENT SYSTEMS

Updating multiple records: If you want to update multiple columns, you should
separate each field assigned with a comma. In the EMPLOYEE table, update the column
EMP_NAME to 'Kevin' and CITY to 'Boston' where EMP_ID is 5.

Syntax
1. UPDATE table_name
2. SET column_name = value1, column_name2 = value2
3. WHERE condition;

Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Kevin', City = 'Boston'
3. WHERE EMP_ID = 5;

Output

EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Kevin Boston 200000 36

6 Marry Canada 600000 48

Without use of WHERE clause: If you want to update all row from a table, then you
don't need to use the WHERE clause. In the EMPLOYEE table, update the column
EMP_NAME as 'Harry'.

Syntax
1. UPDATE table_name
2. SET column_name = value1;

Query
1. UPDATE EMPLOYEE
2. SET EMP_NAME = 'Harry';

9
22ISE42 - DATABASE MANAGEMENT SYSTEMS

Output

EMP_ID EMP_NAME CITY SALARY AGE

1 Harry Chicago 200000 30

2 Harry Austin 300000 26

3 Harry Denver 100000 42

4 Harry Washington 500000 29

5 Harry Los angels 200000 36

6 Harry Canada 600000 48

QUERYING IN SQL – BASIC SELECT-FROM-WHERE BLOCK AND ITS SEMANTICS:


The WHERE clause is used to filter records. It is used to extract only
those records that fulfill a specified condition.

WHERE Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: The WHERE clause is not only used in SELECT statements, it is also
used in UPDATE, DELETE, etc.!

Demo Database: Below is a selection from the "Customers" table:


CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico

3 Antonio Moreno Antonio Mataderos México 05023 Mexico

4 Around the Thomas 120 Hanover London WA1 1DP UK

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden

10
22ISE42 - DATABASE MANAGEMENT SYSTEMS

WHERE Clause Example: The following SQL statement selects all the
customers from the country "Mexico", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';

Operators in The WHERE Clause: The following operators can be used in


the WHERE clause:
Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this operator may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

BETWEEN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database: Below is a selection from the "Products" table:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles

3 Aniseed Syrup 1 2 12 - 550 ml 10


bottles
4 Chef Anton's Cajun 1 2 48 - 6 oz jars 22
Seasoning

11
22ISE42 - DATABASE MANAGEMENT SYSTEMS

5 Chef Anton's Gumbo 1 2 36 boxes 21.35


Mix

BETWEEN Example: The following SQL statement selects all products with a price
between 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
NOT BETWEEN Example: To display the products outside the range of the previous
example, use NOT BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

SQL IN Example: The following SQL statement selects all products whose CategoryID is
not 1,2, and 3:
Example
SELECT * FROM Products
WHERE CategoryID NOT IN (1,2,3);

SQL LIKE Examples: The following SQL statement selects all products with a
ProductName starting with "a":
Example
SELECT * FROM Products
WHERE ProductName LIKE 'a%';

NESTED QUERIES - CORRELATED AND UNCORRELATED:


When a query is included inside another query, the Outer query is known as Main
Query, and Inner query is known as Subquery. The subquery is a nested query.

Example:
SELECT * FROM Customers WHERE
CustomerID IN (SELECT CustomerID FROM Orders);

UNCORRELATED subquery:

12
22ISE42 - DATABASE MANAGEMENT SYSTEMS

When this subquery is executed only once and the result of this subquery is used to
extract the data in the main query, then this type of subquery is known as UNCORRELATED
subquery.

Example: Consider the below two tables –


Customers (CustomerID, CustomerName, ContactName, Country);
Orders (OrderID, CustomerID, OrderDate);
Demo Database: Below is "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico

3 Antonio Moreno Antonio Mataderos México 05023 Mexico

4 Around the Thomas 120 Hanover London WA1 1DP UK

5 Berglunds Christina Berguvsvägen Luleå S-958 22 Sweden

Orders Table:
OrderID OrderNumber CustomerID

1 77895 3

2 44678 3

3 22456 2

4 24562 1

For finding the details of customers who have ordered, the query will be
SELECT * FROM Customers WHERE
CustomerID IN (SELECT CustomerID FROM Orders);

CORRELATED subquery: In Correlated Query, Outer query executes first and for
every Outer query row Inner query is executed. Hence, Inner query uses values
from Outer query. i.e when a subquery refers to the main query for each execution, then the
subquery is known as CORRELATED subquery.

Example –
For finding the details of customers who have ordered.

SELECT * FROM Customers where


EXISTS (SELECT CustomerID FROM Orders
WHERE Orders.CustomerID=Customers.CustomerID);

13
22ISE42 - DATABASE MANAGEMENT SYSTEMS

AGGREGATION FUNCTIONS GROUP BY AND HAVING CLAUSES:


o SQL aggregation function is used to perform the calculations on multiple rows
of a single column of a table. It returns a single value.
o It is also used to summarize the data

Aggregate functions are COUNT, MAX, MIN, SUM, AVG.

COUNT() Syntax:
SELECT COUNT(column_name)
FROM table_name

AVG() Syntax:
SELECT AVG(column_name)
FROM table_name

SUM() Syntax:
SELECT SUM(column_name)
FROM table_name

Demo Database: Below is a selection from the "Products" table:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 18
bags
2 Chang 1 1 24 - 12 oz 19
bottles

14
22ISE42 - DATABASE MANAGEMENT SYSTEMS

3 Aniseed Syrup 1 2 12 - 550 ml 10


bottles
4 Chef Anton's Cajun 1 2 48 - 6 oz jars 22
Seasoning

5 Chef Anton's Gumbo 1 2 36 boxes 21.35


Mix

Example for COUNT():


SELECT COUNT (ProductID)
FROM Products;
Result:
COUNT (ProductID)
5

Example for AVG():


SELECT AVG(Price)
FROM Products;
Result:
AVG (Price)
18.5
Example for SUM():
SELECT SUM (price)
FROM Products;
Result:
SUM (price)
90

The MIN() function returns the smallest value of the selected column.
Example for MIN():
SELECT MIN (Price) AS SmallestPrice
FROM Products;
Result:
SmallestPrice
10

The MAX() function returns the largest value of the selected column.
Example for MAX():
SELECT MAX (Price) AS LargestPrice
FROM Products;
Result:
LargestPrice
22

The SQL GROUP BY Statement: The GROUP BY statement groups rows that have the
same values into summary rows, like "find the number of customers in each country".

Examples for GROUP BY clause:

15
22ISE42 - DATABASE MANAGEMENT SYSTEMS

Example: "Customers" table


Customer ID CustomerName City Country
1 Alfreds Berlin Germany
2 Ana México D.F. Mexico
3 Antonio México D.F. Mexico
4 Horn Lulea Sweden
5 Ricky London UK

The following SQL statement lists the number of customers in each country:
SELECT COUNT (CustomerID), Country
FROM Customers
GROUP BY Country;

Result:
COUNT(CustomerID) Country

1 Germany
2 Mexico
1 Sweden
1 UK

The SQL HAVING Clause: The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.

Example for HAVING clause:


SELECT COUNT (CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT (CustomerID) > 1;

Result:
COUNT(CustomerID) Country

2 Mexico

Embedded SQL:
 So far we described the SQL statements for data definition, manipulation, queries,
updates and constraints etc., Now we discuss some of the methods that have been
developed for accessing databases from programs such as Java, C/C++/C#, PHP,
Python etc..
 When database statements are included in a program, the general-purpose
programming language is called the host language, whereas the database language—
SQL—is called the data sublanguage.
 The rules for embedding SQL statements into a general-purpose programming
language, generally known as embedded SQL. Example making airline reservations or
online purchases.

16
22ISE42 - DATABASE MANAGEMENT SYSTEMS

 The database statements are embedded into the host programming language, but
they are identified by a special prefix. For example, the prefix for embedded SQL is the
string EXEC SQL, which precedes all SQL commands in a host language program.
 A precompiler or preproccessor scans the source program code to identify
database statements and extract them for processing by the DBMS. They are replaced
in the program by function calls to the DBMS-generated code. This technique is
generally referred to as embedded SQL.

An outline of example embedded SQL program:

Aim: The program retrieves an employee's name where emp_number is equal


to 10001 from a table called employees contained in a database called frans and
then prints them.
/* Begin program */

EXEC SQL BEGIN DECLARE SECTION


host_name character_string(20)
host_emp_number integer
EXEC SQL END DECLARE SECTION

EXEC SQL CONNECT frans /* establishing a connection to a database */

/* Formulate query, something like: */

EXEC SQL SELECT name emp_number


INTO host_name host_emp_number
FROM employees
WHERE emp_number = 10001

/* Print host_name and host_emp_number */

EXEC SQL DISCONNECT /* disconnecting to a database */

/* End program */

All statements that begin EXEC SQL are embedded SQL database statements. Some
additional explanation as follows:

 DECLARE SECTION: Host variables must be declared to SQL prior to


their use in any embedded SQL statements (the variable names used may be
identical to those contained in the actual table).
 EXEC SQL CONNECT personnel: Initiates access to the frans data base.
A CONNECT statement must precede any references to a database.
 EXEC SQL SELECT: This is the familiar SQL select statement. It is
followed by an INTO clause. This associates retrieved values with host
variables in the program.

17
22ISE42 - DATABASE MANAGEMENT SYSTEMS

 EXEC SQL DISCONNECT: Severs the connection between the program


and the database.

We are not limited to SELECT statements. We can embed any statement available in
standard SQL. For example we can create a table as follows:
EXEC SQL CREATE TABLE employees
(name c20,
emp_number int)

This creates a table called employees that has two fields, name a character field with
20 characters and emp_number an integer field.

*********************

18

You might also like