Unit-2 (DBMS)
Unit-2 (DBMS)
2.3 Describe Naming of the Objects and parts and how to refer them.
2.4 Explain literals & different data types like character, number, long, date, raw and long raw
2.7 Describe Data Definition Language commands CREATE, ALTER and DROP.
2.8 Explain integrity constraints through creating a table and altering table.
2.9 Describe Data Manipulation Language commands INSERT, UPDATE and DELETE
2.10 Explain SELECT statement with WHERE, ORDER BY, GROUP BY and HAVING clauses with examples
2.11 List and explain single row (Number, character, date and conversion) functions
2.15 Explain Joins (Equi Join, Non-Equi Joins, Inner Join, Outer Join, cross join and Self join) with syntax and examples.
2.1 SQ1 & Benifits of SQL
Structured Query Language specially designed to interact with relational database.
It is a language for storing, manipulating & retriving data in RDBMS. The software that
supporting for sql are Oracle, MS Access, Informix, MS SQL etc.
It is used to control the functions of DBMS for users including
Data Definition: Sql allows was to define Structure & organization of the stored data &
relationship among the stored data.
Data Retrieval: allows users to retrieve. the stared data from the database & use it.
Data Manipulation: allows users to update the database by adding new data & removing old
data & modifying previous data.
Access control: restrict the ability to retrieve, add & modify Protecting stored data against
unauthorized users.
Data sharing:-Used to coordinate data sharing by Concurrent users, ensuring they don't interface
with one another
Data integrity: Integrity constraints in database, protecting it. from inconsistent updates &
system failures
Benefits of Sql:
Sql standard: In 1986 & 1987, ANSI (American National standards Institute & Iso international
standard organization) Standardized language. The most recent standard part was produced in
2011
Portable: Sql rans on Pcs, laptops, servers, tables, & Smart phones. It runs in local system
intranet & internet. It can be moved from device to another.
open source: Fiee databases from MySQL, mariaDB etc Can be sql databases can be used in low
cost large Communities behind them
Used by major DBMS System vendors: Sql used by all vendors such as IBM, Oracle &
microsoft who develop dbms.
Easy to learn & understand: Queries are like English statement makes easy to Learn & write.
Interactive language: Sql used to communicate with db & get answers for Complex Queries in
Seconds
Complete Language for a database: Sal create db, updating, retrieving & sharing data with
multiple users, and also data remains accurate, secure & consistent
Multiple data views: different users of dib can have different views of structure & content of db.
Client/server language: Sql used to connect client's (front end computers) & servers (back end
computers),Thus supports Client Server architecture.
It distinguished by enclosing it between EXEC SQL BEGIN & matching EXEC SQL END(;).
The high level language which supports Embedding SQLs is known as host language. when
SOL Embedded with a language then Compilation poses two steps:
1.Extract sql codes & pre compiler will complete Sal oracle from its Syntax, execution path.
2.Once pre-compilation is done, these executable codes embedded into Code then the compiler
compile & execute the code.
compilation will be done in two steps-ore for sql gone for application Language. this
compilation needs Query, data value. the compilation time itself to generate executable code.
Otherwise any high level language cannot compile the code.
Hence Sql codes are static & Embedded Sql is knowns static sql. Thus sql know how to
access DB, which Queries to execute, values to insert/delete/update
Structure of Embedded sql:-
↳ It shows the process of establishing connection & Executing code in DB within high level
language
(i)Connection of DB
step 1-Connecting DB. will be done by using keyword CONNECT can be procced with "Exec
sql” indicates Sql statement
* Host variables that used to pass the value to the Query & returns the values - this variables
should be within the Sql so that Compiler differentiate from normal c variables between Begin
Declare & end declare
EXEC SQL BEGIN DECLARE SECTION;
int STD_ID;
Char STD_name[15];
EXEC SQL SELECT ENAME, SAL INTO: NAME: SALARY FROM EMPLOYEE WHERE
END=23;
PRINT NAME, SALARY;
LEXICAL CONVENTION:
SQL statement are composed of commands, Variables, & Operators
Sql constructed from, Characters (A tot)..
2.3 NAMING OF THE OBJECCTS AND PARTS AND HOWTO REFER THEM
Naming rules used to increase the readability of data which user apply rules while naming
anything in db, including tables, columns Primary & foreign keys, functions, views etc. for
instance, it would be f to tables & Columns Perfectly to limit naming Conversion rules to tables
& columns.
Naming Rules:
→ Only letters, numbers & underscores are allowed (Oracle allows $ and # which causes
unexpected problems.
→ All names in UPPER CASE (no importance which care it help to & identify easily without
clumsy) rale can be ignored.
*@dblink = It is used when the object is in other db or remote db If you not use @dblink it will
not allows you to accesses.
1)Oracle first cooks the Object in your own schema (your db) if the object with private synonym
it will point to your schema point to of another schema! If it. points to another synonym, oracle
will follow the chain until of finds actual object
2) Oracle finds the object, it perform the sql operation (Like insert) which is correct type of
object.
for INSERT, the object must be table or view (8f it is not in sequence oracle shows errors).
3) The object isn't in your schema of private synonyms then Oracle looks in Public Synonyms
(Shortcut available to everyone in db) still not find then it gives the error.
*Rule of Synonyms:
*Public Synonym has dependent Objects tables of user defined) you can't Create another object
with Same name
--If doesn't have dependent Object you can create new object with same name
Ex: DROP TABLE hr. employees; (delete the employees tables on the hr schema)
→The name of the database link is different from regular Object names.
It can contain dots (.) and @sign
2.4 LITERALS & DIFFERENT DATA TYPES LIKE CHARACTER, NUMBER, LONG,
DATE, RAW AND LONG RAW ETC.
A literal is an explicit numeric, character, string, or Boolean value not represented by an
identifier. Literal items and constant value are synonymous and refer to a fixed data value.
1. String Literals
2. Numeric Literals
3. Boolean Literals
4. Date and Time Literals
String Literals:
string literal examples contain strings enclosed in single quotes (‘).Use the text literal notation to
specify whenever string appears in the syntax of expressions, conditions, SQL functions, and
SQL statements.
Examples:
'apstbet.net' 'This is SQL' '09-MAR-98' '1563'
Numeric Literals:
Numeric literal notation used to specify fixed and floating-point numbers. Integer literals and
decimal literals come under this.
Integer literals can be either positive numbers or negative numbers, but do not contain
decimals. If a sign is not specified, then a positive number is assumed.
Decimal literals:
Decimal Literals can be either positive numbers or negative numbers and contain decimals.
Examples: 25,-25,16.34,-36.03
Datetime Literals:Datetime literals are character representations of datetime values that are
enclosed in single quotes. Here are some examples of valid datetime literals:
DATE Literals:You can specify a DATE value as a string literal, or you can convert a character
or numeric value to a date value with the TO_DATE function.
TIMESTAMP Literals:
The TIMESTAMP data type stores year, month, day, hour, minute, and second, and fractional
second values.
A data type associates a fixed set of properties with the values that can be stored in a column of a
table or in an argument of a procedure.
For example, one property of the NUMBER data type is precision.
For example, columns can hold values of NUMBER data type, but not values of RAW data type.
Oracle supplies the following built-in data types:
BLOB It is used to specify unstructured binary data. Its range goes up to 2^32 - 1 bytes or 4
GB.
BFILE It is used to store binary data in an external file. Its range goes up to 2^32 - 1 bytes
or 4 GB.
CLOB It is used for single-byte character data. Its range goes up to 2^32 - 1 bytes or 4GB.
NCLOB It is used to specify single-byte or fixed length multibyte national character set
(NCHAR) data. Its range is up to 2^32 - 1 bytes or 4 GB.
RAW(size) It is used to specify variable length raw binary data.Its range is up to 2000 bytes per
row. Its maximum size must be specified.
LONG It is used to specify variable length raw binary data. Its range up to 2^31-1 bytes or
RAW 2GB, per row
NUMBER: This data type is used to store the numeric data. This data type can be used in three
forms.
a.NUMBER: In this form we don't need to specify the number of digits to be stored in a
particular field.
Example: create table student (fees number (5)); //maximum five digits i.e. 99999.
c.NUMBER (P, S): Thenumber of digits after point which can be stored in a field of NUMBER
type. Here P is called precision and S is known as scale
Example: create table student (fees number (7,2)); //a numeric value of maximum seven
digits and which can on two digits after decimal point i.e. 99999.99
CHAR: This data type is used to store alphabets, digits, special characters as well as spaces. This
data type is used fixed length string data. The field of this data type can store maximum of 255
characters.
If the value stored in this type of field has lesser numberof characters than the maximum size
then blank spaces will be filled in rest of the size.
Example:create table student(name char(20)); //contain 20 characters
NCHAR:NCHAR data type is similar to the CHAR data type, except that it stores Unicode data
It can store up 00 bytes and must be shorter than 2000 characters.
Example: create table student (name nchar(20)); //maximum of 20 characters.
VARCHAR: A variable-length string data type that stores letters, digits, special characters, and
spaces, up to 2000 characters. Unused space is not wasted and can be used by other fields.
LONG: This data type is also used to store variable length character string containing upto 2GB
of data. Long values can't be indexed and string operations can't be applied on field of this data
type.
Example:create table student(resume LONG);
LONG RAW/RAW: This data type stores binary data like images. RAW fields can hold up to
255 bytes, while LONG RAW fields can store up to 2GB.
Example: create table student (resume RAW);
BLOB: BLOB stores unstructured binary large objects (not character data) with a maximum size
of 4GB. Size can be specified using:
BLOB(length [K|M|G]) where K = kilobytes, M = megabytes, and G = gigabytes. If not
specified, the default size is used value is 4 GB. It's useful for storing images or audio files.
Example: create table student(photo BLOB(10k));//photo can contain upto 10 Kilo Bytes of
data.
CLOB: CLOB stores large amounts of character (text) data, not binary data, with a maximum
size of 4GB.
Size can be set using: CLOB(length [K|M|G]), where K = kilobytes, M = megabytes, and G =
gigabytes. If not specified, the default is 4GB. Useful for storing large text that exceeds
VARCHAR2 limits.
pseudo-column: A pseudo-column behaves like a table column but is not actually stored in the
table. Pseudo columns are nothing but logical columns which behaves like physical columns in
database. We can select from pseudo-columns, but we cannot insert, update, or delete their
values.Some pseudo-columns are:
ROWID is the permanent identity or address of a row which one can easily access (retrieve data
from a row the rows from the table.A user can access a row quickly and easily using its row ID.
ROWID can also be used to delete normal records and the duplicate records from a table.
SINGLE-LINE COMMENTS:Comments that begin and end with a single line are called
Single line comments.Single line comments start with A comment which starts with '-' is not
executed, and the text between double hyphen) and the end of the line will be ignored without
being run.
MULTI-LINE COMMENTS:Multi-line comments start with /* and end with */. Any text
between /* and */ will be ignored:
IN-LINE COMMENTS:To ignore just a part of a statement, also use the /* */ comment.
SELECT id, customer_name, /* city, */ countryFROM customers;
COMMENTS WITHIN SCHEMA OBJECTS:For comments on database objects, such as
views and tables, the syntax to add these explicit comments:
comment on [database object type) <database object name> is 'comment text here’ These
database object-level comments are more useful for adding additional context or metadata to
these inline comments being useful for explaining code functionality. Use the COMMENT
statement to a comment about a table, view, materialized view, or column into the data
dictionary.
Example:
COMMENT ON COLUMN employees.job_id IS 'describe job title';
COMMENT ON COLUMN books.author IS The main author's last name':
COMMENT ON TABLE books IS 'Contains only the best books';
To drop this comment from the database, issue the following statement:
unary Negative Operator: TheSQL Negative (-) operator makes the numeric value of the SOL
table negative.
unary Bitwise NOT Operator: The SOL Bitwise NOT ~ operator provides the one's
complement of the single numeric operand. This operator turns each bit of numeric value. If the
bit of any numerical value is 001100, then this operator turns these bits into 110011.
Binary Operators:binary operator uses two operands. A binary operator appears with its
operands in the following format Syntax: operand1 operator operand2
Other operators with special formats accept more than two operands. If an operator is given a
null operand, the result is always null. The only operator that does not follow this rule is
concatenation (||).
Arithmetic Operators
Comparison Operators
Logical Operators
Set Operators
Bit-wise Operators
ARITHMETIC OPERATORS:These operators are used to perform operations such as
addition, multiplication, subtraction etc.
Operator Operation Description
- Subtraction Subtract right hand side value to left hand side value.
/ Division Divides right hand side value to left hand side value.
% Modulus Divides right hand side value to left hand side value. and returns remainder.
Logical operators:
Operators Description
All Used to compare specific value with other values in a set
Any Used to compare specific value with any other value is a set
IN Used to compare a specific value to literal values mentioned
BETWEEN Searches for values within range mentioned
And Allows the user to mention multiple condition in where clause
or Combines multiple conditions in where clause
NOT Used to reverse the output of the logical operator
Exists Used to search for the row’s presence in table
like Compares a pattern using wildcard operators
some Similar to any, compares a specific value to some of the values present in a set.
Example: SELECT *from Employee WHERE Salary BETWEEN 20000 AND 50000;
Bitwise Operator: It perform the bit operation on the integer values.To understand this concept
you just knew basics of Boolean algebra.
1) Bitwise AND(&)
2) Bitwise OR(|)
3) Bitwise NOT operator(~)
Set Operator: A set operator is a keyword that combines the result of two queries into a single
query. Queries containing set operator called compound queries. They are
a. Union
b. Union all
c. Intersect
d. Minus
SYNTAX: Select query SET_OPERATOR Select Another query;
a. Union: The union operation eliminates the duplicate rows from its resultset. This set
operation is applied only when the no.of datatype and column must be same in both
tables.
Operators Operation
+,- Identity, negation
*,/ Multiplication, division
+,-,|| Addition, subtraction,concatenation
=,!=, <,>,<=,>=,IS,NULL,LIKE BETWEEN,IN Comparision
NOT Exponentation,logical negation
AND Conjuction
OR disjunction
Example:1+2*3 (2*3 = 6 = => 6+1= 7)
PRIMARY KEY-A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table. This ensures that values in a column (or several columns) match values in another
table's column/s.
FOREIGN KEY - Prevents actions that would destroy links between tables this ensures that
values in a column (or several columns) match values in another table's column/s.
CHECK-Ensures that the values in a column satisfies a specific condition
DEFAULT-Sets a default value for a column if no value is specified
We may apply integrity Constraints at the column or table level. The table-level Integrity
constraints pply to the entire table, while the column level constraints are only applied to one
column.
“After the table is created, as part of the ALTER TABLE (or ALTER VIEW) statement”
Syntax (using Create Table):
The basic syntax of creating an SQL constraint using the CREATE TABLE command is:
ename VARCHAR2(200) NOT NULL, --ensure the ename field cannot be null.
salary NUMBER(10), doj DATE, deptid NUMBER(10));
UNIQUE CONSTRAINT: Unique constraint implies no duplicate values for the column. This
is also a type of integrity constraint, h's similar to a primary key, but it can only accept one null
value and cannot have duplicate values.“A PRIMARY KEY constraint automatically has a
UNIQUE constraint”, However, we can have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.
UNIQUE CONSTRAINT using CREATE TABLE statement
Ex:CREATE TABLE Student( ID int NOT NULL, FirstName varchar(25), LastName
varchar(25), Age int,
PRIMARY KEY CONSTRAINT: A primary key is a field in a database table that uniquely
identifies each row/record. This is also one of Integrity Constraint. A table can only have one
primary key, which can be made up of one or more fields. creates a composite key when several
fields are used as a primary key. Primary keys must contain UNIQUE values, and cannot contain
NULL values.
FOREIGN KEY CONSTRAINT: A foreign key constraint is used to create a link between a
column(s) in one table and a priman relates to a record 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. The primary key or unique key referenced by the foreign key must already be
created on the reference table. Both tables (the table that has the primary key and the table that
has the foreign key) must be on the same database.
Each row in the table must ensure the condition is true, or is unknown due to a NULL value. A
check constraint can be created as:
Syntax: “Create table <table name> (<column name> <data type> constraint <constraint name>
check (column name with condition));”
CHECK CONSTRAINT using CREATE TABLE statement
Ex: CREATE TABLE VOTING_LIST(ID int PRIMARY KEY , Name NVARCHAR(50) NOT
NULL, Age int NOT NULL CHECK(Age >=18));
CHECK CONSTRAINT using ALTER TABLE statement
Ex:ALTER TABLE Voting_List ADD CHECK (Age>=1));
DEFAULT CONSTRAINT: The DEFAULT constraint is used to set a default value for a
column. The default value will be added to all new records, if no other value is specified.
SQL functions some times take arguments and always return a value.
There are two types of functions in SQL:
1)Single row functions: Single row or Scalar functions return a value for every row that is
processed in a query.
X
There are four types of single row functions:
1) Numeric functions: Numerical functions are used to perform operations on
numbers.These are functions that accept numeric input and return numeric values as
output.
3) Data Functions: These are the function s that take values that are of datatypes DATE as
input and return the values of datatype DATE, expect for the MONTHS_BETWEEN
function, which returns a number.
Function name Returns Values
ADD_MONTHS Returns a date value after adding ‘n’ months to the date’x’
(date,n) Ex:SELECT ADD_MONTHS(’27-Aug-25’,3); --27-Nov-25
MONTHS_BETWEEN Returns the no.of months between dates x1,x2
(x1,x2) Ex: SELECT MONTHS_BETWEEN(’27-Aug-25’,’27-Nov-25); --3
ROUND(x, date_format) Returns nearest date ‘x’ nearest century,year, month,date,hour, minute
or seconds as specicified by the ‘date_formate’.
SELECT ROUND(’27-Aug-25’,’DD-MM-YYYY); --1-SEP-25
TRUNC(x,date_format) Returns nearest date ‘x’lesser than or equal to nearest century,year,
month,date,hour, minute or seconds as specicified by the
‘date_formate’.
SELECT TRUNC(’27-Aug-25’,’DD-MM-YYYY); --1-Aug-25
NEXT_DAY(x, week_day) Returns the next_date of the ‘week_day’ on or after the date ‘x’ occurs
SELECT NEXT_DAY(‘27-Aug-25’, wednesday); --3-Sep-25
LAST_DAY(x) It is used to determine no.of days remaining in a month from’x’ date
SELECT LAST_DAY(’27-Aug-25’); --31-Aug-25
SYSDATE Returns the system current date and time
27-Aug-25 7:17:50
NEW_TIME(x,Zone1,Zone2) Returns date and time in Zone2 if date ‘x’ represents the time in Zone1
SELECT NEW_TIME(‘27-Aug-25’,’IST’,’EST’); --27-Aug-25
4) Conversion Functions: These are the functions that help us convert a value in one form
to an other form.
For Example: a null values into a actual value or a value from one datatype to another
datatype like NVL, TO_CHAR, TO_NUMBER, TO_NUMBER etc.
More than one function can be combined together in an expresion.This is knows as
nesting of function.
COUNT(EMPNO)
7
2
Count(*) returns the number of total rows returned by the query, including the rows that contain
nulls.
B. MAX:
1.The aggregate function Max (column) can be used only in the column list of a select statement.
MAX (SAL)
32000
C. MIN:
1. The aggregate function Min (column) can be used only in the column list of a select statement.
MIN(SAL)
20000
D. SUM:
The sum function computes the total sum fro any specified attribute, using whatever condition.
159000
E. AVG:
The avg function format is similar to that of min and max. it returns an average value o
2714.285
A subquery consists of all the clauses an ordinary SELECT clause can contain: GROUP BY,
WHERE,
HAVING, DISTINCT, TOP/LIMIT, etc. A subquery can return a single value, a single row, a
single column, or a whole table. They are called scalar subqueries.
SUBQUERIES WITH THE SELECT STATEMENT:Subqueries are most frequently used
with the SELECT statement.
Syntax:
SELECT column_name [, column_name] FROM tablel [, table2 ] WHERE column_name
OPERATOR (SELECT column_name [column_name ] FROM table1 [, table2] [WHERE]);
Consider the following employees and departments tables from the sample database:
Employee Table
Department Table
Suppose to find all employees who locate in the location with the id 1500.
SQL>SELECT Employee ID, Employee Name, FROM employees WHERE Department
SUBQUERIES WITH THE SELECT STATEMENT: We can also the subqueries along with
the INSERT statements. The data returned by the subqueries inserted into another table.
Example:The following example, we have another emp2 table created with same employees
schema
Empid Ename Salary Deptno New to copy the complete records of employees
table into emp2 table, we can use the following
query.
SQL>INSERT INTO emp2 SELECT FROM employees WHERE ID IN (SELECT ID FROM
employees);
Types of SQL.Joins
1)Inner Join
4)Self join
5)Cross Join/Cartesian Join
1) INNER JOIN (simple join): It is the most common type of SQL join, INNER JOIN selects
records that have matching values in bot tables as long as the condition is satisfied. It returns the
combination of all rows from both the tables where the condition satisfies.
this visual diagram, the SOL INNER JOIN returns the shaded area:
Ex: SELECT customers.customer_id, orders.order_id, orders.order_date
2) LEFT OUTER JOIN: The left join returns all the values from left table and the matching
values from the right table. If there in no matching join value, it will return NULL.
Syntax:The syntax for the LEFT OUTER JOIN in SQL is:
SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column table2.column;
In some databases, the OUTER keyword is omitted and written simply as LEFT JOIN.
In the below visual diagram, the SQL LEFT OUTER JOIN returns the shaded area.
Example
Now let's look at an example that shows how to use the LEFT OUTER JOIN in a SELECT
statement.
SQL>SELECT customers.customer id, orders.order id, orders.order_date FROM customers
LEFT OUTER JOIN orders ON customers.customer id=orders.customer id ORDER BY
customers.customer id;
3)RIGHT OUTER JOIN:Another type of join is called a RIGHT OUTER JOIN. This type of
join returns 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
The syntax for the RIGHT OUTER JOIN in SQL is:
SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON tablel.column =
table2.column;
In some databases, the OUTER keyword is omitted and written simply as RIGHT JOIN.
The RIGHT OUTER JOIN would return the all records from table2 and only those records from
tablel that intersect with table2.
Example:Now let's look at an example that shows how to use the RIGHT OUTER JOIN in a
SELECT statement,
SQL>SELECT customers.customer_id, orders,order_id, orders.order_date FROM customers
Example: Let's look at an example that shows how to use the FULL OUTER JOIN in a SELECT
statement.
6)SELF JOIN: As the name signifies, in SELF JOIN a table is joined to itself. That is, each row
of the table is yinel with itself and all other rows depending on some conditions. In other words
we can say that it is a join between two copies of the same table.
Syntax:
SELECT a.coulmn1, b.column2 FROM table_name a, table_name b WHERE some_condition;
table name: Name of the table.
some_condition: Condition for selecting the rows.
SQL>SELECT employee.Id, employee.Name, employee.Managerld, manager. Name as
ManagerName FROM Employees employee JOIN Employees manager ON
employee.Managerld manager.Id;
this query, the Employees table is joined with itself and has two different roles:
7)EQUI JOIN: EQUI JOIN creates a JOIN for equality or matching column(s) values of the
relative tables.An Equi Join aajoin operation in SQL that combines two tables based on a
matching column between them. Simply put, an Equi Join returns all rows from both tables
where the values in the specified columns are equal.
Syntax: SELECT FROM table1 JOIN table2 ON tablel.column_name table2.column_name;
ON student.city=record.city;
7)NON EOULJOIN: NON EQUI JOIN performs a JOIN using comparison operator other than
equal=-) sign like >,<,>=,<= with conditions,
Syntax: SELECT FROM table namel, table name2
HERE table_namel.column [> | < | >= |<=] table_name2.column;