Rdbms
Rdbms
Rdbms
DBMS VS RDBMS
Database Management System
o Database management system is a software which is used to manage the
database. For example: MySQL, Oracle, etc are a very popular commercial
database which is used in different applications.
o DBMS provides an interface to perform various operations like database creation,
storing data in it, updating data, creating a table in the database and a lot more.
o It provides protection and security to the database. In the case of multiple users,
it also maintains data consistency.
Advantages of DBMS
o Controls database redundancy: It can control data redundancy because it stores
all the data in one single database file and that recorded data is placed in the
database.
o Data sharing: In DBMS, the authorized users of an organization can share the
data among multiple users.
o Easily Maintenance: It can be easily maintainable due to the centralized nature
of the database system.
o Reduce time: It reduces development time and maintenance need.
o Backup: It provides backup and recovery subsystems which create automatic
backup of data from hardware and software failures and restores the data if
required.
o multiple user interface: It provides different types of user interfaces like
graphical user interfaces, application program interfaces
RDBMS
Multiple data elements are accessible together Individual access of data elements
Data in the form of a table are linked together No connection between data
Here, redundancy of data is reduced with the help of key Data redundancy is common
and indexes in RDBMS
It features multiple layers of security while handling data There is only low security while
handling data
The software and hardware requirements are higher The software and hardware
requirements are low
Dr Edgar F. Codd, after his extensive research on the Relational Model of database
systems, came up with twelve rules of his own, which according to him, a database
must obey in order to be regarded as a true relational database.
These rules can be applied on any database system that manages stored data using
only its relational capabilities. This is a foundation rule, which acts as a base for all the
other rules.
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for Standardization
(ISO) in 1987
o SELECT
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
Types of Datatypes
There are three main types of datatypes in the SQL server. They are listed below −
String
Numeric
Date and Time
SQL Keywords
Keyword Description
ALL Returns true if all of the subquery values meet the condition
ALTER Adds, deletes, or modifies columns in a table, or changes the data type of a
column in a table
ANY Returns true if any of the subquery values meet the condition
CHECK A constraint that limits the value that can be placed in a column
CREATE VIEW Creates a view based on the result set of a SELECT statement
FOREIGN KEY A constraint that is a key used to link two tables together
FULL OUTER JOIN Returns all rows when there is a match in either left table or right table
GROUP BY Groups the result set (used with aggregate functions: COUNT, MAX, MIN,
SUM, AVG)
INNER JOIN Returns rows that have matching values in both tables
INSERT INTO Copies data from one table into another table
SELECT
NOT NULL A constraint that enforces a column to not accept NULL values
OUTER JOIN Returns all rows when there is a match in either left table or right table
PRIMARY KEY A constraint that uniquely identifies each record in a database table
RIGHT JOIN Returns all rows from the right table, and the matching rows from the left table
SELECT INTO Copies data from one table into a new table
SELECT TOP Specifies the number of records to return in the result set
SET Specifies which columns and values that should be updated in a table
TRUNCATE TABLE Deletes the data inside a table, but not the table itself
UNION Combines the result set of two or more SELECT statements (only distinct
values)
UNION ALL Combines the result set of two or more SELECT statements (allows duplicate
values)
UNIQUE A constraint that ensures that all values in a column are unique
UPDATE Updates existing rows in a table
WHERE Filters a result set to include only records that fulfill a specified condition
Delimiters in MySQL?
Delimiters can be used when you need to define the stored procedures, function as well
as to create triggers. The default delimiter is semicolon.
You can change the delimiters to create procedures and so on. However, but if you are
considering multiple statements, then you need to use different delimiters like $$ or //.
1. CREATE TABLE table_name
2. (
3. column_Name1 data_type ( size of the column ) ,
4. column_Name2 data_type ( size of the column) ,
5. column_Name3 data_type ( size of the column) ,
6. ...
7. column_NameN data_type ( size of the column )
8. ) ;
Example :
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
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.
WHERE ID = 6;
Output
The query produces the following output −
(1 row affected)
TRUNCATE Command
TRUNCATE is another DDL command which deletes or removes all the records from the
table.
This command also removes the space allocated for storing the table records.
TRUNCATE TABLE Table_Name;
RENAME Command
RENAME is a DDL command which is used to change the name of the database table.
1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqRENAME T
ABLE Old_Table_Name TO New_Table_Name;
Example
RENAME TABLE Student TO Student_Details ;
ALTER Command
ALTER is a DDL command which changes or modifies the existing structure of the
database, and it also changes the schema of database objects.
We can also add and drop constraints of the table using the ALTER command.
ALTER TABLE name_of_table ADD column_name column_definition;
Suppose, you want to add the 'Father's_Name' column in the existing Student table. To
do this, you have to write the following DDL command:
ALTER TABLE Student ADD Father's_Name Varchar(60);
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.
Unit - 3
Operators, Functions and Joins
Operators
Arithmetic Operators
Arithmetic operators can perform arithmetical operations on numeric operands
involved. Arithmetic operators are addition(+), subtraction(-), multiplication(*) and
division(/). The + and - operators can also be used in date arithmetic.
Syntax:
SELECT <Expression>[arithmetic operator]<expression>...
FROM [table_name]
WHERE [expression];
Parameter Description
Expression Expression made up of a single constant, variable, scalar function, or column name and
can also be the pieces of a SQL query that compare values against other values or perform
arithmetic calculations.
Logical Operators
The Logical operators are those that are true or false. They return a true or false
values to combine one or more true or false values.
Operator Description
AND Logical AND compares between two Booleans as expression and returns true when both expressions
are true...
OR Logical OR compares between two Booleans as expression and returns true when one of the
expression is true...
NOT Not takes a single Boolean as an argument and changes its value from false to true or from true to
false....
Special operators
BETWEEN The SQL BETWEEN operator tests an expression against a range. The range Numeric, characters,
consists of a beginning, followed by an AND keyword and an end or datetime values
expression....
ANY ANY compares a value to each value in a list or results from a query and A value to a list or a
evaluates to true if the result of an inner query contains at least one row.... single - columns set of
values
ALL ALL is used to select all records of a SELECT STATEMENT. It compares a value A value to a list or a
to every value in a list or results from a query. The ALL must be preceded by single - columns set of
the comparison operators and evaluates to TRUE if the query returns no values
rows....
SOME SOME compare a value to each value in a list or results from a query and A value to a list or a
evaluate to true if the result of an inner query contains at least one row... single - columns set of
values
EXISTS The EXISTS checks the existence of a result of a subquery. The EXISTS Table
subquery tests whether a subquery fetches at least one row. When no data
is returned then this operator returns 'FALSE'...
Syntax:
SELECT [column_name | * | expression] [logical operator]
[column_name | * | expression .....]
FROM <table_name>
WHERE <expressions> [ logical operator |
arithmetic operator | ...] <expressions>;
Parameters:
Name Description
expression Expression made up of a single constant, variable, scalar function, or column name and
can also be the pieces of a SQL query that compare values against other values or
perform arithmetic calculations.
Checks if the values of two operands are equal or not, if yes (A = B) is not
=
then condition becomes true. true.
!=
Checks if the values of two operands are equal or not, if values (A != B) is
<>
are not equal then condition becomes true. true.
~=
Checks if the value of left operand is greater than the value of (A > B) is not
>
right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right (A < B) is
<
operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes true. not true.
Checks if the value of left operand is less than or equal to the (A <= B) is
<=
value of right operand, if yes then condition becomes true. true
here expression can be constant, variable, return value of function, column value or any
combination of constant, variable, function or column value.
The LIKE clause uses the following symbols known as wildcard operators in SQL to
perform this pattern-matching task in SQL.
SELECT ColumnName1, ColumnName2 FROM TableName WHERE ColumnName LIKE [
Expression];
Here, Expression refers to the pattern which we want to search for in the values of a
table. This expression will include the wildcard operators such as '%' and '_'.
IN Predicate
Here's an example:
NOT IN predicate
The NOT IN predicate seems to be just the inverse of the useful IN predicate, but in SQL,
this isn't entirely true
The SQL Server NOT IN operator is used to replace a group of arguments using the <> (or !=)
operator that are combined with an AND. It can make code easier to read and understand for
SELECT, UPDATE or DELETE SQL commands. Generally, it will not change performance
characteristics.
SELECT *
FROM Sales.Invoices
WHERE LastEditedBy NOT IN (11,17,13);
The SQL ANY and ALL Operators
The ANY and ALL operators allow you to perform a comparison between a single
column value and a range of other values.
ANY means that the condition will be true if the operation is true for any of the
values in the range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
ALL means that the condition will be true only if the operation is true for all
values in the range.
ALL Syntax With SELECT
SELECT ALL column_name(s)
FROM table_name
WHERE condition;
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
SET Operators in SQL
SET operators are special type of operators which are used to combine the result of two
queries.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
UNION
When multiple SELECT queries are joined using UNION operator, Oracle displays the
combined result from all the compounded SELECT queries, after removing all
duplicates and in sorted order (ascending by default), without ignoring the NULL values.
Consider the below five queries joined using UNION operator. The final combined result
set contains value from all the SQLs. Note the duplication removal and sorting of data.
NUM
-------
1
3
5
6
UNION ALL
UNION and UNION ALL are similar in their functioning with a slight difference. But
UNION ALL gives the result set without removing duplication and sorting the data. For
example,in above query UNION is replaced by UNION ALL to see the effect.
Consider the query demonstrated in UNION section. Note the difference in the output
which is generated without sorting and deduplication.
SELECT 1 NUM FROM DUAL
UNION ALL
SELECT 5 FROM DUAL
UNION ALL
SELECT 3 FROM DUAL
UNION ALL
SELECT 6 FROM DUAL
UNION ALL
SELECT 3 FROM DUAL;
NUM
-------
1
5
3
6
3
INTERSECT
Using INTERSECT operator, Oracle displays the common rows from both the SELECT
statements, with no duplicates and data arranged in sorted order (ascending by default).
For example,the below SELECT query retrieves the salary which are common in
department 10 and 20.As per ISO SQL Standards, INTERSECT is above others in
precedence of evaluation of set operators but this is not still incorporated by Oracle.
SELECT SALARY
FROM employees
WHERE DEPARTMENT_ID = 10
INTRESECT
SELECT SALARY
FROM employees
WHERE DEPARTMENT_ID = 20
SALARY
---------
1500
1200
2000
MINUS
Minus operator displays the rows which are present in the first query but absent in the
second query, with no duplicates and data arranged in ascending order by default.
SELECT JOB_ID
FROM employees
WHERE DEPARTMENT_ID = 10
MINUS
SELECT JOB_ID
FROM employees
WHERE DEPARTMENT_ID = 20;
JOB_ID
-------------
HR
FIN
ADMIN
SQL JOIN
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 as
follows:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
NATURAL JOIN
StudentCourse
C. 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
the join. For the rows for which there is no matching row on the 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;
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
HARSH 1
NAME COURSE_ID
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
Natural join can join tables based on the common columns in the tables being
joined. A natural join returns all rows by matching values in common columns
having same name and data type of columns and that column should be
present in both tables.
Both table must have at list one common column with same column name and
same data type.
The two table are joined using Cross join.
DBMS will look for a common column with same name and data type Tuples
having exactly same values in common columns are kept in result.
Example:
Employee
Emp_i
d Emp_name Dept_id
1 Ram 10
2 Jon 30
3 Bob 50
Department
Dept_id Dept_name
10 IT
30 HR
40 TIS
1 Ram 10 10 IT
2 Jon 30 30 HR
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
Count()
Sum()
Avg()
Min()
Max()
COUNT() Function
Syntax:
COUNT(*)
or
SUM() Function
Syntax:
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example:
The following SQL statement finds the sum of the "unit price" fields in the "products"
table:
AVG() Function
Syntax:
AVG()
or
Example:
MIN() Function
The MIN() aggregate function returns the lowest value (minimum) in a set of non-NULL
values.
Syntax:
MIN()
or
Example:
MAX() Function
The MAX() aggregate function returns the highest value (maximum) in a set of non-
NULL values.
Syntax:
AVG()
or
Example:
The code depicted below will give us the maximum quantity in stock in the products
table.
Numeric Functions
CEIL(): It returns the smallest integer value that is greater than or equal to a
number.
Syntax: SELECT CEIL(25.75);
Output: 26
String functions are used to perform an operation on input string and return an
output string.
Following are the string functions defined in SQL:
1. ASCII(): This function is used to find the ASCII value of a character.
Syntax: SELECT ascii('a');
Output: 97
2. CHAR_LENGTH(): Doesn’t work for SQL Server. Use LEN() for SQL Server.
This function is used to find the length of a word.
Syntax: SELECT char_length('Hello!');
Output: 6
10. LCASE(): This function is used to convert the given string into lower
case.
Syntax: LCASE ("GeeksFor Geeks To Learn");
Output: geeksforgeeks to learn
11. LEFT(): This function is used to SELECT a sub string from the left of
given size or characters.
Conversion Function
TO_CHAR
This function is used to explicitly convert a number or date data type to char.
The syntax of this function is given as follows −
TO_CHAR(number,format,parameters)
This function changes number to char with the specific format as provided according to
the syntax. The parameters can be used to specify decimal characters, group
separators etc.
For example −
SELECT CHAR(sysdate, “Month DD,YYYY”) FROM DUAL;
TO_NUMBER
This function is used to explicitly convert a string to number. If the string to be
converted does not contain numeric characters then TO_NUMBER shows an error.
The syntax of this function is given as follows −
TO_NUMBER(number,format,parameters)
This function changes the given string to number with the specific format as provided
according to the syntax.
The parameters and format are optional so to convert a string to a number
For example,
TO_NUMBER (‘353.78’);
TO_DATE
This function takes character values and returns the output in the date format.
The syntax of this function is given as follows −
TO_DATE(number, format, parameters)
This function changes the given string to number with the specific format as provided
according to the syntax.
SELECT TO_DATE(‘2018/07/31’,’yyyy/mm/dd’) FROM DUAL;
This takes the values in character format and returns them in date format as specified.
CRUD operations refer to the basic operations that can be performed on data stored in
a database. CRUD stands for Create, Read, Update, and Delete. These operations are
essential for managing data in any database management system.
Create (C): Create operation is used to insert new data into the database. In SQL, this
is done using the INSERT statement. The INSERT statement adds a new row to a
table.
Read (R): Read operation is used to retrieve data from the database. In SQL, this is
done using the SELECT statement. The SELECT statement retrieves data from one or
more tables and returns the result set.
Update (U): Update operation is used to modify existing data in the database. In SQL,
this is done using the UPDATE statement. The UPDATE statement modifies one or
more columns in one or more rows of a table.
Delete (D): Delete operation is used to remove data from the database. In SQL, this is
done using the DELETE statement. The DELETE statement removes one or more rows
from a table.
SELECT:
SELECT column_name(s) FROM table_name WHERE condition;
INSERT:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES
(value1, value2, value3, ...);
UPDATE:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
DELETE:
DELETE FROM table_name WHERE condition;
CREATE SEQUENCE my_sequence
START WITH 1
INCREMENT BY 1
MAXVALUE 100
NOCYCLE;
This will create a sequence called my_sequence that starts at 1 and increments by 1,
generating numbers up to a maximum value of 100. The NOCYCLE option is used to
prevent the sequence from starting over at the beginning when it reaches the maximum
value.
CREATE SEQUENCE sequence_name
[START WITH start_value]
[INCREMENT BY increment_value]
[MAXVALUE max_value | NOMAXVALUE]
[MINVALUE min_value | NOMINVALUE]
[CYCLE | NOCYCLE]
[CACHE cache_size | NOCACHE];
sequence_name: The name of the sequence you want to create.
start_value: The value at which the sequence should start. If not specified, the default is
1.
increment_value: The amount by which the sequence should be incremented. If not
specified, the default is 1.
max_value: The maximum value that the sequence can generate. If not specified, the
default is the maximum value for the data type of the sequence.
min_value: The minimum value that the sequence can generate. If not specified, the
default is the minimum value for the data type of the sequence.
CYCLE: Specifies whether the sequence should restart at the minimum value when it
reaches the maximum value. If specified, the sequence will cycle. If not specified, the
default is NOCYCLE.
CACHE: Specifies the number of sequence numbers to cache for performance. If not
specified, the default is 20.