DBMS Module 2 by Sandhyarani
DBMS Module 2 by Sandhyarani
SYSTEMS (DBMS)
MODULE - 2
(22AIM42)
2
MODULE – II : SYLLABUS
Sandhya V
RELATIONAL MODEL
Relational Model Concepts: 3
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.
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
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.
1.Domain Constraints
2.Key Constraints
3.Referential Integrity Constraints
4.The Entity integrity constraint
Sandhya V
11
1. Domain Constraints
Domain constraints specify that within each tuple, the value of each
attribute A must be an atomic value from the domain dom(A).
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”.
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]
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.
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
Sandhya V
22
Sandhya V
EXAMPLE 2: 23
Sandhya V
24
Sandhya V
25
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.
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 =
Sandhya V
27
Sandhya V
28
Sandhya V
29
CHARACTERISTICS OF RELATIONS
• 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.
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:
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.
• 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
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).
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.
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
Sandhya V
41
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.
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
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).
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.
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;
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
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:
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:
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:
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 :
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.
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.
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:
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.
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
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
Sandhya V
63
SQL CODE TO CREATE A FOREIGN KEY ON THE "PERSONID" COLUMN
WHEN THE "ORDERS" TABLE IS CREATED:
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.
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.
Sandhya V
creates a table Payment: 66
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:
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
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:
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.
{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
3. RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
4. FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
create database sqljoins;
use sqljoins;
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:
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.
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:
office_locations
For example, SQL Query to find out what is the office address of all the Employees.
office_locations
What is the output?
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.
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.
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.
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:
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:
Syntax
Example
Syntax:
Or
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:
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;
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
XML data type This data type is used to store XML data.
Example
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;
Syntax
CREATE TABLE table_name
(
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
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:
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.
Min():