DBMS - Notes - Unit 3
DBMS - Notes - Unit 3
RAMAPURAM CHENNAI
FACULTY OF SCIENCE AND HUMANITIES
DEPARTMENT OF COMPUTER SCIENCE AND APPLICATIONS
UNIT 3: Defining constraints through SQL – Introduction to SQL Aggregate functions – Built-in
Functions: Numeric, Date and String – SQL Joins – Creating Sub Queries – Transaction Control
Commands: Commit, Rollback and Savepoint – Relational Algebra: Fundamental Operations –
Fundamental Dependency: Trivial and Non-trivial.
NOTES
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 NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new
record, or update a record without adding a value to this field.
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT
accept NULL values when the "Persons" table is created:
CREATE TABLE Persons (ID int NOT NULL, LastName varchar(25) NOT NULL, FirstName
varchar(25) NOT NULL, Age int );
SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table is already
created, use the following SQL:
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:
To create a UNIQUE constraint on the "ID" column when the table is already created, use the
following SQL:
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use
the following SQL:
Persons Table
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
Orders Table
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table
is created:
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the following SQL:
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:
To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:
The default value will be added to all new records, if no other value is specified.
The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is
created:
Function Description
ASCII Returns the ASCII value for the specific character
CHAR_LENGTH Returns the length of a string (in characters)
CHARACTER_LENGTH Returns the length of a string (in characters)
CONCAT Adds two or more expressions together
CONCAT_WS Adds two or more expressions together with a separator
FIELD Returns the index position of a value in a list of values
FIND_IN_SET Returns the position of a string within a list of strings
FORMAT Formats a number to a format like "#,###,###.##", rounded to a
specified number of decimal places
INSERT Inserts a string within a string at the specified position and for a
certain number of characters
INSTR Returns the position of the first occurrence of a string in another
string
LCASE Converts a string to lower-case
LEFT Extracts a number of characters from a string (starting from left)
LENGTH Returns the length of a string (in bytes)
LOCATE Returns the position of the first occurrence of a substring in a string
LOWER Converts a string to lower-case
LPAD Left-pads a string with another string, to a certain length
LTRIM Removes leading spaces from a string
MID Extracts a substring from a string (starting at any position)
POSITION Returns the position of the first occurrence of a substring in a string
REPEAT Repeats a string as many times as specified
REPLACE Replaces all occurrences of a substring within a string, with a new
substring
REVERSE Reverses a string and returns the result
RIGHT Extracts a number of characters from a string (starting from right)
RPAD Right-pads a string with another string, to a certain length
RTRIM Removes trailing spaces from a string
SPACE Returns a string of the specified number of space characters
STRCMP Compares two strings
SUBSTR Extracts a substring from a string (starting at any position)
SUBSTRING Extracts a substring from a string (starting at any position)
SUBSTRING_INDEX Returns a substring of a string before a specified number of
delimiter occurs
TRIM Removes leading and trailing spaces from a string
UCASE Converts a string to upper-case
UPPER Converts a string to upper-case
Function Description
ABS Returns the absolute value of a number
ACOS Returns the arc cosine of a number
ASIN Returns the arc sine of a number
ATAN Returns the arc tangent of one or two numbers
ATAN2 Returns the arc tangent of two numbers
AVG Returns the average value of an expression
CEIL Returns the smallest integer value that is >= to a number
CEILING Returns the smallest integer value that is >= to a number
COS Returns the cosine of a number
COT Returns the cotangent of a number
COUNT Returns the number of records returned by a select query
DEGREES Converts a value in radians to degrees
DIV Used for integer division
EXP Returns e raised to the power of a specified number
FLOOR Returns the largest integer value that is <= to a number
GREATEST Returns the greatest value of the list of arguments
LEAST Returns the smallest value of the list of arguments
LN Returns the natural logarithm of a number
LOG Returns the natural logarithm of a number, or the logarithm of a
number to a specified base
LOG10 Returns the natural logarithm of a number to base 10
LOG2 Returns the natural logarithm of a number to base 2
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
MOD Returns the remainder of a number divided by another number
PI Returns the value of PI
POW Returns the value of a number raised to the power of another
number
POWER Returns the value of a number raised to the power of another
number
RADIANS Converts a degree value into radians
RAND Returns a random number
ROUND Rounds a number to a specified number of decimal places
SIGN Returns the sign of a number
SIN Returns the sine of a number
SQRT Returns the square root of a number
SUM Calculates the sum of a set of values
TAN Returns the tangent of a number
TRUNCATE Truncates a number to the specified number of decimal places
Function Description
ADDDATE Adds a time/date interval to a date and then returns the date
ADDTIME Adds a time interval to a time/datetime and then returns the
time/datetime
CURDATE Returns the current date
CURRENT_DATE Returns the current date
CURRENT_TIME Returns the current time
CURRENT_TIMESTAMP Returns the current date and time
CURTIME Returns the current time
DATE Extracts the date part from a datetime expression
DATEDIFF Returns the number of days between two date values
DATE_ADD Adds a time/date interval to a date and then returns the date
DATE_FORMAT Formats a date
DATE_SUB Subtracts a time/date interval from a date and then returns the
date
DAY Returns the day of the month for a given date
DAYNAME Returns the weekday name for a given date
DAYOFMONTH Returns the day of the month for a given date
DAYOFWEEK Returns the weekday index for a given date
DAYOFYEAR Returns the day of the year for a given date
EXTRACT Extracts a part from a given date
FROM_DAYS Returns a date from a numeric datevalue
HOUR Returns the hour part for a given date
LAST_DAY Extracts the last day of the month for a given date
LOCALTIME Returns the current date and time
LOCALTIMESTAMP Returns the current date and time
MAKEDATE Creates and returns a date based on a year and a number of days
value
MAKETIME Creates and returns a time based on an hour, minute, and second
value
MICROSECOND Returns the microsecond part of a time/datetime
MINUTE Returns the minute part of a time/datetime
MONTH Returns the month part for a given date
MONTHNAME Returns the name of the month for a given date
NOW Returns the current date and time
PERIOD_ADD Adds a specified number of months to a period
PERIOD_DIFF Returns the difference between two periods
QUARTER Returns the quarter of the year for a given date value
SECOND Returns the seconds part of a time/datetime
SEC_TO_TIME Returns a time value based on the specified seconds
STR_TO_DATE Returns a date based on a string and a format
SUBDATE Subtracts a time/date interval from a date and then returns the
date
SUBTIME Subtracts a time interval from a datetime and then returns the
time/datetime
SYSDATE Returns the current date and time
TIME Extracts the time part from a given time/datetime
TIME_FORMAT Formats a time by a specified format
TIME_TO_SEC Converts a time value into seconds
TIMEDIFF Returns the difference between two time/datetime expressions
TIMESTAMP Returns a datetime value based on a date or datetime value
TO_DAYS Returns the number of days between a date and date "0000-00-
00"
WEEK Returns the week number for a given date
WEEKDAY Returns the weekday number for a given date
WEEKOFYEAR Returns the week number for a given date
YEAR Returns the year part for a given date
YEARWEEK Returns the year and week number for a given date
Examples:
As the name shows, JOIN means to combine something. In case of SQL, JOIN means
"to combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
(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
Sample Table
EMPLOYEE
1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables
as long as the condition is satisfied. It returns the combination of all rows from
both the tables where the condition satisfies.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,….
2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values
from the right table. If there is no matching join value, it will return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,….
2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and
the matched values from the left table. If there is no matching in both tables, it will return
NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,…
2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables
have all the records from both tables. It puts NULL on the place of matches not found.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output
EMP_NAME DEPARTMENT
Angelina Testing
Robert Development
Christian Designing
Kristen Development
Russell NULL
Marry NULL
SUBQUERIES
CORRELATED SUBQUERY
A correlated subquery is evaluated once for each row processed by the parent statement. The
parent statement can be a SELECT, UPDATE, or DELETE statement.
A nested query (also called a subquery) is a query embedded within another SQL query. The
result of the inner query is used by the outer query to perform additional operations.
Subqueries can be used in various parts of an SQL query such as SELECT, FROM or WHERE
Clauses.
The inner query runs first, providing data for the outer query.
The output query uses the results of the inner query for comparison or as input.
Nested queries are particularly useful for breaking down complex problems into smaller,
manageable parts, making it easier to retrieve specific results from large datasets.
SELECT last_name, salary, department_id FROM employees outer WHERE salary >
(SELECT AVG(salary) FROM employees WHERE department_id = outer.department_id
group by department_id);
Using the EXISTS Operator:
The EXISTS operator tests for existence of rows in the results set of the subquery. If a
subquery row value is found the condition is flagged TRUE and the search does not continue
in the inner query, and if it is not found then the condition is flagged FALSE and the search
continues in the inner query.
OUTPUT:
OUTPUT:
A nested query is a query that has another query embedded within it.
The embedded query is called a subquery.
A subquery typically appears within the WHERE clause of a query. It
can sometimes appear in the FROM clause or HAVING clause.
Example
Let’s learn about nested queries with the help of an example. Find the names of employee who
have regno=103. The query is as follows −
select E.ename from employee E where E.eid IN (select S.eid from salary S where
S.regno=103);
Output
Example
Output
Example 1
Select AVG(noofstudents) from class where teacherID IN( Select id from teacher where
subject=’science’ OR subject=’maths’);
Output
You will get the following output −
20.0
Example 2
Output
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or
DELETE, the changes made by these commands are not permanent,
until the current session is closed, the changes made by these
commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last commited state. It is also used with
SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and
realize that those changes were not required, then we can use the ROLLBACK command
to rollback those changes, if they were not committed using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can
rollback to that point whenever required.
Following is savepoint command's syntax,
SAVEPOINT Savepoint_name;
In short, using this command we can name the different states of our
data in any table and then rollback to that state using the ROLLBACK
command whenever required.
NOTE: SELECT statement is used to show the data stored in the table. The resultant table will
SELECT * FROM class;
look like,
Id Name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Now let's use the ROLLBACK command to roll back the state of data to the savepoint B.
ROLLBACK TO B;
Now let's again use the ROLLBACK command to roll back the state of data to
the savepoint A
ROLLBACK TO A;
Id Name
1 Abhi
2 Adam
4 Alex
5 Abhijit
Relational database systems are expected to be equipped with a query language that can assist
its users to query the database instances. There are two kinds of query languages − relational
algebra and relational calculus.
Relational Algebra
Output − Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" and price = "450" or year > "2010"(Books)
Output − Selects tuples from books where subject is 'database' and 'price' is 450
or those books published after 2010.
Selects and projects columns named as subject and author from the relation
Books.
The result of set difference operation is tuples, which are present in one relation
but are not in the second relation.
Notation − r − s
Finds all the tuples that are present in r but not in s.
∏ author (Books) − ∏ author (Articles)
Output − Provides the name of authors who have written books but not articles.
r Χ s = { q t | q ∈ r and t ∈ s}
σauthor = 'tutorialspoint'(Books Χ Articles)
Output − Yields a relation, which shows all the books and articles written by tutorialspoint.
The results of relational algebra are also relations but without any name. The
rename operation allows us to rename the output relation. 'Rename' operation
is denoted with small Greek letter rho ρ.
Notation − ρ x (E)
FUNCTIONAL DEPENDENCY
A functional dependency occurs when the value of one attribute (or a set of attributes) uniquely
determines the value of another attribute. This relationship is denoted as:
X→Y
Here, X is the determinant, and Y is the dependent attribute. This means that for each unique
value of X, there is precisely one corresponding value of Y.
42 Abc 17
43 Pqr 18
44 Xyz 18
Example:
42 Abc 17
43 Pqr 18
44 Xyz 18
Here, roll_no → name is a non-trivial functional dependency, since the dependent name is not
a subset of determinant roll_no. Similarly, {roll_no, name} → age is also a non-trivial
functional dependency, since age is not a subset of {roll_no, name}