Professional Documents
Culture Documents
UNIT - 2
Relational Model: Introduction to relational model, concepts of domain, attribute, tuple,
relation, importance of null values, constraints (Domain, Key constraints, integrity
constraints) and their importance
BASIC SQL: Simple Database schema, data types, table definitions (create, alter), different
DML operations (insert, delete, update), basic SQL querying (select and project) using
where clause, arithmetic & logical operations, SQL functions(Date and Time, Numeric,
String conversion).
-----------------------------------------------------------------------------------------------------------------------------------2.1
Introduction to relational model
Relational Model (RM) represents the database as a collection of relations. A relation is
nothing but a table of values. Every row in the table represents a collection of related data
values. These rows in the table denote a real-world entity or relationship.
Relational Model was proposed by E.F. Codd to model data in the form of relations or
tables. After designing the conceptual model of Database using ER diagram, we need to
convert the conceptual model in the relational model which can be implemented using
any RDBMS languages like Oracle SQL, MySQL etc.
-------------------------------------------X----------------------------------------
2.2 concepts of domain, attribute, tuple, relation
Consider a relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE and
AGE shown in below.
STUDENT
ROLL_NO NAME ADDRESS PHONE AGE
1 ram delhi 9455123451 18
2 ramesh gurgaon 9652431543 18
3 sujit rohtak 9156253131 20
4 suresh delhi 18
Concept of DOMAIN:
o A domain describes the set of possible values for a given attribute, and can be
considered a constraint on the value of the attribute.
(or)
o A Domain is a set of atomic and valid values. Every attribute has some pre-defined
value scope, known as Attribute Domain. It is a named set of values, all of the same
type.
o Examples:
1. AGE attribute in the STUDENT relation.
Domain of AGE = { 18, 19, 20, 21, 22, 23, 24, 25}
Which means the student age must be in the range of 18 to 25.
2. Domain of PHONE ={all possible integer values of the length 10}
3. Domain of NAME = {character strings that represents person’s name }
Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME
Relation Schema: A relation schema is used to describea relation. A relation
schema represents name of the relation with its attributes.
Denoted by R(A1, A2, … , An), where R is a relation name, Ai is the name of the
attribute and domain of attribute denoted by dom(Ai).
e.g.; STUDENT (ROLL_NO, NAME, ADDRESS, PHONE and AGE) is relation schema for
STUDENT. If a schema has more than 1 relation, it is called Relational Schema.
Tuple: Each row in the relation is known as tuple. The above relation contains 4
tuples, one of which is shown as:
1 ram delhi 9455123451 18
ROLL_NO
1
2
3
4
NULL Values: The value which is not known or unavailable is called NULL value. It is
represented by blank space.
e.g.; PHONE of STUDENT having ROLL_NO 4 is NULL.
------------------------------x------------------------------
NULL values: NULL values are used to represent the values ofattributes that may be
unknown or may not apply to a tuple. A special value, calledNULL, is used in these cases.
For example, the Apartment_number attribute of an address applies only to address that
are in apartment buildings and not to other types of residences.
It is important to understand that a NULL value is different from zero value.
A NULL value is used to represent a missing value, but that it usually has one of
three different interpretations:
Value unknown (value exists but is not known)
Attribute not applicable (undefined for this tuple)
1. Value Unknown:
For example, some STUDENT tuples haveNULL for their phone because he does not
have a phone.(that isphone value is unknown).
For example, some STUDENT tuples have NULL for their height because the height
value is there but, presently it is not available with us.
--------------------------------------x---------------------------------------
2.4 Constraints (Domain, Key constraints, integrity constraints) and their importance
Constraints in DBMS:
• Constraints are the rules enforced on the data columns of a table.
• These 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 database.
• Restrictions on actual values of the database state.
Example:
1. Every student must have a name.
2. Minimum age to take into the college admission is 18.
1. Domain Constraints:
It specifies that the value taken by the attribute must be the atomic value from its
domain.
Domain constraint ensures two things
o The data value entered for that particular column matches with the data type
defined for that column
o Domain Constraint = data type check for the column + Constraints (NOT
NULL / UNIQUE / PRIMARY KEY / FOREIGN KEY / CHECK / DEFAULT)
Example: We can specify if a particular column can hold null values or not, if the values
have to be unique or not, the data type or size of values that can be entered in the column,
the default values for the column, etc.
Example-
Consider the following Student table-
• We want to create a table “student” with “age” field having a value greater than 18,
can create a table like this:
• Creating a studenttable:
a) Superkey
• super denotes the superiority of a key- the super key is the super set of all those
attributes that can uniquely identify a table.
• A Super key may have additional attributes that are not needed for unique
identification.
• Sets of super key are able to uniquely identify a row of the employee table.
• If we set Super key on Emp_SSN, it will be able to identify all other tuples of the
table very easily.
• Similarly, if we set the Super key on (Emp_Id, Emp_name}, we can easily get the
value or details of the other remaining attributes of the employee. So, in this way,
we can create and search out the super keys from a table.
b) Candidate key
• A candidate key is a set of attributes that uniquely identify tuples in a table.
Candidate Key is a super key with no repeated attributes.
• Candidate key is a minimal super key with no redundant attributes.
• It is a part of the super key.
• The Primary key should be selected from the candidate keys.
• Every table must have at least a single candidate key. A table can have multiple
candidate keys but only a single primary key.
Properties of Candidate key:
Example:
• Now, from the above mentioned sets of super keys, we can conclude the candidate
keys.
• In order to pick up the candidate keys, the best way is to analyze and form the
primary keys as much as we can.
• So, we need to identify those sets from the super key sets that alone can
identify the whole table, or we can say the other attributes of the table. Thus,
the result is:
• So, these are the three attributes obtained that can identify the other non-prime
attributes of the table. All these are the candidate keys and from which we can pick
the most appropriate attribute that can easily identify all records of the table, which
will be described as the Primary key.
c) Primary key
• A Primary Key is the minimal set of attributes of a table that is used to uniquely
identify the rows, or the tuples of the given particular table.
• Thus, a row that needs to be uniquely identified, the key constraint is set as the
Primary key to that particular field.
• A primary key can never have a NULL value because the use of the primary key is
to identify a value uniquely, but if no value will be there, how could it sustain.
Thus, the field set with the primary key constraint cannot be NULL.
• Also, it all depends on the user that the user can add or delete the key if applied.
Note:
One table can have only one primary key where it does not matter the table having one or
more columns in it.
Rules for defining Primary key:
• Two rows can't have the same primary key value
• It must for every row to have a primary key value.
• The primary key field cannot be null.
• The value in a primary key column can never be modified or updated if any foreign
key refers to that primary key.
Example:
Primary key : Emp_Id
3. Intregrity constraints
• Integrity constraints are a set of rules. It is used to maintain the quality of
information.
• Integrity constraints ensure that the data insertion, updating, and other processes
have to be performed in such a way that data integrity is not affected.
• Thus, integrity constraint is used to guard against accidental damage to the
database.
Types of Integrity constraints:
a) Entity integrity constraints
Explanation:
In the above relation, EID is made primary key, and the primary key can’t take NULL
values but in the third tuple, the primary key is null, so it is a violating Entity Integrity
constraints.
b) Referential integrity constraints
• The Referential integrity constraints is specified between two relations or tables
and used to maintain the consistency among the tuples in two relations.
• This constraint is enforced through foreign key, when an attribute in the foreign
key of relation R1 have the same domain(s) as the primary key of relation R2, then
the foreign key of R1 is said to reference or refer to the primary key of relation R2.
• The values of the foreign key in a tuple of relation R1 can either take the values of
the primary key for some tuple in relation R2, or can take NULL values, but can’t be
empty.
Example:
Explanation:
In the above, DNO of the first relation is the foreign key, and DNO in the second relation
is the primary key. DNO = 22 in the foreign key of the first table is not allowed since DNO
= 22
is not defined in the primary key of the second relation. Therefore, Referential integrity
constraints are violated here.
---------------------------------------------------x-------------------------------------------------------------
BASIC SQL
2.5
Simple Database schema, data types, table definitions (create, alter), different DML
operations (insert, delete, update), basic SQL querying (select and project) using where
clause, arithmetic & logical operations, SQL functions(Date and Time, Numeric, String
conversion).
o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.
1. Numeric Datatype
Data type Description
Int It is used to specify an integer value.
Smallint It is used to specify small integer value.
Bit It has the number of bits to store.
Decimal It specifies a numeric value that can have a decimal
number.
Numeric It is used to specify a numeric value.
---------------------------------------------------x-------------------------------------------------------------
2.7Table definitions (create, alter)
Create command:
Syntax:
Address varchar(255),
City varchar(255)
);
• The PersonID column is of type int and will hold an integer.
• The LastName, FirstName, Address, and City columns are of type varchar and will
hold characters, and the maximum length for these fields is 255 characters.
• The empty "Persons" table will now look like this:
-------x-------
Alter command:
Alter command is used for altering the table structure, such as,
Consider customers table, which consists of cust_id, name and age attributes.
1. ADD Column
Example
2.DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):
The following SQL deletes the "Email" column from the "Customers" table:
Example
3.MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
Example:
4. RENAME A TABLE
To rename a teable
5. RENAME COLUMN
EXAMPLE:
---------------------------------------------------x-------------------------------------------------------------
DML(Data Manipulation Language): The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data Manipulation
Language and this includes most of the SQL statements.
Examples of DML:
INSERT – is used to insert data into a table.
UPDATE – is used to update existing data within a table.
Consider ‘student’relation
Syntax1: Specify both the column names and the values to be inserted:
Example:
2. UPDATE Statement
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Syntax:
---------------------------------------------------x-------------------------------------------------------------
2.9Basic SQL querying (select and project) using where clause
SELECT command:
Syntax:
SELECT [DISTINCT | UNIQUE] (*, columnname [ AS alias], ……)
FROM tablename(s)
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY columnname ASC|DESC];
FROM clause is used to list the tables
WHERE clause:
WHERE keyword is used for fetching filtered data in a result set.
It is used to fetch data according to a particular criteria.
WHERE keyword can also be used to filter data by matching patterns.
The WHERE clause is not only used in the SELECT statement, but it is also used in
the UPDATE, DELETE statement, etc.,
List of operators that can be used with where clause:
operator Description
> Greater Than
>= Greater than or Equal to
< Less Than
<= Less than or Equal to
= Equal to
<> Not Equal to
BETWEEN In an inclusive Range
LIKE Search for a pattern
To specify multiple possible values for a
IN column
GROUP BY Clause:
It Forms groups
The GROUP BY clause is a SQL command that is used to group rows that
have the same values.
For example, if you want to count how many employees in each department
of the company.
It groups the databases on the basis of one or more column and aggregates
the results.
The GROUP BY clause is used in the SELECT statement and it follows the
WHERE clause and precedes the ORDER BY clause.
HAVING Clause
The HAVING Clause enables to specify conditions that filter which group results
appear in the results.
The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY clause.
SQL Having Clause is used to restrict the results returned by the GROUP BY clause.
The HAVING clause must follow the GROUP BY clause in a query and must also
precede the ORDER BY clause if used.
ORDER BY Clause:
---------------------------------------------------x-------------------------------------------------------------
(20/5)
----------
4
5. Modulus:
Query:
select12%5;
output:
12 % 5 |
----------
2
2. Logical Operations:
ALL
1 The ALL operator is used to compare a value to all values in another value
set.
AND
2 The AND operator allows the existence of multiple conditions in an SQL
statement's WHERE clause.
ANY
3 The ANY operator is used to compare a value to any applicable value in the
list as per the condition.
BETWEEN
4 The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.
EXISTS
5 The EXISTS operator is used to search for the presence of a row in a
specified table that meets a certain criterion.
IN
6 The IN operator is used to compare a value to a list of literal values that
have been specified.
LIKE
7 The LIKE operator is used to compare a value to similar values using
wildcard operators.
NOT
The NOT operator reverses the meaning of the logical operator with which
8
it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.
OR
9 The OR operator is used to combine multiple conditions in an SQL
statement's WHERE clause.
IS NULL
10
The NULL operator is used to compare a value with a NULL value.
UNIQUE
11 The UNIQUE operator searches every row of a specified table for
uniqueness (no duplicates).
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Here are some simple examples showing usage of SQL Comparison Operators −
Example 1
SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;
Output
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
Example 2
Output
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Example 3
Output
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Example 4
Output
+----+-------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+-------+-----+---------+---------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+-------+-----+---------+---------+
Example 5
Output
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
Example 6
Output
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
Example 7
Output
+-----+
| AGE |
+-----+
| 32 |
| 25 |
| 23 |
| 25 |
| 27 |
| 22 |
| 24 |
+-----+
7 rows in set (0.02 sec)
Example 8
Output
+----+--------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+--------+-----+-----------+---------+
Example 9
Output
+----+----------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
---------------------------------------------------x-------------------------------------------------------------
1. Numeric functions:
SQL Numeric Functions:
Numeric Functions are used to perform operations on numbers and return numbers.
Following are the numeric functions defined in SQL:
5. CEIL(): It returns the smallest integer value that is greater than or equal to a number.
Syntax: SELECT CEIL(25.75);
Output: 26
6. CEILING(): It returns the smallest integer value that is greater than or equal to a
number.
Syntax: SELECT CEILING(25.75);
Output: 26
SQL>SELECT DEGREES(PI());
+------------------------------------------+
| DEGREES(PI())
+------------------------------------------+
| 180.000000
+------------------------------------------+
10. DIV(): It is used for integer division.
Syntax: SELECT 10 DIV 5;
Output: 2
12. FLOOR(): It returns the largest integer value that is less than or equal to a number.
Syntax: SELECT FLOOR(25.75);
Output: 25
28. ATAN2(): It returns the arctangent of the x and y coordinates, as an angle and
expressed in radians.
Syntax: SELECT ATAN2(7);
Output: 1.42889927219073
29. TRUNCATE(): It returns 7.53635 truncated to 2 places right of the decimal point.
Syntax: SELECT TRUNCATE(7.53635, 2);
Output: 7.53
Syntax:
concat(string1, string2)
Example:
Output:
heloworld
Syntax:
LENGTH(string)
Example:
Output:
LENGTH('SECONDIT')
------------------
3. LOWER(): This function is used to convert the upper case string into lower case.
Syntax:
LOWER(string)
Example:
Output:
LOWER
-----
aliet
4. UPPER() : This function is used to convert the lower case string into upper case.
Syntax:
UPPER(string)
Example:
Output:
UPPER(
------
SQL123
5. LTRIM(): This function is used to remove the given sub string or empty spaces from
the left- hand side of the original string.
Syntax:
LTRIM(string, substring);
Example1:
Output:
LTRIM
-----
aliet
Example 2:
Output:
LTRIM
-----
Aliet
In the above example empty spaces from left side are removed.
6. RTRIM(): This function is used to remove the given sub string or empty spaces from
the right- hand side of the original string.
Syntax:
RTRIM(string, substring);
Example1:
Output:
RTRIM
-----
aliet
Example 2:
Output:
RTRIM
-----
aliet
These are functions that take values that are of datatype DATE as input and return values
of datatype DATE, except for the MONTHS_BETWEEN function, which returns a number.
1. NOW(): Returns the current date and time. FORMAT YYYY-MM-DD HH:MM:SS
Example:
SELECT NOW();
Output:
2017-01-13 08:03:52
2. CURDATE(): Returns the current date.
Example:
SELECT CURDATE();
Output:
2017-01-13
3. CURTIME(): Returns the current time.
Example:
SELECT CURTIME();
Output:
08:05:15
4. DATE(): Extracts the date part of a date or date/time expression.
Example:
SELECT DATE('2003-12-31 01:02:03');
Output:
2003-12-31
5. TIME(expr): Extracts the time part of the time or datetime expression expr and returns
it as a string.
Example:
SELECT TIME('2003-12-31 01:02:03');
Output:
01:02:03
1. TO_CHAR(value, format)
Example1:
Output:
2012-07-19
Example2:
TO_CHAR(1210.73, '9999.9')
Output:
'1210.7'
Example3:
TO_CHAR(1210.73, '$9,999.00')
Output:
' $1,210.73'
Example4:
TO_CHAR(21, '000099')
Output:
' 000021'
------------------------------------------------------------------------------------------------
2. TO_DATE (x [, date_format])
Example1:
TO_DATE('070903', 'MMDDYY')
Output:
July 9, 2003
Example2:
TO_DATE('20020315', 'yyyymmdd')
Output:
2002-Mar-15
Example3:
SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.')
FROM DUAL;
Output:
15-JAN-89
---------------------------------------------------------------------------
3. TO_NUMBER(string, format)
Example1 :
TO_NUMBER('1210.73', '9999.99')
Output:
1210.73
Example2:
TO_NUMBER('546', '999')
Output:
546
-------------------------------------------------------------------------------------
4. NVL (x, y)
If 'x' is NULL, replace it with 'y'. 'x' and 'y'must be of the same datatype.
Example1:
Output:
----------------------------------------------------------------------
5. NVLIF(exp1, exp2)
Compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it returns
NULL; else, it returns expr1. Unlike the other null handling function, first argument can't
be NULL.
Example1:
Output:
NULL
Example2:
Output:
SUN
---------------------------------------------------------------------------------------
Checks the value of 'a', if a = b, then returns'c'. If a = d, then returns 'e'. Else, returns
default_value.
Equivalence of IF..THEN..ELSE
Example:
Output:
EQUAL
---------------------------------------------------x-------------------------------------------------------------