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

DBMS Module 2 by Sandhyarani

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)
6 views

DBMS Module 2 by Sandhyarani

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/ 166

DATABASE MANAGEMENT

SYSTEMS (DBMS)

MODULE - 2

(22AIM42)
2

MODULE – II : SYLLABUS

Introduction to Logical Design and Relational Model:


Domains, Attributes, Tuples, and Relations; Relational Model
Constraints; Relational Database Schemas; SQL-1: Overview
of SQL language; SQL Data Definition and Data Types;
Schema change statements in SQL; Enforcing basic
constraints in SQL; Basic structure of SQL queries, Joins;
Logical connectives - AND, OR and NOT; Addition basic
operations ; Set operations; Aggregate function; SQL
modification language; Select, Delete, Update clause

Sandhya V
RELATIONAL MODEL
Relational Model Concepts: 3

•The relational model represents the database


as a collection of relations(Tables).
Informally, each relation resembles a table of
values.

•Figure 1.2 is similar to the basic relational


model representation.

•When a relation is thought of as a table of


values, each row in the table represents a
collection of related data values.

•For example, the first table of Figure 1.2 is


called STUDENT because each row
represents facts about a particular student
entity.

Sandhya V
Domains, Attributes, Tuples, and Relations
4
• In the formal relational model terminology, a row is called a tuple, a column
header is called an attribute, and the table is called a relation. The data
type describing the types of values that can appear in each column is
represented by a domain of possible values.

Domain: It Attribute: It Tuple:In the formal


contains a set contains the name relational model
of atomic of a column in a terminology, a row
values that an particular table. is called a tuple
attribute can Each attribute Ai
take. must have a
domain, dom(Ai)
Some examples of domains follow:
• Usa_phone_numbers. The set of ten-digit phone numbers valid in the United
States.
• Names: The set of character strings that represent names of persons.
• Employee_ages: Possible ages of employees in a company; each must be an
Sandhya V
integer value between 15 and 80.
5

Sandhya V
• A relation schema R, denoted by R(A1, A2, ..., An), is made up of a relation name R and 6
a list of attributes, A1, A2, ..., An. Each attribute Ai is the name of a role played by some
domain D in the relation schema R. D is called the domain of Ai and is denoted by dom(Ai
). A relation schema is used to describe a relation; R is called the name of this relation.

• A relation (or relation state) r of the relation schema R(A1, A2, ..., An), also denoted by
r(R), is a set of n-tuples r = {t1, t2, ..., tm}. Each n-tuple t is an ordered list of n values t
=<v1, v2, …,vn>

• The terms relation intension for the schema R and relation extension for a relation state
r(R) are also commonly used

• The degree (or arity) of a relation is the number of attributes n of its relation schema.

• A relation of degree seven would contain seven attributes describing each student. as
follows:
STUDENT(Name, Ssn, Home_phone, Address, Office_phone, Age, Gpa)

