0% found this document useful (0 votes)
4 views

DBMS_Unit_5_Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DBMS_Unit_5_Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

SQL DATABASE :

MySQL

• MySQL is open source SQL database, which is developed by Swedish company MySQL
AB.
• MySQL is pronounced "my ess-que-ell," in contrast with SQL, pronounced "sequel."
• MySQL is supporting many different platforms including Microsoft Windows, the major
Linux distributions, UNIX, and Mac OS X.

MySQL has free and paid versions, depending on its usage (non-commercial/commercial) and
features. MySQL comes with a very fast, multi-threaded, multi-user, and robust SQL database
server.

Features:
• High Performance.
• High Availability.
• Scalability and Flexibility Run anything.
• Robust Transactional Support.
• Web and Data Warehouse Strengths.
• Strong Data Protection.
• Comprehensive Application Development.
• Management Ease.
• Open Source Freedom and 24 x 7 Support.
• Lowest Total Cost of Ownership.

MS SQL Server
MS SQL Server is a Relational Database Management System developed by Microsoft Inc. Its
primary query languages are:
• T-SQL.
• ANSI SQL.
Features:
• High Performance.
• High Availability.
• Database mirroring.
• Database snapshots.
• CLR integration.
• Service Broker.
• DDL triggers.
• Ranking functions.
• Row version-based isolation levels.
• XML integration.
• TRY...CATCH.
• Database Mail.

ORACLE
It is very large and multi-user database management system. Oracle is a relational
database management system developed by 'Oracle Corporation'.
Oracle works to efficiently manage its resource, a database of information, among the
multiple clients requesting and sending data in the network.
It is an excellent database server choice for client/server computing. Oracle supports all
major operating systems for both clients and servers, including MSDOS, NetWare, UnixWare,
OS/2 and most UNIX flavors.

Features:
• Concurrency • Read Consistency • Locking Mechanisms • Quiesce Database •
Portability • Self managing database • SQL*Plus • ASM • Scheduler • Resource Manager
• Data Warehousing • Materialized views • Bitmap indexes • Table compression • Parallel
Execution • Analytic SQL • Data mining • Partitioning

MS- ACCESS
This is one of the most popular Microsoft products. Microsoft Access is entry-level
database management software. MS Access database is not only an inexpensive but also
powerful database for small-scale projects. MS Access uses the Jet database engine which
utilizes a specific SQL language dialect
Features:
• Users can create tables, queries, forms and reports, and connect them together with
macros.

• The import and export of data to many formats including Excel, Outlook, ASCII,
dBase, Paradox, FoxPro, SQL Server, Oracle, ODBC, etc.

• There is also the Jet Database format (MDB or ACCDB in Access 2007) which can
contain the application and data in one file. This makes it very convenient to distribute
the entire application to another user, who can run it in disconnected environments.

• Microsoft Access offers parameterized queries. These queries and Access tables can be
referenced from other programs like VB6 and .NET through DAO or ADO.

• The desktop editions of Microsoft SQL Server can be used with Access as an alternative
to the Jet Database Engine.

• Microsoft Access is a file server-based database. Unlike client-server relational database


management systems (RDBMS), Microsoft Access does not implement database triggers,
stored procedures, or transaction logging.

• SQL data type is an attribute that specifies type of data of any object. Each column,
variable and expression has related data type in SQL.

• You would use these data types while creating your tables. You would choose a
particular data type for a table column based on your requirement.
• SQL Server offers six categories of data types for your use:
Operator in SQL
An operator is a reserved word or a character used primarily in an SQL statement's
WHERE clause to perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement.

• Arithmetic operators
• Comparison operators
• Logical operators
• Operators used to negate conditions
SQL Commands

• SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
• SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
• SQLcan perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

Types of SQL Commands


• There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

SQL commands

Data Definition Language (DDL)


• DDL changes the structure of the table like creating a table, deleting a table, altering a table,
etc.
• DDL changes the structure of the table like creating a table, deleting a table, altering a table,
etc.
• All the command of DDL are auto-committed that means it permanently save all the changes in
the database.

• Here are some commands that come under DDL:


 CREATE
 ALTER
 DROP
 ALTER
 DROP
 TRUNCATE

Data Definition Language (DDL)- CREATE

CREATE It is used to create a new table in the database.

Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATA TYPES[,....]);

Example: CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100),


DOB DATE);

Data Definition Language (DDL)- Drop

Drop: It is used to delete both the structure and record stored in the table.

Syntax: DROP TABLE ;


Example: DROP TABLE EMPLOYEE;

