Professional Documents
Culture Documents
Database
A database is an organized collection of data, so that it can be easily accessed and managed.
You can organize data into tables, rows, columns, and index it to make it easier to find relevant
information.
Database handlers create a database in such a way that only one set of software program provides access
of data to all the users.
The main purpose of the database is to operate a large amount of information by storing, retrieving, and
managing data.
Creating Tables
Syntax
The basic syntax of the CREATE TABLE statement is as follows −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows the
CREATE TABLE statement.
Data Types
SQL Data Type is an attribute that specifies the type of data of any object. Each column,
variable and expression has a related data type in SQL. You can use these data types while
creating your tables. You can choose a data type for a table column based on your
requirement.
SQL Server offers six categories of data types for your use which are listed below −
Exact Numeric Data Types
tinyint 0 255
bit 0 1
Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute
accuracy.
char
1
Maximum length of 8,000 characters.( Fixed length non-Unicode characters)
varchar
2
Maximum of 8,000 characters.(Variable-length non-Unicode data).
varchar(max)
3 Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL Server
2005 only).
text
4
Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.
nchar
1
Maximum length of 4,000 characters.( Fixed length Unicode)
2 nvarchar
Maximum length of 4,000 characters.(Variable length Unicode)
nvarchar(max)
3
Maximum length of 2E + 31 characters (SQL Server 2005 only).( Variable length Unicode)
ntext
4
Maximum length of 1,073,741,823 characters. ( Variable length Unicode )
binary
1
Maximum length of 8,000 bytes(Fixed-length binary data )
varbinary
2
Maximum length of 8,000 bytes.(Variable length binary data)
varbinary(max)
3
Maximum length of 2E + 31 bytes (SQL Server 2005 only). ( Variable length Binary data)
image
4
Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data)
sql_variant
1 Stores values of various SQL Server-supported data types, except text, ntext, and
timestamp.
2 timestamp
Stores a database-wide unique number that gets updated every time a row gets updated
uniqueidentifier
3
Stores a globally unique identifier (GUID)
xml
4 Stores XML data. You can store xml instances in a column or a variable (SQL Server 2005
only).
cursor
5
Reference to a cursor object
table
6
Stores a result set for later processing
Authorization
Authorization is a privilege provided by the Database Administer. Users of the database can
only view the contents they are authorized to view. The rest of the database is out of bounds
to them.
Context sensitive permission - This is related to sensitive content and only granted
to a select users.
System Control - This is the highest control authorization for a user. This allows
maintenance operations on the database but not direct access to data.
System Maintenance - This is the lower level of system control authority. It also
allows users to maintain the database but within a database manager instance.
System Monitor - Using this authority, the user can monitor the database and take
snapshots of it.
Structured Query Language (SQL) as we all know is the database language by the use of
which we can perform certain operations on the existing database and also we can use this
language to create a database. SQL uses certain commands like Create, Drop, Insert, etc. to
carry out the required tasks.
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
o DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
o REATE
o ALTER
o DROP
o TRUNCATE
Syntax:
1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB D
ATE);
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
1. DROP TABLE ;
Example
1. DROP TABLE EMPLOYEE;
c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
1. ALTER TABLE table_name ADD column_name COLUMN-definition;
1. ALTER TABLE MODIFY (COLUMN DEFINITION....);
EXAMPLE
1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.
Syntax:
1. TRUNCATE TABLE table_name;
Example:
1. TRUNCATE TABLE EMPLOYEE;
o DML commands are used to modify the database. It is responsible for all form of
changes in the database.
o 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.
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.
Syntax:
1. INSERT INTO TABLE_NAME
2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);
Or
1. INSERT INTO TABLE_NAME
2. VALUES (value1, value2, value3, .... valueN);
For example:
1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [W
HERE CONDITION]
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
Syntax:
1. DELETE FROM table_name [WHERE condition];
For example:
1. DELETE FROM javatpoint
2. WHERE Author="Sonoo";
DCL commands are used to grant and take back authority from any database user.
o Grant
o Revoke
Example
1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USE
R;
Example
1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE
only.
These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.
Here are some commands that come under TCL:
o COMMIT
o ROLLBACK
o SAVEPOINT
Syntax:
1. COMMIT;
Example:
1. DELETE FROM CUSTOMERS
2. WHERE AGE = 25;
3. COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.
Syntax:
1. ROLLBACK;
Example:
1. DELETE FROM CUSTOMERS
2. WHERE AGE = 25;
3. ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
o SELECT
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
A SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them. Different types of Joins are:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
The simplest Join is INNER JOIN.
INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as
the condition satisfies. This keyword will create the result-set by combining all rows from
both the tables where the condition satisfies i.e value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2 ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.
Example Queries(INNER JOIN)
This query will show the names and age of students enrolled in different courses.
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
LEFT JOIN: This join returns all the rows of the table on the left side of the join and
matching rows for the table on the right side of join. The rows for which there is no
matching row on right side, the result-set will contain null. LEFT JOIN is also known as
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table matching_column: Column common to both the tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are same.
RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the
table on the right side of the join and matching rows for the table on the left side of join.
The rows for which there is no matching row on left side, the result-set will contain null.
RIGHT JOIN is also known as RIGHT OUTER JOIN.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table matching_column: Column common to both the tables.
Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of a
table.
Sample table:
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Detail
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
1. CREATE VIEW view_name AS
2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;
In this example, we create a View named DetailsView from the table Student_Detail.
Query:
1. CREATE VIEW DetailsView AS
2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. WHERE STU_ID < 4;
Just like table query, we can query the view to view the data.
1. SELECT * FROM DetailsView;
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
View from multiple tables can be created by simply include multiple tables in the SELECT
statement.
In the given example, a view is created named MarksView from two tables Student_Detail
and Student_Marks.
Query:
1. CREATE VIEW MarksView AS
2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARK
S
3. FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;
1. SELECT * FROM MarksView;
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
Syntax
1. DROP VIEW view_name;
Example:
1. DROP VIEW MarksView;
In this section, we introduce two additional features of SQL: the CREATE
ASSERTION statement and the CREATE TRIGGER statement.
CREATE TRIGGER was introduced to specify automatic actions that the database system
will perform when certain events and conditions occur. This type of functionality is generally
referred to as active data-bases. We only introduce the basics of triggers in this chapter, and
present a more complete discussion of active databases.
The basic technique for writing such assertions is to specify a query that selects any
tuples that violate the desired condition. By including this query inside a NOT
EXISTS clause, the assertion will specify that the result of this query must be empty so that
the condition will always be TRUE. Thus, the assertion is violated if the result of the query is
not empty. In the preceding example, the query selects all employees whose salaries are
greater than the salary of the manager of their department. If the result of the query is not
empty, the assertion is violated.
Note that the CHECK clause and constraint condition can also be used to specify constraints
on individual attributes and domains and on individual tuples. A major difference
between CREATE ASSER-TION and the individual domain constraints and tuple constraints
is that the CHECK clauses on individual attributes, domains, and tuples are checked in
SQL only when tuples are inserted or updated. Hence, constraint checking can be imple-
mented more efficiently by the DBMS in these cases. The schema designer should
use CHECK on attributes, domains, and tuples only when he or she is sure that the constraint
can only be violated by insertion or updating of tuples. On the other hand, the schema
designer should use CREATE ASSERTION only in cases where it is not possible to
use CHECK on attributes, domains, or tuples, so that simple checks are implemented more
efficiently by the DBMS.
Suppose we want to check whenever an employee’s salary is greater than the salary of his or
her direct supervisor in the COMPANY database. Several events can trigger this rule:
inserting a new employee record, changing an employee’s salary, or changing an employee’s
supervisor. Suppose that the action to take would be to call an external stored
procedure SALARY_VIOLATION, which will notify the supervisor. The trigger could then
be written as in R5 below. Here we are using the syntax of the Oracle database system.
WHERE SSN = NEW.SUPERVISOR_SSN ) )
INFORM_SUPERVISOR(NEW.Supervisor_ssn, NEW.Ssn );
The event(s): These are usually database update operations that are explicitly
applied to the database. In this example the events are: inserting a new employee record,
changing an employee’s salary, or changing an employee’s supervisor. The person who
writes the trigger must make sure that all possi-ble events are accounted for. In some cases, it
may be necessary to write more than one trigger to cover all possible cases. These events are
specified after the keyword BEFORE in our example, which means that the trigger should be
executed before the triggering operation is executed. An alternative is to use the
keyword AFTER, which specifies that the trigger should be executed after the operation
specified in the event is completed.
The condition that determines whether the rule action should be executed: Once the
triggering event has occurred, an optional condition may be evaluated. If no condition is
specified, the action will be executed once the event occurs. If a condition is specified, it is
first evaluated, and only if it evaluates to true will the rule action be executed. The condition
is specified in the WHEN clause of the trigger.
Relational Algebra
Notation: σ p(r)
Where:
p is used as a propositional logic formula which may use connectors like: AND
OR and NOT. These relational can use as relational operators like =, ≠, ≥, <, >,
≤.
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
2. Project Operation:
o This operation shows the list of those attributes that we wish to appear in the
result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.
1. Notation: ∏ A1, A2, An (r)
Where
Input:
1. ∏ NAME, CITY (CUSTOMER)
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
3. Union Operation:
o Suppose there are two tuples R and S. The union operation contains all the
tuples that are either in R or S or both in R & S.
1. Notation: R ∪ S
Example:
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Input:
1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
4. Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in both R & S.
o It is denoted by intersection ∩.
1. Notation: R ∩ S
Input:
1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Smith
Jones
5. Set Difference:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
1. Notation: R - S
Input:
1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
6. Cartesian product
o The Cartesian product is used to combine each row in one table with each row
in the other table. It is also known as a cross product.
o It is denoted by X.
1. Notation: E X D
Example:
EMPLOYEE
1 Smith A
2 Harry C
3 John B
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
1. EMPLOYEE X DEPARTMENT
Output:
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
7. Rename Operation:
1. ρ(STUDENT1, STUDENT)
Join Operation
Theta join combines tuples from different relations provided they satisfy the theta condition.
The join condition is denoted by the symbol θ.
Notation
R1 ⋈θ R2
R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the
attributes don’t have anything in common, that is R1 ∩ R2 = Φ.
Theta join can use all kinds of comparison operators.
Student
SID Name Std
101 Alex 10
102 Maria 11
Subjects
Class Subject
10 Math
10 English
11 Music
11 Sports
Student_Detail −
STUDENT ⋈Student.Std = Subject.Class SUBJECT
Student_detail
When Theta join uses only equality comparison operator, it is said to be equijoin. The above
example corresponds to equijoin.
Natural join does not use any comparison operator. It does not concatenate the way a
Cartesian product does. We can perform a Natural Join only if there is at least one common
attribute that exists between two relations. In addition, the attributes must have the same
name and domain.
Natural join acts on those matching attributes where the values of attributes in both the
relations are same.
Courses
CS01 Database CS
ME01 Mechanics ME
EE01 Electronics EE
HoD
Dept Head
CS Alex
ME Maya
EE Mira
Courses ⋈ HoD
Outer Joins
Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only
those tuples with matching attributes and the rest are discarded in the resulting relation.
Therefore, we need to use outer joins to include all the tuples from the participating relations
in the resulting relation. There are three kinds of outer joins − left outer join, right outer join,
and full outer join.
All the tuples from the Left relation, R, are included in the resulting relation. If there are
tuples in R without any matching tuple in the Right relation S, then the S-attributes of the
resulting relation are made NULL.
Left
A B
100 Database
101 Mechanics
102 Electronics
Right
A B
100 Alex
102 Maya
104 Mira
Courses HoD
A B C D
All the tuples from the Right relation, S, are included in the resulting relation. If there are
tuples in S without any matching tuple in R, then the R-attributes of resulting relation are
made NULL.
Courses HoD
A B C D
Courses HoD
A B C D
ROLL_NO
2
References
1. https://www.javatpoint.com/dbms-tutorial
2. https://www.geeksforgeeks.org/dbms/
3. https://www.tutorialspoint.com/dbms/index.htm
4. Elmasri, R., et al. Fundamentals of Database Systems</Title.
Addison-Wesley</publisher, 2000.
5. Silberschatz, Abraham, Henry F. Korth, and Shashank Sudarshan. Database
system concepts. Vol. 4. New York: Mcgraw-hill, 1997.