• Using the data type of each attribute, the definition is sometimes written as:
STUDENT(Name: string, Ssn: string, Home_phone: string, Address: string, Sandhya V
7

STUDENT(Name, Ssn, Home_phone, Address, Office_phone, Age, Gpa)

Sandhya V
Relational Model Constraints 8

 In a Relational database, there will typically be many relations, and the tuples in
those relations are usually related in various ways.
 The state of the whole database will correspond to the states of all its relations at a
particular point in time
 There are generally many restrictions or constraints on the actual values in a
database state.
 These constraints are to achieve the integrity of data in database.
 In this section, we discuss the various restrictions on data that can be specified on
a relational database in the form of constraints.
1. Constraints that are inherent in the data model. ( inherent model-based constraints or implicit constraints)
2. Constraints that can be directly expressed in schemas of the data model, typically by specifying them in the
DDL ( schema-based constraints or explicit constraints)
3. Constraints that cannot be directly expressed in the schemas of the data model, and hence must be expressed
and enforced by the application programs.( application-based or semantic constraints or business rules.)
Sandhya V
Examples of constraints categories 9

 The characteristics of relations, are the inherent constraints of the relational model.
For example, the constraint that a relation cannot have duplicate attributes is an
inherent constraint.

 The second category constraints are the constraints that can be expressed in the
schema of the relational model via the DDL.

 Constraints in the third category are more general, relate to the meaning as well as
behavior of attributes, and are difficult to express and enforce within the data
model, so they are usually checked within the application programs that perform
database updates.

 Another important category of constraints is data dependencies, which include


functional dependencies and multivalued dependencies. They are used mainly for
testing the “goodness” of the design of a relational database and are utilized in a
process called normalization Sandhya V
Schema-based constraints / 10

Relational Integrity Constraints

 Relational Integrity constraints in DBMS are referred to conditions which must be


present for a valid relation. These Relational constraints in DBMS are derived
from the rules in the mini-world that the database represents.

 There are many types of Integrity Constraints in DBMS.

 Constraints on the Relational database management system(RDBMS) is mostly


divided into three main categories are:

1.Domain Constraints
2.Key Constraints
3.Referential Integrity Constraints
4.The Entity integrity constraint

Sandhya V
11
1. Domain Constraints

 Domain constraints can be violated if an attribute value is not


appearing in the corresponding domain or it is not of the
appropriate data type.

 Domain constraints specify that within each tuple, the value of each
attribute A must be an atomic value from the domain dom(A).

 The data types associated with domains typically include


standard numeric data types for integers (such as short
integer, integer, and long integer) and real numbers (float and
double precision float).

 Characters, Booleans, fixed-length strings, and variable-length


strings are also available, as are date, time, timestamp, and Sandhya V
Consider the following example relations.
Student Student Marks This is a valid table. 12
ID Name (in %) Because the student ID attribute can
have only integers as ID and it does
1 Guneet 90 have only integers as ID.
Also, the names can be strings only
2 Ahan 92 and the marks can be integers or
floating values only.
3 Yash 87 So, every attribute for every tuple has
its values within its domain.
4 Lavish 90
5 Ashish 79

Student Student Marks


ID Name (in %)
1 Guneet 90
Now, in the 2nd table, the tuple with
2 Ahan 92 Student ID = 4 and name = “Lavish”
has marks = A. This is not an
3 Yash 87 integer or float value. So,
the domain constraint is
4 Lavish A violated here.
5 Ashish 79
Sandhya V
13
2. Key Constraints

 An attribute that can uniquely identify a tuple in a relation is called


the key of the table. The value of the attribute for different tuples in the
relation has to be unique.

Example:
In the given table, CustomerID is a key attribute of Customer Table. It is
most likely to have a single key for one customer, CustomerID = 1 is only
for the CustomerName =” Google”.

CustomerID CustomerName Status


1 Google Active
2 Amazon Active
3 Apple Inactive
Sandhya V
14

Keys
•Keys play an important role in the relational database.
•It is used to uniquely identify any record or row of data from the
table. It is also used to establish and identify relationships between
tables.
Types of keys:

Sandhya V
15

1. SUPER KEY:
Usually, there are other subsets of attributes of a relation schema R with the property that no two
tuples in any relation state r of R should have the same combination of values for these attributes.

Suppose that we denote one such subset of attributes by SK; then for any two distinct tuples t 1
and t 2 in a relation state r of R, we have the constraint that: t 1[SK]≠ t 2[SK]

Any such set of attributes SK is called a superkey of the relation schema R.

A superkey SK specifies a uniqueness constraint that no two distinct tuples in any state r of R can have
the same value for SK. Every relation has at least one default superkey—the set of all its attributes.

A superkey can have redundant attributes

Sandhya V
16

Sandhya V
17

2. Candidate key
•A candidate key is an attribute or set of attributes that can uniquely identify a
tuple.
•Except for the primary key, the remaining attributes are considered as
candidate key. The candidate keys are as strong as the primary key.
For example: In the EMPLOYEE table, id is best suited for the primary key. The
rest of the attributes, like SSN, Passport_Number, License_Number, etc., are
considered a candidate key.

Sandhya V
18
3. Primary key
•It is the first key used to identify one and only one instance of an entity uniquely.
An entity can contain multiple keys, as we saw in the employee table. The key
which is most suitable from those lists becomes a primary key.
•In the EMPLOYEE table, ID can be the primary key since it is unique for each
employee. In the EMPLOYEE table, we can even select License_Number and
Passport_Number as primary keys since they are also unique.
•For each entity, the primary key selection is based on requirements and
developers.

Sandhya V
3. Foreign key 19
•Foreign keys are the column of the table used to point to the primary key of
another table.
•Every employee works in a specific department in a company, and employee and
department are two different entities. So we can't store the department's information
in the employee table. That's why we link these two tables through the primary key
of one table.
•We add the primary key of the DEPARTMENT table, Department_Id, as a new
attribute in the EMPLOYEE table.
•In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are
related.

Sandhya V
20

Sandhya V
3. Referential Integrity Constraints 21

Referential Integrity constraints in DBMS are based on the concept of Foreign


Keys. A foreign key is an important attribute of a relation which should be referred
to in other relationships. Referential integrity constraint state happens where
relation refers to a key attribute of a different or same relation. However, that
key element must exist in the table.
Example:

In the given example, we have 2


relations, Customer and Billing.
Tuple for CustomerID =1 is
referenced twice in the relation
Billing.
So we know
CustomerName=Google has
billing amount $300

Sandhya V
22

SCHEMA DIAGRAM WITH REFERENTIAL


INTEGRITY CONSTRAINTS

Sandhya V
EXAMPLE 2: 23

Sandhya V
24

Sandhya V
25

4. The Entity integrity constraint

 The entity integrity constraint states that no primary key value can be NULL .
This is because the primary key value is used to identify individual tuples in a relation. Having NULL
values for the primary key implies that we cannot identify some tuples.
 For example, if two or more tuples had NULL for their primary keys, we may not be able to distinguish
them if we try to reference them from other relations.

Key constraints and entity integrity constraints are specified on individual relations.

The referential integrity constraint:


The referential integrity constraint is specified between two relations and is used to maintain the
consistency among tuples in the two relations.

Informally, the referential integrity constraint states that a tuple in one relation that refers to
another relation must refer to an existing tuple in that relation. Sandhya V
26
Relational Database Schemas
A relational database usually contains many relations, with tuples in relations that are related in
various ways. In this section, we define a relational database and a relational database schema.

A relational database schema S is a set of relation schemas S = {R1, R2, … , Rm} and a set of
integrity constraints IC.

A relational database state10 DB of S is a set of relation states DB = {r1, r2, … , rm} such that
each ri is a state of Ri and such that the ri relation states satisfy the integrity constraints specified
in IC. Figure 3.5 shows a relational database schema that we call COMPANY =

{EMPLOYEE, DEPARTMENT, DEPT_LOCATIONS, PROJECT, WORKS_ON,


DEPENDENT}. In each relation schema, the underlined attribute represents the primary key.
Figure3.6 shows a relational database state corresponding to the COMPANY schema.

Sandhya V
27

Sandhya V
28

Sandhya V
29

CHARACTERISTICS OF RELATIONS

The characteristics of a relation that make a relation different from a file


or a table are:
1.Ordering of Tuples in a Relation:
• A relation is defined as a set of tuples. Mathematically, elements of a set have no order
among them; hence, tuples in a relation do not have any particular order. In other
words, a relation is not sensitive to the ordering of tuples

• The definition of a relation does not specify any order: There is no preference for one
ordering over another. Hence, the relation displayed in Figure 3.2 is considered
identical to the one shown in Figure 3.1

Sandhya V
30

Sandhya V
2.ORDERING OF VALUES WITHIN A TUPLE AND AN ALTERNATIVE 31

DEFINITION OF A RELATION
An alternative definition of a relation can be given, making the ordering of values in a
tuple unnecessary.

In this definition, a relation schema R = {A1, A2, ..., An} is a set of attributes and a
relation state r(R) is a finite set of mappings r = {t1, t2, ..., tm}, where :
Each tuple ti is a mapping from R to D
D is the union (denoted by 𝖴) of the attribute domains; that is, D = dom(A1) 𝖴
dom(A2) 𝖴 ... 𝖴 dom(An).

t[Ai ] must be in dom(Ai ) for 1 ≤ i ≤ n for each mapping t in r. Each mapping ti is called
a tuple.
According to this definition of tuple as a mapping, a tuple can be considered as a set of
(<attribute>,<value>) pairs, where each pair gives the value of the mapping from an
attribute Ai to a value vi from dom(Ai ). The ordering of attributes is not important,
because the attribute name appears with its value. Sandhya V
32
3.VALUES AND NULLS IN THE TUPLES
Each value in a tuple is an atomic value; that is, it is not divisible into components
within the framework of the basic relational model. Hence, composite and multivalued
attributes are not allowed. This model is sometimes called the flat relational model.

This assumption is called the first normal form assumption.

Hence, multivalued attributes must be represented by separate relations, and composite


attributes are represented only by their simple component attributes in the basic
relational model.

Sandhya V
NULL VALUES 33

NULL values are used to represent the values of attributes that may be unknown or
may not apply to a tuple. A special value, called NULL, is used in these cases.

For example, in Figure 3.1, some STUDENT tuples have NULL for their office phones
because they do not have an office (that is, office phone does not apply to these
students)

We can have several meanings for NULL values, such as value unknown, value exists
but is not available, or attribute does not apply to this tuple (also known as value
undefined).

An example of the last type of NULL will occur if we add an attribute Visa_status to the
STUDENT relation that applies only to tuples representing foreign students
Sandhya V
34
4.INTERPRETATION (MEANING) OF A RELATION:

The relation schema can be interpreted as a declaration or a type of assertion.

For example, the schema of the STUDENT relation of Figure 3.1 asserts that, in general,
a student entity has a Name, Ssn, Home_phone, Address, Office_phone, Age, and Gpa.

Each tuple in the relation can then be interpreted as a fact or a particular instance of
the assertion.

For example, the first tuple in Figure 3.1 asserts the fact that there is a STUDENT
whose Name is Benjamin Bayer, Ssn is 305-61-2435, Age is 19, and so on.

Some relations may represent facts about entities, whereas other relations may
represent facts about relationships
Sandhya V
35
OVERVIEW OF SQL LANGUAGE
• 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 as the interface for an experimental relational database system called
SYSTEM R.

• SQL is now the standard language for commercial relational DBMSs.

• A joint effort by the American National Standards Institute (ANSI) and the International Standards
Organization (ISO) has led to a standard version of SQL (ANSI 1986), called SQL-86 or SQL1.

• A revised and much expanded standard called SQL-92 (also referred to as SQL2) was subsequently
developed. The next standard that is well-recognized is SQL:1999, which started out as SQL3.

• Two later updates to the standard are SQL:2003 and SQL:2006, which added XML features among
other updates to the language.

• Another update in 2008 incorporated more object database features in SQL Sandhya V
SQL IS A COMPREHENSIVE DATABASE LANGUAGE: IT HAS 36

STATEMENTS FOR DATA DEFINITIONS, QUERIES, AND UPDATES.


HENCE, IT IS BOTH A DDLAND A DML.
In addition, it has facilities for
o defining views on the database,
o for specifying security and authorization,
o for defining integrity constraints, and
o for specifying transaction controls.
o has rules for embedding SQL statements into a general-purpose
programming language such as Java, COBOL, or C/C++.

Eg: Create view


CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4; Sandhya V
SQL DATA DEFINITION AND DATA TYPES 37
SQL uses the terms table, row, and column for the formal relational model terms relation, tuple, and attribute, respectively.

The main SQL command for data definition is the CREATE statement, which can be used to create schemas, tables
(relations), and domains (as well as other constructs such as views, assertions, and triggers).

i) Schema and Catalog Concepts in SQL


Schema is used to group together tables and other constructs that belong to the same database application.
The concept of an SQL schema was incorporated starting with SQL2 .

A database schema, is the way a given database is organized or structured. It organizes the objects in a database