Data Definition Language (DDL)- ALTER

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:
ALTER TABLE table_name ADD column_name COLUMN-definition;
ALTER TABLE MODIFY(COLUMN DEFINITION....);

Example:
ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

Data Definition Language (DDL)- TRUNCATE


TRUNCATE: It is used to delete all the rows from the table and free the space containing the
table.

Syntax: Syntax:
TRUNCATE TABLE table_name;

Example:
TRUNCATE TABLE EMPLOYEE;

Data Manipulation Language

• DML commands are used to modify the database. It is responsible for all form of CHANGES
in the database.
• DML commands are used to modify the database. It is responsible for all form of CHANGES
in the database.
• 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.

Here are some commands that come under DML:


 INSERT
 UPDATE
 DELETE

Data Manipulation Language- INSERT

INSERT: The INSERT statement is a SQL query.


It is used to insert data into the row of a table.

Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, ....
valueN);
OR
INSERT INTO TABLE_NAME VALUES(value1, value2, value3, .... valueN);

Example: INSERT INTO XYZ (Author, Subject) VALUES ("Sonoo", "DBMS");

Data Manipulation Language- UPDATE

Update: This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN=valueN] [WHERE


CONDITION]

Example:
UPDATE students UPDATE students SET User_Name = 'Sonoo' WHERE Student_Id = '3';
Data Control Language

DCL commands are used to GRANT and TAKE BACK authority from any database user.

Here are some commands that come under DCL:


Grant
Revoke

Data Control Language- Grant


GRANT:
It is used to give user access privileges to a database.

Example:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER

REVOKE:
It is used to take back permissions from the user.

Example: REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

Transaction Control Language


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:

COMMIT
 ROLLBACK
 SAVEPOINT

Transaction Control Language- COMMIT

Commit: Commit command is used to save all the transactions to the database.
Syntax: COMMIT;

Example: DELETE FROM CUSTOMERS WHERE AGE=25;


COMMIT;

Transaction Control Language- Rollback and Savepoint

SAVE POINT: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.

Syntax: SAVEPOINT SAVEPOINT_NA ME;

Example: SAVEPOINT S1;

Rollback:
Rollback command is used to undo transactions that have not already been saved to the database.
Syntax:
ROLLBACK;
Example:
DELETE FROM CUSTOMERS WHERE AGE=25;
ROLLBACK;

Data Query Language


DQL is used to fetch the data from the database. It uses only one command:

SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to select
the attribute based on the condition described by WHERE clause.

Syntax:
SELECT expressions FROM TABLES WHERE conditions;

Example:
SELECT emp_name FROM employee WHERE age>20;

Views in SQL

• Views in SQL are considered as a virtual table. A view also contains rows and columns.
• Views in SQL are considered as a virtual table. A view also contains rows and columns.
• To create the view, we can select the fields from one or more tables present in the
database.
• To create the view, we can select the fields from one or more tables present in the
database.
• A view can either have specific rows based on certain condition or all the rows of a
table.

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

CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name


WHERE condition;

Creating View from a single table

CREATE VIEW Details_View AS SELECT NAME, ADDRESS FROM Student_Details


WHERE STU_ID<4;

Creating View from multiple tables


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.

CREATE VIEW MarksView AS


SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;

SELECT * FROM MarksView;

DROP VIEW view_name;

SQL Index
• Indexes are special lookup tables. It is used to retrieve data from the database very fast.
• An Index is used to speed up select queries and where clauses. But it shows down the data input
with insert and update statements. Indexes can be created or dropped without affecting the data.
• An index in a database is just like an index in the back of a book.

Create Index statement


CREATE INDEX index_name
ON table_name (column1, column2, ...);

Unique Index statement

Syntax
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);
Example
CREATE UNIQUE INDEX websites_idx ON websites (site_name);

Drop Index Statement

Syntax
DROP INDEX index_name;

Example
DROP INDEX websites_idx;

SQL Sub Query

A Sub query is a query within another SQL query and embedded within the WHERE clause.

Important Rule:
• A sub query can be placed in a number of SQL clauses like WHERE clause, FROM
clause, HAVING clause.
• You can use Sub query with SELECT, UPDATE, INSERT, DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• A sub query is a query within another query. The outer query is known as the main query,
and the inner query is known as a sub query.
• Sub queries are on the right side of the comparison operator.
• A sub query is enclosed in parentheses.
• In the Sub query, ORDER BY command cannot be used. But GROUP BY command can
be used to perform the same function as ORDER BY command.

Sub queries with the Select Statement

SQL sub queries are most frequently used with the Select statement.

Syntax:
SELECT column_name FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE... );