An SQL schema is identified by a schema name, and includes an authorization identifier to indicate the user or
account who owns the schema, as well as descriptors for each element in the schema.

Schema elements include tables, constraints, views, domains, and other constructs (such as authorization grants) that describe
the schema.
A schema is created via the CREATE SCHEMA statement, which can include all the schema elements’ definitions.
Alternatively, the schema can be assigned a name and authorization identifier, and the elements can be defined later.
Sandhya V
38

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 COMPANYAUTHORIZATION ‘Jsmith’;

In general, not all users are authorized to create schemas and schema elements.

The privilege to create schemas, tables, and other constructs must be explicitly granted
to the relevant user accounts by the system administrator or DBA

Sandhya V
In SQL, Schema and Database concepts are synonymous 39

Sandhya V
40

CATALOG

• Catalog is a named collection of schemas in an SQL environment.

• A catalog always contains a special schema called INFORMATION_SCHEMA,


which provides information on all the schemas in the catalog and all the element
descriptors in these schemas.

• Integrity constraints such as referential integrity can be defined between relations


only if they exist in schemas within the same catalog.

Sandhya V
41

SQL DDL COMMANDS FOR CREATING TABLES

 The CREATE TABLE command is used to specify a new relation by giving it a name
and specifying its attributes and initial constraints.

 The attributes are specified first, and each attribute is given a name, a data type to
specify its domain of values, and any attribute constraints, such as NOT NULL.

 The key, entity integrity, and referential integrity constraints can be specified within
the CREATE TABLE statement after the attributes are declared, or they can be added
later using the ALTER TABLE command

Sandhya V
42

Figure 4.1 - SQL CREATE TABLE data definition statements for defining the COMPANY schema

Sandhya V
43

SQL CREATE TABLE data definition statements for defining the COMPANY schema

Sandhya V
44

SQL CREATE TABLE data definition statements for defining the COMPANY schema Sandhya V
BASE AND VIRTUAL RELATIONS
 The relations declared through CREATE TABLE statements are called base tables (or base relations); this means
that the relation and its tuples are actually created and stored as a file by the DBMS.

 The relations declared through CREATE VIEW statements are called virtual relations, which may or may not
correspond to an actual physical file.

 In SQL, the attributes in a base table are considered to be ordered in the sequence in which they are specified in the
CREATE TABLE statement.

 However, rows (tuples) are not considered to be ordered within a relation

Foreign keys that are specified either via circular references or those that refer to a table that has not yet been
created may cause errors. For example, the foreign key Super_ssn in the EMPLOYEE table is a circular
reference because it refers to the table itself.

The foreign key Dno in the EMPLOYEE table refers to the DEPARTMENT table, which
has not been created yet. To deal with this type of problem, these constraints can be left
out of the initial CREATE TABLE statement, and then added later using the ALTER
TABLE statement
THE ALTER COMMAND
The definition of a base table or of other named schema elements can be changed by using the ALTER
command.

For base tables, the possible alter table actions include adding or dropping a column (attribute), changing a
column definition, and adding or dropping table constraints.

For example, to add an attribute for keeping track of jobs of employees to the EMPLOYEE base relation in
the COMPANY schema (see Figure 4.1), we can use the command

ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);

We must still enter a value for the new attribute Job for each individual EMPLOYEE tuple.

This can be done either by specifying a default clause or by using the UPDATE command individually
on each tuple

If no default clause is specified, the new attribute will have NULLs in all the tuples of the relation
immediately after the command is executed; hence, the NOT NULL constraint is not allowed in this case
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
SMALLINT) and floating-point (real) numbers of various precision (FLOAT or REAL, and
DOUBLE PRECISION).

Formatted numbers can be declared by using DECIMAL(i,j)—or DEC(i,j) or


NUMERIC(i,j)—where i, the precision, is the total number of decimal digits and j, the
scale, is the number of digits after the decimal point. The default for scale is zero, and the
default for precision is implementation-defined.

■Character-string data types are either fixed length—CHAR(n) or CHARACTER(n),


where n is the number of characters—or varying length— VARCHAR(n) or CHAR
VARYING(n) or CHARACTER VARYING(n), where n is the maximum number of
characters
Another variable-length string data type called CHARACTER LARGE
OBJECT or CLOB is also available to specify columns that have large text
values, such as documents.

The CLOB maximum length can be specified in kilobytes (K), megabytes (M),
or gigabytes (G). For example, CLOB(20M) specifies a maximum length of 20
megabytes.
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. THE DEFAULT
FOR N, THE LENGTH OF A CHARACTER STRING OR BIT STRING, IS 1

• A Boolean data type has the traditional values of TRUE or FALSE. In SQL, because of the presence of
NULL values, a three-valued logic is used, so a third possible value for a Boolean data type is
UNKNOWN.

• 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

A timestamp data type (TIMESTAMP) includes the DATE and TIME fields, plus a minimum of six positions
for decimal fractions of seconds and an optional WITH TIME ZONE qualifier.

Literal values are represented by single quoted strings preceded by the keyword TIMESTAMP, with a blank
space between data and time; for example, TIMESTAMP ‘2008-09-27 09:12:47.648302’.
SCHEMA CHANGE STATEMENTS IN SQL 50

The schema evolution commands available in SQL can be used to alter a schema by adding or
dropping tables, attributes, constraints, and other schema elements.

1.The DROP Command


The DROP command can be used to drop named schema elements, such as tables, domains, or constraints. One can also
drop a schema. For example, if a whole schema is no longer needed, the DROP SCHEMA command can be used.
There are two drop behavior options: CASCADE and RESTRICT. For example, to remove the COMPANY
database schema and all its tables, domains, and other elements, the CASCADE option is used as follows:

DROP SCHEMA COMPANY CASCADE;

If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only if it has no elements in it;
otherwise, the DROP command will not be executed.
To use the RESTRICT option, the user must first individually drop each element in the schema, then drop the schema
itself

Sandhya V
If a base relation within a schema is no longer needed, the relation
and its definition can be deleted by using the DROP TABLE
command. For example, if we no longer wish to keep track of
dependents of employees in the COMPANY database of Figure
4.1, we can get rid of the DEPENDENT relation by issuing the
following command:
DROP TABLE DEPENDENT CASCADE;

If the RESTRICT option is chosen instead of CASCADE, a table is dropped


only if it is not referenced in any constraints (for example, by foreign key
definitions in another relation) or views (see Section 5.3) or by any other
elements.

Sandhya V
THE ALTER COMMAND 52

The definition of a base table or of other named schema elements can be changed by using the ALTER
command.

For base tables, the possible alter table actions include adding or dropping a column
(attribute), changing a column definition, and adding or dropping table constraints.

For example, to add an attribute for keeping track of jobs of employees to the EMPLOYEE base relation in
the COMPANY schema , we can use the command

ALTER TABLE COMPANY.EMPLOYEEADD COLUMN Job VARCHAR(12);

We must still enter a value for the new attribute Job for each individual EMPLOYEE tuple. This can be done
either by specifying a default clause or by using the UPDATE command individually on each tuple.
If no default clause is specified, the new attribute will have NULLs in all the tuples of the relation
immediately after the command is executed; hence, the NOT NULL constraint is not allowed in this case.

Sandhya V
53
TO DROP A COLUMN, WE MUST CHOOSE EITHER CASCADE OR
RESTRICT FOR DROP BEHAVIOR.
If CASCADE is chosen, all constraints and views that reference the column are dropped automatically from the
schema, along with the column.

If RESTRICT is chosen, the command is successful only if no views or constraints (or other schema elements)
reference the column.

For example, the following command removes the attribute Address from the EMPLOYEE base table:

ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN Address CASCADE;

It is also possible to alter a column definition by dropping an existing default clause or by defining a new
default clause. The following examples illustrate this clause:

ALTER TABLE COMPANY.DEPARTMENTALTER COLUMN Mgr_ssn DROP DEFAULT;

ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn SET DEFAULT ‘333445555’;

Sandhya V
ADDING OR DROPPING A NAMED CONSTRAINT: 54

One can also change the constraints specified on a table by adding or dropping a named constraint.

To be dropped, a constraint must have been given a name when it was specified.
For example, to drop the constraint named EMPSUPERFK from the EMPLOYEE relation, we write:

ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK CASCADE;

Once this is done, we can redefine a replacement constraint by adding a new constraint to
the relation, if needed.
This is specified by using the ADD keyword in the ALTER TABLE statement followed by the
new constraint, which can be named or unnamed and can be of any of the table constraint
types

Sandhya V
SYNTAX FOR ADDING THE UNIQUE KEY CONSTRAINT TO SINGLE AS55
WELL AS MULTIPLE COLUMNS IS GIVEN BELOW:
Syntax :

Adding unique key constraint to a column using alter:

ALTER TABLE <table_name> ADD UNIQUE (<column_name>);

Adding unique key constraint to multiple columns:

ALTER TABLE <table_name>

ADD CONSTRAINT <identifier_name> UNIQUE (<column_name1>,<column_name2>,…);

Sandhya V
SUMMARY OF SQL SYNTAX
56

Sandhya V
57
ENFORCING BASIC CONSTRAINTS IN SQL
The basic constraints that can be specified in SQL as part of table creation include key and referential integrity
constraints, restrictions on attribute domains and NULLs, and constraints on individual tuples within a relation.

Specifying Attribute Constraints and Attribute Defaults


Because SQL allows NULLs as attribute values, a constraint NOT NULL may be specified if NULL is not permitted for a
particular attribute.

This is always implicitly specified for the attributes that are part of the primary key of each relation, but it can be
specified for any other attributes whose values are required not to be NULL,

Sandhya V
SPECIFYING ATTRIBUTE DEFAULTS 58
It is also possible to define a default value for an attribute by appending the
clause DEFAULT to an attribute definition.

The default value is included in any new tuple if an explicit value is not provided for that attribute.
If no default clause is specified, the default default value is NULL for attributes that do not have
the NOT NULL constraint.

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT ‘Bangalore ‘
);

Sandhya V
THE CHECK CONSTRAINT 59

• The CHECK constraint is used to limit the value range that can be placed in a column.

• If you define a CHECK constraint on a column it will allow only certain values for this column.

• If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other
columns in the row.

The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created. The CHECK
constraint ensures that the age of a person must be 18, or older:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

Sandhya V
SPECIFYING KEY AND REFERENTIAL INTEGRITY 60
CONSTRAINTS
There are special clauses within the CREATE TABLE statement to specify the keys and referential integrity constraints

The PRIMARY KEY clause specifies one or more attributes that make up the primary key of a relation.

If a primary key has a single attribute, the clause can follow the attribute directly.

For example, the primary key of DEPARTMENT can be specified as follows :


Dnumber INT PRIMARY KEY;

The UNIQUE clause specifies alternate (secondary) keys, as illustrated in the DEPARTMENT and PROJECT table
declarations . The UNIQUE clause can also be specified directly for a secondary key if the secondary key is a single
attribute:
Dname VARCHAR(15) UNIQUE;

Sandhya V
FOREIGN KEY CONSTRAINT 61

The FOREIGN KEY constraint is used to preventactions that


would destroy links between tables.

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.

Sandhya V
62

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.

Sandhya V
63
SQL CODE TO CREATE A FOREIGN KEY ON THE "PERSONID" COLUMN
WHEN THE "ORDERS" TABLE IS CREATED:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Sandhya V
64

A referential integrity constraint can be violated when tuples are inserted or deleted, or when a foreign key
or primary key attribute value is modified.

The default action that SQL takes for an integrity violation is to reject the update operation that will cause
a violation, which is known as the RESTRICT option.

However, the schema designer can specify an alternative action to be taken by attaching a referential
triggered action clause to any foreign key constraint.

ON DELETE CASCADE clause in MySQL is used to automatically remove the matching records from the child table
when we delete the rows from the parent table.

It is a kind of referential action related to the foreign key.

Sandhya V
MySQL ON DELETE CASCADE Example 65
First, we are going to create two tables named Employee and Payment. Both tables are related through a foreign
key with on delete cascade operation. Here, an Employee is the parent table, and Payment is the child table. The
following scripts create both tables along with their records.

creates a table Employee:


CREATE TABLE Employee (
emp_id int(10) NOT NULL,
name varchar(40) NOT NULL, INSERT INTO Employee (emp_id, name, birthdate, gender,
hire_date) VALUES
birthdate date NOT NULL,
(101, 'Bryan', '1988-08-12', 'M', '2015-08-26’),
gender varchar(10) NOT NULL,
(102, 'Joseph', '1978-05-12', 'M', '2014-10-21’),
hire_date date NOT NULL,
(103, 'Mike', '1984-10-13', 'M', '2017-10-28'),
PRIMARY KEY (emp_id)
);

Sandhya V
creates a table Payment: 66

CREATE TABLE Payment (


payment_id int(10) PRIMARY KEY NOT NULL,
emp_id int(10) NOT NULL,
amount float NOT NULL,
payment_date date NOT NULL,
FOREIGN KEY (emp_id) REFERENCES Employee (emp_id) ON DELETE CASCADE
);
1.INSERT INTO Payment (payment_id, emp_id, amount, payment_date) VALUES
(301, 101, 1200, '2015-09-15'),
(302, 101, 1200, '2015-09-30'),
(303, 101, 1500, '2015-10-15’),
(304, 101, 1200, '2015-09-15'),
(305, 102, 1200, '2015-09-30'),
(306, 102, 1500, '2015-10-15'),

Sandhya V
67
delete data from the parent table Employee.
DELETE FROM Employee WHERE emp_id = 102;
The above statement will delete the employee records whose emp_id = 102 and referencing data into the child
table. We can verify the data using the SELECT statement that will give the following output:

In the above output we can see that all the rows referencing to emp_id=102 were automatically
deleted from both tables;

Sandhya V
68
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 - Prevents actions that would destroy links
between tables
• CHECK - Ensures that the values in a column satisfies a
specific condition
• DEFAULT - Sets a default value for a column if no value is
specified
• CREATE INDEX - Used to create and retrieve data from the
database very quickly

Sandhya V
Basic Retrieval Queries in SQL 69

SQL has one basic statement for retrieving information from a database: the SELECT
statement.

SQL allows a table (relation) to have two or more tuples that are identical in all their attribute
values. Hence, in general, an SQL table is not a set of tuples, because a set does not allow two
identical members; rather, it is a multiset (sometimes called a bag) of tuples.
The SELECT-FROM-WHERE Structure of Basic SQL Queries

The basic form of the SELECT statement, sometimes called a mapping or a select-from-
where block, is formed of the three clauses SELECT, FROM, and WHERE and has the
following form:9

Sandhya V
70

Sandhya V
71
In SQL, the basic logical comparison operators for comparing attribute values with one another
and with literal constants are =, <, <=, >, >=, and <>.

Query 0. Retrieve the birth date and address of the employee(s) whose name is ‘John B.
Smith’

Query 1. Retrieve the name and address of all employees who work for the
‘Research’ department.

Sandhya V
Query 2. For every project located in ‘Stafford’, list the project number, the 72
controlling department number, and the department manager’s last name,
address, and birth date.

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.

Sandhya V
73

Sandhya V
74
SQL Queries with AND, OR, and NOT Logical Operators

AND, OR, and NOT are commonly used as SQL Logical Operators that are
used with a WHERE or HAVING clause to filter on more than one condition.
 AND displays records where ALL the conditions
specified are true
 OR displays records where ANY of the
conditions specified are true
 NOT displays records where the condition(s)
specified are NOT TRUE

Sandhya V
AND Syntax
76

SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2 AND condition3
...;

OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3
...;

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

Sandhya V
77
Examples:

SELECT * FROM Customers


WHERE Country='Germany' AND City='Berlin';

SELECT * FROM Customers


WHERE City='Berlin' OR City='München';

SELECT * FROM Customers


WHERE NOT Country='Germany';

Sandhya V
JOINS IN SQL
JOIN IN ITS SIMPLEST FORM CAN BE THOUGHT OF AS A MEANS
TO RETRIEVE/UPDATE OR DELETE DATA FROM MULTIPLE
TABLES AGAINST A SINGLE QUERY.
So, in essence, JOIN combines 2 or more tables to fetch data against a given
condition.
MySQL JOIN is used to fetch, update or delete data from 2 or more tables against a given
condition.

Hence, JOIN is always used in conjunction with SELECT, UPDATE, or DELETE


statements

Syntax of JOIN with SELECT command:

SELECT {column_list} FROM tableName1 {joinType} tableName2


ON {joinCondition}
The different parts of the syntax include:

{column_list} – This represents the names of columns we want to retrieve as


the result of our query.
{JoinType} – This indicates the type of Join that we are applying.
There are following different types of JOINS that can fetch data:
• INNER JOIN
• OUTER JOIN
• LEFT OUTER JOIN
• RIGHT OUTER JOIN
• CROSS JOIN

{JoinCondition} – This is the column conditions which would be used for the
JOIN to query and fetch data.
DIFFERENT TYPES OF THE
JOINS IN SQL:

1. (INNER) JOIN: Returns records that have matching values in both tables

2. LEFT (OUTER) JOIN: Returns all records from the left table, and the matched

records from the right table

3. RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched

records from the left table

4. FULL (OUTER) JOIN: Returns all records when there is a match in either left or right

table
create database sqljoins;
use sqljoins;

CREATE TABLE Employee_Department (


name varchar(100),
id INT NOT NULL auto_increment,
PRIMARY KEY (id));

CREATE TABLE Employee (


name varchar(100),
id int not null auto_increment,
address varchar(100),
Department_id int,
PRIMARY KEY (id),
FOREIGN KEY (Department_id) references
Employee_Department(id));
`EMPLOYEE_DEPARTMENT`
VALUES ('INFORMATION
TECHNOLOGY','1’), ('HR','2’),
('FINANCE','3’),
('Accounting','4’),
('Housekeeping','5’),
('Security','6’),
('Support','7’),
('Contract Staff','8’);

INSERT INTO `Employee`


VALUES ('Veniam','1','640 Damon Junction\nEast Mathew, NY 68818','3’),
('Molestiae','2','6658 Hollis Club\nErnamouth, TX 19743','4’),
('Officiis','3','59965 Mason Neck Apt. 985\nKareemborough, NV 85535','5’),
('Rerum','4','91067 Geovany Fort\nHanefort, WA92863','6’),
('Et','5','7647 Reva Shores Suite 970\nNew Audrafort, OH 17846-5397','2’),
('Et','6','9419 Carmela Burg Apt. 687\nAimeebury, SD 32389-4489','8’),
('Laborum','7','6961 Weissnat Drive\nDonnellyfort, MT 53947','6’),
('Cupiditate','8','117 Nellie Summit Suite 982\nSouth Heavenfurt, CA 45675','8');
EMPLOYEE_DEPARTME
NT TABLE

Employee table
INNER JOIN QUERY:
SELECT EMPLOYEE.NAME AS EMPLOYEE_NAME,
EMPLOYEE_DEPARTMENT.NAME
as Department_name
FROM Employee INNER JOIN Employee_Department
ON Employee.Department_id = Employee_Department.id;
Query result:

Here we have used column name aliases.


Example: Employee.name as Employee_name just to make the
results more readable and comprehensive.
WITHOUT USING AS KEYWORD IN
SELECT QUERY
Modified query to fetch just the names beginning with the letter ‘e’.

SELECT EMPLOYEE.NAME AS
EMPLOYEE_NAME,
EMPLOYEE_DEPARTMENT.NAME
AS DEPARTMENT_NAME
FROM EMPLOYEE INNER JOIN
EMPLOYEE_DEPARTMENT ON
EMPLOYEE.DEPARTMENT_ID =
EMPLOYEE_DEPARTMENT.ID WHERE
EMPLOYEE.NAME LIKE 'E%'
OUTER JOIN
OUTER JOIN IS USED TO FETCH DATA FROM 2 OR MORE TABLES WITH AN EXCEPTION OF
INCLUDING UNMATCHED ROWS (OR ROWS HAVING NULL DATA FOR THE QUERIED
COLUMNS) AS WELL.

There are 2 types of OUTER JOINs

a) LEFT OUTER JOIN


This type of Join would fetch all the rows (including NULL values) from the table which is on the left side of
the JOIN query. Returns all records from the left table, and the matched records from the right table

b) RIGHT OUTER JOIN


Similar to LEFT JOIN, in this type of Join all the records that do not match from the right table are returned
with NULL values on the columns for the left side table. Returns all records from the right table, and the matched records
from the left table

In the OUTER JOIN queries – the RIGHT OUTER JOIN and LEFT OUTER JOIN could be
just specified as RIGHT JOIN and LEFT JOIN respectively for more readability.
Outer Join Example
Create a new table office_locations having fields – id and address
Add a new column named `office_id` to the originally created Employee table.

Queries:

CREATE TABLE office_locations ( address varchar(100), id INT NOT NULL


auto_increment, PRIMARY KEY (id));

ALTER TABLE Employee ADD COLUMN officeid int;

INSERT INTO office_locations(address)


VALUES('Bangalore'),('Mumbai'),('Seattle'),('Santa Clara’);

select * from employee;


set sql_safe_updates=0;
UPDATE Employee SET officeid=1 where id % 2 = 0;
UPDATE Employee SET officeid=2 where id % 2 <> 0;
Employee

office_locations
For example, SQL Query to find out what is the office address of all the Employees.

SELECT * from Employee


LEFT OUTER JOIN office_locations
ON Employee.office_id = office_locations.id
RIGHT OUTER JOIN
SQL Query to find out the Employees of all the office locations
CROSS
JOIN
The CROSS JOIN keyword returns all records from both tables (table1 and
table2).
CROSS JOIN is also called Cartesian Product. It returns a result against
matching Join conditions with a total of m x n rows where m and n are a
number of matching rows in table1 and table2 against the JOIN condition.

MySQL CROSS JOIN syntax:

CROSS JOIN Syntax


SELECT column_name(s)
FROM table1
CROSS JOIN table2;
Employee

office_locations
What is the output?

SELECT * FROM EMPLOYEE CROSS JOIN


OFFICE_LOCATIONS ON
EMPLOYEE.OFFICEID =
OFFICE_LOCATIONS.ID;
THE OUTPUT OF THE
QUERY:
IT IS USED
Addition TO
(+) operation in SQL : PERFORM ADDITION
OPERATION ON THE DATA
ITEMS, ITEMS INCLUDE EITHER SINGLE COLUMN OR
MULTIPLE COLUMNS.
Implementation:

SELECT employee_id, employee_name, salary,


salary + 100 AS "salary + 100" FROM
Employee;
employee employee salary+1
salary
OUTPUT: _id _name 00
**Employee is
1 alex 25000 25100
the table name
2 rr 55000 55100

3 jpm 52000 52100

4 ggshmr 12312 12412


SET Operators in SQL
SET operators are special type of
operators which are used
to combine the result of two
queries.
Operators covered under SET
operators are:
1.UNION
2.UNION ALL
3.INTERSECT
4.MINUS
There are certain rules which must be followed to perform operations using SET
operators in SQL. Rules are as follows:
1.The number and order of columns must be the same.
2.Data types must be compatible.

Let us see each of the SET operators in more detail with the help of examples.
Consider we have the following tables with the given data.
Table 1: t_employees Table 2: t2_employees
I Name Department Salar Year_o
ID Name Department Salary Year_ D y f_Exp
of_Ex erienc
perien e
ce 1 Prashant Wagh R&D 49000 1
1 Aakash Singh Development 72000 2
2 Abhishek Pawar Production 45000 1
2 Abhishek Pawar Production 45000 1
3 Gautam Jain Development 56000 4
3 Pranav Deshmukh HR 59900 3
4 Shubham Accounts 57000 2
4 Shubham Mahale Accounts 57000 2
Mahale
5 Sunil Kulkarni Development 87000 3 5 Rahul Thakur Production 76000 4
6 Bhushan Wagh R&D 75000 2 6 Bhushan Wagh R&D 75000 2
7 Paras Jaiswal Marketing 32000 1 7 Anand Singh Marketing 28000 1
TABLE 4:
Table 3: t_students T2_STUDENTS
ID Name Hometo Percent Favouri ID Name Homet Percen Favour
wn age te_Subj own tage ite_Su
ect bject
1 Soniya Udaipur 89 Physics 1 Soniya Udaipu 89 Physics
Jain Jain r
2 Harshad Kanpur 92 Chemist 2 Ishwari Delhi 86 Hindi
a ry Dixit
Sharma
3 Anuja Jaipur 78 History
3 Anuja Jaipur 78 History Rajput
Rajput
4 Pakhi Surat 70 Sanskri
4 Pranali Nashik 88 Geograp Arora t
Singh hy
5 Renuka Panipat 90 Biology
5 Renuka Panipat 90 Biology Deshm
Deshmu ukh
kh
6 Jayshre Pune 91 Maths
6 Swati Faridab 93 English e Patel
Kumari ad
7 Prachi Gurugr 96 Hindi
7 Prachi Gurugra 96 Hindi Jaiswal am
Jaiswal m
1. UNION:
•UNION will be used to combine the result of two select
statements.
•Duplicate rows will be eliminated from the results obtained
after performing the UNION operation.
Example 1:
Write a query to perform union between the table t_employees
and the table t2_employees.

SELECT *FROM t_employees UNION SELECT *FROM t2_employees;

 Here, in a single query, we have written two SELECT queries.


The first SELECT query will fetch the records from the
t_employees table and perform a UNION operation with the
records fetched by the second SELECT query from the
t2_employees table.
 You will get the following output:
ID Name Department Salary Year_of_Expe
rience
1 Aakash Singh Development 72000 2
2 Abhishek Production 45000 1
Pawar
3 Pranav HR 59900 3
Deshmukh
4 Shubham Accounts 57000 2
Mahale
5 Sunil Kulkarni Development 87000 3
6 Bhushan R&D 75000 2
Wagh
7 Paras Jaiswal Marketing 32000 1
1 Prashant R&D 49000 1
Wagh
3 Gautam Jain Development 56000 4
5 Rahul Thakur Production 76000 4
7 Anand Singh Marketing 28000 1
Since we have performed union operation between both the tables, so only the records from
the first and second table are displayed except for the duplicate records.
2. UNION ALL
•This operator combines all the records from both the queries.
•Duplicate rows will be not be eliminated from the results
obtained after performing the UNION ALL operation.
SELECT *FROM t_employees UNION ALL SELECT *FROM t2_employees;
ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2


2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2


7 Paras Jaiswal Marketing 32000 1
1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4


4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4


6 Bhushan Wagh R&D 75000 2
7 Anand Singh Marketing 28000 1
3. INTERSECT:
•It is used to combine two SELECT statements, but it only returns
the records which are common from both SELECT statements.
Example 1:
Write a query to perform intersect operation between the table
t_employees and the table t2_employees.

SELECT *FROM t_employees INTERSECT SELECT *FROM t2_employees;


Here, in a single query, we have written two SELECT queries. The
first SELECT query will fetch the records from the t_employees
table and perform INTERSECT operation with the records fetched
by the second SELECT query from the t2_employees table.
You will get the following output:

ID Name Hometown Percentage Favourite_Subject


2 Abhishek Pawar Production 45000 1
4 Shubham Mahale Accounts 57000 2
6 Bhushan Wagh R&D 75000 2
4.MINUS
•It displays the rows which are present in the first query but
absent in the second query with no duplicates.
SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;

ID Name Depart Salary Year_o


Here, in a single query, we
ment f_Expe have written two SELECT
rience queries. The first SELECT
1 Aakash Develo 72000 2 query will fetch the records
Singh pment from the t_employees
3 Pranav HR 59900 3 table and perform MINUS
Deshm
ukh operation with the records
5 Sunil Develo 87000 3 fetched by the second
Kulkarn pment SELECT query from the
i t2_employees table.You
7 Paras Marketi 32000 1 will get the following
Jaiswal ng
output as shown.
SQL SERVER AGGREGATE FUNCTIONS
AGGREGATE FUNCTIONS IN SQL SERVER ARE USED TO PERFORM
CALCULATIONS ON ONE OR MORE VALUES AND RETURN THE
RESULT IN A SINGLE VALUE. IN SQL SERVER, ALL AGGREGATE
FUNCTIONS ARE BUILT-IN FUNCTIONS THAT AVOID NULL VALUES
EXCEPT FOR COUNT(*). WE MAINLY USE THESE FUNCTIONS WITH
THE GROUP BY AND HAVING CLAUSES OF THE SELECT
STATEMENTS IN THE DATABASE QUERY LANGUAGES.
aggregate_function_name: It indicates the
Syntax: name of the aggregate function that we want
The following are the to use.
DISTINCT | ALL: The DISTINCT modifier is used
syntax to use
when we want to consider the distinct values
aggregate functions in the calculation. The ALL modifiers are used
in SQL: when we want to calculate all values,
including duplicates. If we do specify any
modifier, all aggregate functions use the ALL
aggregate_function_ modifier by default.
name(DISTINCT | ALL exp: It indicates the table's columns or an
expression containing multiple columns with
exp)
arithmetic operators.
Aggregate Function Descriptions
COUNT() This function counts the number of
elements or rows, including NULL
values in the defined set.

SUM() This function calculates the total sum


of all NON-NULL values in the given
set.
AVG() This function performs a calculation
on NON-NULL values to get the
average of them in a defined set.

MIN() This function returns the minimum


(lowest) value in a set.

MAX() This function returns the maximum


(highest) value in a set.
COMPARISON INVOLVING NULL AND THREE
VALUED LOGIC IN SQL

SQL has various rules for dealing with NULL values. NULL is used to represent a missing value, but that
it usually has one of three different interpretations namely:

1. Unknown value.
A person’s date of birth is not known, so it is represented by NULL in the database.

2. Unavailable or withheld value.


A person has a home phone but does not want it to be listed, so it is withheld and represented as NULL in
the database.

3. Not applicable attribute.


An attribute LastCollegeDegree would be NULL for a person who has no college degrees because it does
not apply to that person
 When a NULL is involved in a comparison operation, the result is considered to
be UNKNOWN (it may be TRUE or it may be FALSE).

 Hence, SQL uses a three-valued logic with values TRUE, FALSE, and
UNKNOWN instead of the standard two-valued (Boolean) logic with values
TRUE or FALSE.

 So We define the results (or truth values) of three-valued logical expressions


when the logical connectives AND, OR, and NOT are used

SQL allows queries that check whether an attribute value is NULL.

Rather than using = or <> to compare an attribute value to NULL, SQL uses the
comparison operators IS or IS NOT. This is because SQL considers each NULL value as
being distinct from every other NULL value, so equality comparison is not appropriate.
LOGICAL CONNECTIVES IN THREE-
VALUED LOGIC
CREATE
SYNTA
CREATE TABLE X:

It creates a table in the database. CREATE TABLE table_name


You can specify the name of the (column_1 datatype,
table and the columns that should
column_2 datatype,
be in the table.
column_3 datatype );

Example:
CREATE TABLE EMPLOYEE
(Name VARCHAR(20), Email VARCH
AR(100), DOB DATE);
ALTER TABLE
Changes the structure of a table. Here is how you would add a column to a database:
Syntax:

1. //To add a new column in the table

ALTER TABLE table_name ADD


column_name datatype;

2. To modify existing column in the table:

ALTER TABLE table_name MODIFY


(column_definitions....);
DROP:
It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE table_name;

Example

DROP TABLE EMPLOYEE;


INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.

Syntax:

INSERT INTO TABLE_NAME


(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);

Or

INSERT INTO TABLE_NAME (columnlist)


VALUES
(value1, value2, value3, .... valueN);
For example:
INSERT INTO Textbook (Author, Subject) VALUES ("Sonoo", "DBMS");
SELECT/DELETE/
UPDATE

UPDATE: This command is used to update or modify the value of a column in the
table.

Syntax:
UPDATE table_name
SET [column_name1= value1,...column_nameN = valueN]
[WHERE CONDITION]

For example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = '3'
DELETE:

It is used to remove one or more row from a table.

Syntax:
DELETE FROM table_name
[WHERE condition];

For example:
DELETE FROM Textbook
WHERE Author="Sonoo";
SELECT:
This is the same as the projection operation of relational algebra. It is used to select
the attribute based on the condition described by WHERE clause.

For example:
1.SELECT emp_name
FROM employee
WHERE age > 20;

2. Select * from employee;

Syntax:
SELECT expressions
FROM TABLES
WHERE conditions;
The standard SQL commands to interact with relational databases
are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP.
These commands can be classified into the following groups
based on their nature:
DDL - Data Definition Language
Data Definition Language
(DDL)
•DDL changes the
structure of the table like
creating a table, deleting
a table, altering a table,
etc.
•All the command of DDL
are auto-committed that
means it permanently
save all the changes in
the database.
DML - Data Manipulation Language

Data Manipulation
Language
•DML commands are
used to modify the
database. It is
responsible for all
form of changes in the
database.
•The command of
DML is not auto-
committed that means
it can't permanently
save all the changes
in the database. They
can be rollback.
DCL - Data Control Language

DCL commands are used to grant and take back


authority from any database user.
SQL data types
 The data type of a column can be defined as basically what type
of data format in which each cell will store the data it can be
any type of integer, character, money, date and time, binary,
etc.

 An SQL developer must aware of what type of data will be


stored inside each column while creating a table. The data type
guideline for SQL is to understand what type of data is
expected inside each column and it also identifies how SQL will
interact with the stored data.

 SQL (Structured Query Language) is a language used to interact


with relational databases. SQL data types define the type of
data that can be stored in a database column or variable. Here
are the most common SQL data types:
Data Type Properties
These are used to store numeric values.
Numeric data types Examples include INT, BIGINT, DECIMAL,
and FLOAT.

These are used to store character strings.


Character data types Examples include CHAR, VARCHAR, and
TEXT.

These are used to store date and time


Date and time data types values. Examples include DATE, TIME,
and TIMESTAMP.

This data type is used to store logical


Boolean data type values. The only possible values are TRUE
and FALSE.
These are used to store intervals of time.
Interval data types Examples include INTERVAL YEAR,
INTERVAL MONTH, and INTERVAL DAY.

These are used to store arrays of values.


Array data types
Examples include ARRAY and JSON.

XML data type This data type is used to store XML data.

These are used to store geometric or


Spatial data types geographic data. Examples include POINT,
LINE, and POLYGON.
CREATE
CREATE TABLE
does just what it Syntax:
sounds like: it
creates a table in the CREATE TABLE table_name
database. You can (column_1 datatype, column_2
specify the name of datatype, column_3 datatype );
the table and the
columns that should
be in the table.
Example:
CREATE TABLE EMPLOYEE
(Name VARCHAR(20), Email VARCHAR(
100), DOB DATE);
Syntax:
ALTER

1. //To add a new column in the table


ALTER TABLE
ALTER TABLE table_name ADD
changes the column_name datatype;
structure of a
table. Here is how
you would add a 2. To modify existing column in the table:
column to a ALTER TABLE table_name MODIFY
database: (column_definitions....);

3. To rename existing column


alter table orders2 rename column
personid to personi ;
DROP:
It is used to delete
both the structure
and record stored in
the table.
Syntax

DROP TABLE table_name;

Example

DROP TABLE EMPLOYEE;


INSERT: The
Syntax:
INSERT
statement is a
INSERT INTO TABLE_NAME
SQL query. It is
(col1, col2, col3,.... col N)
used to insert
VALUES (value1, value2, value
data into the row
3, .... valueN);
of a table.
Or

INSERT INTO TABLE_NAME VAL


UES
(value1, value2, value3, .... valueN
For example: );
INSERT INTO Textbook (Author, Subject) VALUES ("Sonoo", "
DBMS");
UPDATE: This
Syntax:
command is used to
UPDATE table_name SET [colu
update or modify the
mn_name1= value1,...column_n
value of a column in
ameN = valueN] [WHERE CON
the table.
DITION];

For example:
UPDATE students
SET User_Name = 'Sonoo'
WHERE Student_Id = 3;
DELETE: It is
used to remove
Syntax:
one or more row
DELETE FROM table_name
from a table.
[WHERE condition];

For example:
DELETE FROM Textbook
WHERE Author="Sonoo";
SELECT: This is Syntax:
the same as the SELECT expressions
projection FROM TABLES
operation of WHERE conditions;
relational algebra.
It is used to select
the attribute
based on the For example:
condition 1. SELECT emp_name
described by FROM employee
WHERE clause. WHERE age > 20;

2. Select * from employee;


SQL Constraints

SQL constraints are used to specify rules for


data in a table.
SQL Create Constraints
Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER
TABLE statement.

Syntax
CREATE TABLE table_name
(
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints

 SQL constraints are used to specify rules for the


data in a table.
 Constraints are used to limit the type of data
that can go into a table. This ensures the
accuracy and reliability of the data in the table.
If there is any violation between the constraint
and the data action, the action is aborted.
 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 - Prevents actions that would destroy links
between tables
•CHECK - Ensures that the values in a column satisfies a
specific condition
•DEFAULT - Sets a default value for a column if no value is
specified
•CREATE INDEX - Used to create and retrieve data from the
database very quickly
SQL Joins
SQL JOIN Then, look at a selection from the
A JOIN clause is used to combine "Customers" table:
rows from two or more tables,
based on a related column between Custo Custo Contac Countr
them. merID merNa tName y
me
Let's look at a selection from the
1 Alfreds Maria Germa
"Orders" table:
Futterk Anders ny
iste
OrderI CustomerID OrderDate
2 Ana Ana Mexico
D Trujillo Trujillo
10308 2 1996-09-18 Empar
edados
y
10309 3 1996-09-19 helado
s
10310 77 1996-09-20 3 Antoni Antoni Mexico
o o
Moren Moren
Notice that the "CustomerID" column in the "Orders"
o table
o refers
to the "CustomerID" in the "Customers" table. The relationship
Taquer
between the two tables above is the "CustomerID"
ía column.
and it will produce
something like this:
Then, we can create the
following SQL statement
(that contains an INNER OrderI CustomerName OrderD
JOIN), that selects D ate
records that have 10308 Ana Trujillo Emparedados y helados 9/18/19
matching values in both 96
tables:
10365 Antonio Moreno Taquería 11/27/1
996
10383 Around the Horn 12/16/1
Example
996
10355 Around the Horn 11/15/1
996
10278 Berglunds snabbköp 8/12/19
96
SELECT Orders.OrderID, Customers.CustomerName,
Orders.OrderDate
FROM Orders
JOIN Customers ON Orders.CustomerID=Customers.Customer
ID;
Different Types of SQL JOINs:
Here are the different types of the
JOINs in SQL:
•(INNER) JOIN: Returns records that
have matching values in both tables
•LEFT (OUTER) JOIN: Returns all records
from the left table, and the matched
records from the right table
•RIGHT (OUTER) JOIN: Returns all
records from the right table, and the
matched records from the left table
•FULL (OUTER) JOIN: Returns all records
when there is a match in either left or
right table
PRACTICE QUESTION:
1. Considering the Shema
Sailors(sid, sname,rating,age)
Boats(bid,bname,color)
Reserves(sid,bid,day)

Write relational algebraic queries for the following


a)Write names of sailors who have reserved boat #103
b) Write names of sailors who have reserved a Red boat
c) Write names of sailors who have reserved a Red or
Green boat
1. SELECT Sailors.sname FROM Sailors, Reserves
WHERE Sailors.sid = Reserves.sid AND Reserves.bid
= 103;

2. SELECT Sailors.sname, Sailors.age FROM Sailors ,


Reserves, Boats WHERE Sailors.sid = Reserves.sid AND
Reserves.bid = Boat.bid AND Boat.color = ‘red’ ;

3. SELECT sailors.sname FROM Boats


,Reserves,sailors WHERE Sailors.sid = Reserves.sid
AND Reserves.bid = Boat.bid Boats.color = ‘red’
UNION
SELECT sailors.sname FROM sailors,Boats Reserves
WHERE Sailors.sid = Reserves.sid AND Reserves.bid =
Boat.bid Boats.color = ‘green’ ;
SQL Queries with AND, OR, and NOT Logical Operators

AND, OR, and NOT are commonly used T-SQL Logical


Operators that are used with a WHERE or HAVING
clause to filter on more than one condition.
 AND displays records where ALL the
conditions specified are true
 OR displays records where ANY of the
conditions specified are true
 NOT displays records where the
condition(s) specified are NOT TRUE
The WHERE clause can be combined with AND, OR, and NOT operators

The AND and OR operators are used to filter records based


on more than one condition:
•The AND operator displays a record if all the conditions
separated by AND are TRUE.
•The OR operator displays a record if any of the
conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is
NOT TRUE.
AND Syntax

SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2 AND condition3
...;

OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3
...;

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

SELECT * FROM Customers


WHERE Country='Germany' AND City='Berlin';

SELECT * FROM Customers


WHERE City='Berlin' OR City='München';

SELECT * FROM Customers


WHERE NOT Country='Germany';
SET Operators in SQL
SET operators are special type
of operators which are used
to combine the result of two
queries.
Operators covered under SET
operators are:
1.UNION
2.UNION ALL
3.INTERSECT
4.MINUS
There are certain rules which must be followed to perform
operations using SET operators in SQL. Rules are as
follows:
1.The number and order of columns must be the same.
2.Data types must be compatible.

Let us seeConsider
each of we
thehave
SET the
operators in more
following tablesdetail withgiven
with the the data.
help of1:examples.
Table t_employees Table 2: t2_employees
I Name Department Salar Year_o
ID Name Department Salary Year_ D y f_Exp
of_Ex erienc
perien e
ce 1 Prashant R&D 4900 1
1 Aakash Singh Developmen 72000 2 Wagh 0
t 2 Abhishek Production 4500 1
Pawar 0
2 Abhishek Pawar Production 45000 1
3 Gautam Jain Developmen 5600 4
3 Pranav HR 59900 3 t 0
Deshmukh 4 Shubham Accounts 5700 2
4 Shubham Accounts 57000 2 Mahale 0
Mahale 5 Rahul Thakur Production 7600 4
5 Sunil Kulkarni Developmen 87000 3 0
t 6 Bhushan R&D 7500 2
1. UNION:
•UNION will be used to combine the result of two select
statements.
•Duplicate rows will be eliminated from the results
obtained after performing the UNION operation.
Example 1:
Write a query to perform union between the table
t_employees and the table t2_employees.

SELECT *FROM t_employees UNION SELECT *FROM t2_e


mployees;
 Here, in a single query, we have written two SELECT
queries. The first SELECT query will fetch the records
from the t_employees table and perform a UNION
operation with the records fetched by the second
SELECT query from the t2_employees table.
 You will get the following output:
ID Name Department Salary Year_of_Expe
rience
1 Aakash Development 72000 2
Singh
2 Abhishek Production 45000 1
Pawar
3 Pranav HR 59900 3
Deshmukh
4 Shubham Accounts 57000 2
Mahale
5 Sunil Development 87000 3
Kulkarni
6 Bhushan R&D 75000 2
Wagh
7 Paras Marketing 32000 1
Jaiswal
1 Prashant R&D 49000 1
Wagh
3 Gautam Jain Development 56000 4
Since
5 we have performed union operation
Rahul Thakur Productionbetween both the tables,
76000 4 so only the records
from the first and second table are displayed except for the duplicate records.
7 Anand Singh Marketing 28000 1
2. UNION ALL
•This operator combines all the records from both the
queries.
•Duplicate rows will be not be eliminated from the results
obtained
SELECT after performing
*FROM theUNION
t_employees UNIONALL
ALLSELECT
operation.
*FROM t2_e
mployees;
ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2


2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2


7 Paras Jaiswal Marketing 32000 1
1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4


4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4


6 Bhushan Wagh R&D 75000 2
7 Anand Singh Marketing 28000 1
3. INTERSECT:
•It is used to combine two SELECT statements, but it only
returns the records which are common from both SELECT
statements.
Example 1:
Write a query to perform intersect operation between the table
t_employees and the table t2_employees.
SELECT *FROM t_employees INTERSECT SELECT *FROM t2_
employees;
Here, in a single query, we have written two SELECT
queries. The first SELECT query will fetch the records from
the t_employees table and perform INTERSECT operation
with the records fetched by the second SELECT query from
the t2_employees table.
You will get the following output:
ID Name Hometown Percentage Favourite_Subject
2 Abhishek Pawar Production 45000 1
4 Shubham Mahale Accounts 57000 2
6 Bhushan Wagh R&D 75000 2
4.MINUS
•It displays the rows which are present in the first query
but absent in the second query with no duplicates.
SELECT *FROM t_employees MINUS SELECT *FROM t2_e
mployees;
ID Name Depart Salary Year_o Here, in a single query,
ment f_Expe we have written two
rience SELECT queries. The
1 Aakas Develo 72000 2 first SELECT query will
h pment
Singh
fetch the records from
the t_employees table
3 Pranav HR 59900 3
Deshm and perform MINUS
ukh operation with the
5 Sunil Develo 87000 3 records fetched by the
Kulkar pment second SELECT query
ni
from the t2_employees
7 Paras Market 32000 1
Jaiswa ing table.You will get the
l following output as
An SQL aggregate function

 In database management an aggregate function is a function


where the values of multiple rows are grouped together as input
on certain criteria to form a single value of more significant
meaning.
It calculates on a set of values and returns a single value

Various Aggregate Functions


 Count()
 Sum()
 Avg()
 Min()
Max()
Now let us understand each Aggregate function with a example:
Count():
Id Name Salary
1 A 80 Count(*): Returns total number of records .i.e 6.
Count(salary): Return number of Non Null
2 B 40 values over the column salary. i.e 5.
3 C 60 Count(Distinct Salary): Return number of
4 D 70 distinct Non Null values over the column salary
5 E 60 .i.e 4
6 F Null
Sum():

sum(salary): Sum all Non Null


values of Column salary i.e., 310
sum(Distinct salary): Sum of all
distinct Non-Null values i.e.,
250.
Avg():
Id Name Salary
1 A 80
Avg(salary) = Sum(salary) /
2 B 40
count(salary) = 310/5
3 C 60
Avg(Distinct salary) =
4 D 70
sum(Distinct salary) /
5 E 60
Count(Distinct Salary) =
6 F Null
250/4

Min():

Min(salary): Minimum value Max(salary): Maximum value in


in the salary column except the salary i.e., 80.
NULL i.e., 40.
1. Differentiate between weak entity and strong entity.
2. Give a short note on constraints in relational model
3. Distinguish DDL,DML with syntax and example for each
4. Explain SQL constraints
5. Write about SET operations and aggregate functions in SQL.
6. Discuss various types of joins with examples
7. Explain SQL Logical operators with example for each.
8. Write a SQL query to display three numbers in three columns.
9. Write an SQL query to display the result of an arithmetic expression.

9. Write relational algebra queries


a. Viewing all databases, Creating a Database,
b. Viewing all Tables in a Database,
c. Creating Tables (With and Without Constraints),
d.Inserting/Updating/Deleting
10. Considering the schema
Sailors(sid, sname,rating,age)
Boats(bid,bname,color)
Reserves(sid,bid,day)

Write relational algebraic queries for the following


a)Write names of sailors who have reserved boat #103
b) Write names of sailors who have reserved a Red boat
c) Write names of sailors who have reserved a Red or Green boat
d) Write names of sailors who have reserved all boats

You might also like