Example:
SELECT * FROM EMPLOYEE WHERE ID IN(SELECT ID FROM EMPLOYEE
WHERE SALARY > 4500);
Sub queries with the INSERT Statement

SQL sub query can also be used with the Insert statement. In the insert statement, data returned
from the sub query is used to insert into another table.

In the sub query, the selected data can be modified with any of the character, date functions.
Syntax:
INSERT INTO table_name (column1, column2, column3....)
SELECT * FROM table_name WHERE VALUE OPERATOR

Example:
INSERT INTO EMPLOYEE_BKP SELECT * FROM EMPLOYEE
WHERE ID IN(SELECT ID FROM EMPLOYEE);

Sub queries with the UPDATE Statement

The sub query of SQL can be used in conjunction with the Update statement. When a sub query
is used with the Update statement, then either single or multiple columns in a table can be
updated.

Syntax:
UPDATE table SET column_name = new_value WHERE VALUE OPERATOR (SELECT
COLUMN_NAME FROM TABLE_NAME WHERE condition);

Example:
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE
table. The given example updates the SALARY by .25 times in the EMPLOYEE table for all
employee whose AGE is greater than or equal to 29.

UPDATE EMPLOYEE SET SALARY = SALARY *0.25


WHERE AGE IN(SELECT AGE FROM CUSTOMERS_BKP WHERE AGE>=29);

Sub queries with the DELETE Statement

The sub query of SQL can be used in conjunction with the Delete statement just like any other
statements mentioned above.

Syntax:
DELETE FROM TABLE_NAME WHERE VALUE OPERATOR (SELECT
COLUMN_NAME FROM TABLE_NAME WHERE condition);

Example:
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE
table. The given example deletes the records from the EMPLOYEE table for all EMPLOYEE
whose AGE is greater than or equal to 29.

DELETE FROM EMPLOYEE WHERE AGE IN(SELECT AGE FROM


EMPLOYEE_BKP WHERE AGE>=29);

SQL Clauses

GROUP BY
• SQL GROUP BY statement is used to arrange identical data into groups.
• The GROUP BY statement is used with the SQL SELECT statement.
• The GROUP BY statement follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
• The GROUP BY statement is used with aggregation function.

Syntax
SELECT column FROM table_name
WHERE conditions
GROUP BY column
ORDER BY column

Example
SELECT COMPANY, COUNT (*) FROM PRODUCT_MAST GROUP BY COMPANY;

HAVING
• HAVING clause is used to specify a search condition for a group or an aggregate.
• Having is used in a GROUP BY clause. If you are not using GROUP BY clause then you
can use HAVING function like a WHERE clause

Syntax
SELECT column1, column2 FROM table_name WHERE conditions GROUP BY
column1,column2 HAVING conditions ORDER BY column1, column2;

Example
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY
HAVING COUNT(*)>2;

ORDER BY

• The ORDER BY clause sorts the result-set in ascending or descending order.


• It sorts the records in ascending order by default. DESC keyword is used to sort the
records in descending order.
Syntax
SELECT column1, column2 FROM table_name WHERE condition ORDER
BYcolumn1, column2... ASC | DESC;

Example
SELECT * FROM CUSTOMER ORDER BY NAME;
OR
SELECT * FROM CUSTOMER ORDER BY NAME DESC;
SQL Aggregate Functions

AGGREGATION AND GROUPING


GROUP BY groups together rows that have the same values in specified columns. It computes
summaries (aggregates) for each unique combination of values.

AGGREGATE FUNCTIONS
1. avg(expr) − average value for rows within the group
2. count(expr) − count of values for rows within the group
3. max(expr) − maximum value within the group
4. min(expr) − minimum value within the group
5. sum(expr) − sum of values within the group

EXAMPLE QUERIES
Count
Find out the number of cities:
SELECT COUNT(*) FROM city;

Find out the number of cities with non-null ratings:


SELECT COUNT(rating) FROM city;

Find out the number of distinctive country values:


SELECT COUNT(DISTINCT country_id) FROM city;

Max and Min


Find out the smallest and the greatest country populations:
SELECT MIN(population), MAX(population) FROM country;

SUM
Find out the total population of cities in respective countries:
SELECT country_id, SUM(population) FROM city GROUP BY country_id;

Average
Find out the average rating for cities in respective countries if the average is above 3.0:
SELECT country_id, AVG(rating) FROM city GROUP BY country_id HAVING
AVG(rating) > 3.0;

SQL JOINs

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.

Types of SQL JOIN

 INNERJOIN

 LEFTJOIN

 RIGHTJOIN

 FULL JOIN
(MINUS or EXCEPT)

You might also like