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

DBMS-Unit IV

The document provides an overview of Structured Query Language (SQL), detailing its purpose for managing relational databases and the types of commands it includes: DDL, DML, DCL, and TCL. It describes various SQL data types, including binary, numeric, character strings, and date/time types, as well as commands for creating, altering, and deleting database structures. Additionally, it covers data manipulation commands and set operations, such as UNION and INTERSECT, along with examples for clarity.

Uploaded by

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

DBMS-Unit IV

The document provides an overview of Structured Query Language (SQL), detailing its purpose for managing relational databases and the types of commands it includes: DDL, DML, DCL, and TCL. It describes various SQL data types, including binary, numeric, character strings, and date/time types, as well as commands for creating, altering, and deleting database structures. Additionally, it covers data manipulation commands and set operations, such as UNION and INTERSECT, along with examples for clarity.

Uploaded by

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

Structured Query Language(SQL):

SQL is a database language designed for the retrieval and management of data in a relational
database. SQL is the standard language for database management. All the RDBMS systems
like MySQL, MS Access, Oracle, Sybase, Postgres, and SQL Server use SQL as their standard
database language.
These SQL commands are divided into four types
1. DDL – Data Definition Language
2. DML – Data Manipulation Language
3. DCL – Data Control Language
4. TCL – Transaction control language

SQL Datatype

o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.

1. Binary Datatypes

There are Three types of binary Datatypes which are given below:
Data Type Description

Binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.

Varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.

Image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.

2. Approximate Numeric Datatype :

Data type From To Description

Float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.

Real -3.40e + 38 3.40E + 38 It specifies a single precision floating point number

3. Exact Numeric Datatype


Data type Description

Int It is used to specify an integer value.

Smallint It is used to specify small integer value.

Bit It has the number of bits to store.

Decimal It specifies a numeric value that can have a decimal number.

Numeric It is used to specify a numeric value.

4. Character String Datatype

Data Description
type

Char It has a maximum length of 8000 characters. It contains Fixed-length non-unicode characters.

varchar It has a maximum length of 8000 characters. It contains variable-length non-unicode


characters.

Text It has a maximum length of 2,147,483,647 characters. It contains variable-length non-unicode


characters.

5. Date and time


date It is used to store the year, month, and days value.

time It is used to store the hour, minute, and second values.

timestamp It stores the year, month, day, hour, minute, and the second value.

1. Data Definition Language (DDL)


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.

Some DDL commands:


CREATE
ALTER
DROP
TRUNCATE

There are two CREATE statements available in SQL:


1. CREATE DATABASE
2. CREATE TABLE

The CREATE DATABASE statement is used to create a new database in SQL.

Syntax: CREATE DATABASE database_name;

database_name: name of the database.

Example CREATE DATABASE NPCDATA; -- NPCDATA is the database name

Data Description
type

Data Description
type
Create table : The CREATE TABLE statement is used to create a table in SQL. We know
that a table comprises of rows and columns. So while creating tables we have to provide all
the information to SQL about the names of the columns, type of data to be stored in columns,
size of the data etc.
Syntax:
CREATE TABLE table_name
(
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);

Example:
CREATE TABLE Students
(
ROLL_NO int(3),
NAME varchar(20),
SUBJECT varchar(20),
);
SQL | ALTER (ADD, DROP, MODIFY) :

ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is
also used to add and drop various constraints on the existing table.
ALTER TABLE – ADD
ADD is used to add columns into the existing table.

Syntax: ALTER TABLE table_name


ADD (Columnname_1 datatype,
Columnname_2 datatype,

Columnname_n datatype);

Example : alter table students add remarks varchar(20);

ALTER TABLE – DROP

DROP COLUMN is used to drop column in a table. Deleting the unwanted columns from
the table.
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;

Example: alter table students drop column subject;

ALTER TABLE-MODIFY

It is used to modify the existing columns in a table. Multiple columns can also be
modified at once.

Syntax :

ALTER TABLE table_name


MODIFY column_name column_type;

Example:

Alter table students modify remarks char(25);

SQL | DROP, TRUNCATE

DROP
DROP is used to delete a whole database or just a table.The DROP statement destroys the
objects like an existing database, table, index, or view.
Syntax:

DROP TABLE table_name;


table_name: Name of the table to be deleted.

Example : drop table students; -- students table name

DROP DATABASE database_name;


database_name: Name of the database to be deleted.
Example: drop database NCPDATA; -- NCPDATA database name

TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.
Syntax: TRUNCATE TABLE table_name;
Example: TRUNCATE TABLE EMPLOYEE;

SQL | Comments
Comments can be written in the following three formats:
1. Single line comments.
2. Multi line comments
3. In line comments
Single line comments: Comments starting and ending in a single line are considered
as single line comments.
Line starting with ‘–‘ is a comment and will not be executed.
Syntax:
-- single line comment
-- another comment
SELECT * FROM Customers;
Multi line comments: Comments starting in one line and ending in different line are
considered as multi line comments. Line starting with ‘/*’ is considered as starting
point of comment and are terminated when ‘*/’ is encountered.
Syntax:
/* multi line comment
another comment */
SELECT * FROM Customers;
• In line comments: In line comments are an extension of multi line comments,
comments can be stated in between the statements and are enclosed in between ‘/*’
and ‘*/’.
Syntax:
SELECT * FROM /* Customers; */

SQL | ALTER (RENAME)


This is used to rename table existing in the database.
Syntax:
ALTER TABLE table_name
RENAME TO new_table_name;
Example:
Alter table students rename to alcstudents;

2. Data Manipulation Language


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.
1. SELECT
2. INSERT
3. UPDATE
4. DELETE

SQL | SELECT: -

It is used to retrieve data from the database.


Syntax: -

SELECT column1, column2 FROM table_name

Example: -

SELECT ROLL_NO, NAME, AGE FROM Student;

SQL | INSERT INTO Statement

The INSERT INTO statement of SQL is used to insert a new row in a table. There are two
ways of using INSERT INTO statement for inserting rows:

1.Only values: First method is to specify only the value of data to be inserted without
the column names.

Syntax

INSERT INTO table_name VALUES (value1, value2, value3,…);

Example: -

INSERT INTO Student VALUES (‘5′,’HARSH’,’WEST BENGAL’,’XXXXXXXXXX’,’19’);


2.Column names and values both: In the second method we will specify both the columns
which we want to fill and their corresponding values as shown below:

Syntax

INSERT INTO table_name (column1, column2, column3,..) VALUES (value1, value2,


value3,….);

Example: -

INSERT INTO Student (ROLL_NO, NAME, Age) VALUES (‘5′,’PRATIK’,’19’);

SQL | UPDATE Statement

The UPDATE statement in SQL is used to update the data of an existing table in database.
We can update single columns as well as multiple columns using UPDATE statement as
per our requirement.

Syntax

UPDATE table_name SET column1 = value1, column2 = value2,...


WHERE condition;

Example: -

UPDATE Student SET NAME = 'PRATIK' WHERE Age = 20;

SQL | DELETE Statement

The DELETE Statement in SQL is used to delete existing records from a table. We can
delete a single record or multiple records depending on the condition we specify in the
WHERE clause.

Syntax: -
DELETE FROM table_name WHERE some_condition;
Example: -
DELETE FROM Student WHERE NAME = 'Ram';

Selection Operation
SELECT is used to retrieve rows selected from one or more tables.

1. SELECT field_name1, field_name 2,... field_nameN


2. FROM table_name1, table_name2...
3. [WHERE condition]
4. [GROUP BY field_name(s)]
5. [HAVING condition]
6. [ORDER BY field_name(s)]
7. [OFFSET M ][LIMIT N];

The SELECT statement uses the following parameters:

Parameter Descriptions
Name

field_name(s) or It is used to specify one or more columns to returns in the result set. The
* asterisk (*) returns all fields of a table.

table_name(s) It is the name of tables from which we want to fetch data.

WHERE It is an optional clause. It specifies the condition that returned the


matched records in the result set.

GROUP BY It is optional. It collects data from multiple records and grouped them
by one or more columns.

HAVING It is optional. It works with the GROUP BY clause and returns only
those rows whose condition is TRUE.

ORDER BY It is optional. It is used for sorting the records in the result set.

Example:-

SELECT Name, City, SUM (working_hours) AS "Total working hours"


FROM employee_detail
GROUP BY Name
HAVING SUM (working_hours) > 5;

Table: customer

Table: orders

SELECT cust_name, city, order_num, order_date


FROM customer INNER JOIN orders
ON customer.cust_id = orders.order_id
WHERE order_date < '2020-04-30'
ORDER BY cust_name;
MySQL Aggregate/Group Functions

There are various aggregate functions that can be used with SELECT statement.

A list of commonly used aggregate functions are given below.

Aggregate Descriptions
Function

count() It returns the number of rows, including rows with NULL values in a
group.

sum() It returns the total summed values (Non-NULL) in a set.

average() It returns the average value of an expression.

min() It returns the minimum (lowest) value in a set.

max() It returns the maximum (highest) value in a set.

groutp_concat() It returns a concatenated string.

first() It returns the first value of an expression.

last() It returns the last value of an expression.

MySQL Count () Function

MySQL count() function is used to returns the count of an expression. It is used when you
need to count some records of your table

Syntax :

SELECT COUNT (aggregate_expression)

FROM table_name

[WHERE conditions];

Example:
SELECT COUNT(*) FROM employees WHERE emp_age>32;

MySQL sum() function

The MySQL sum() function is used to return the total summed value of an expression.

Syntax :

SELECT SUM(aggregate_expression)

FROM tables

[WHERE conditions];

Example:
SELECT SUM(working_hours) AS "Total working hours" FROM employees;

AVG() Function

MySQL AVG() function calculates the average of the values specified in the column.

Syntax :

SELECT AVG(working_hours) AS "Average working hours"

FROM employee;

MAX() Function

MySQL MAX() function returns the maximum (highest) value of the specified column.

Syntax :

SELECT MAX(working_hours) AS Maximum_working_hours

FROM employee;

MIN() Function

MySQL MIN() function returns the minimum (lowest) value of the specified column.

Syntax :
SELECT MIN(working_hours) AS Minimum_working_hours

FROM employee;

FIRST() Function

This function returns the first value of the specified column

Syntax :

SELECT working_date FROM employee LIMIT 1;

LAST() Function

This function returns the last value of the specified column.

SELECT working_hours

FROM employee

ORDER BY name DESC LIMIT 1;

Table Modification Commands

SQL | ALTER (ADD, DROP, MODIFY) :

ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is
also used to add and drop various constraints on the existing table.
ALTER TABLE – ADD
ADD is used to add columns into the existing table.
Syntax: ALTER TABLE table_name
ADD (Columnname_1 datatype,
Columnname_2 datatype,

Columnname_n datatype);

Example : alter table students add remarks varchar(20);

ALTER TABLE – DROP

DROP COLUMN is used to drop column in a table. Deleting the unwanted columns from
the table.
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;

Example: alter table students drop column subject;

ALTER TABLE-MODIFY

It is used to modify the existing columns in a table. Multiple columns can also be
modified at once.

Syntax :

ALTER TABLE table_name


MODIFY column_name column_type;

Example:

Alter table students modify remarks char(25);

SQL Set Operation

The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in both
the tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

Syntax

1. SELECT column_name FROM table1


2. UNION
3. SELECT column_name FROM table2;

Example:

The First tableM89

Difference between JDK, JRE, and JVM

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table


ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:

1. SELECT * FROM First


2. UNION
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David

2. Union All

Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:

1. SELECT column_name FROM table1


2. UNION ALL
3. SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

1. SELECT * FROM First


2. UNION ALL
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David

3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax

1. SELECT column_name FROM table1


2. INTERSECT
3. SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

1. SELECT * FROM First


2. INTERSECT
3. SELECT * FROM Second;
The resultset table will look like:

ID NAME

3 Jackson

4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.

Syntax:

1. SELECT column_name FROM table1


2. MINUS
3. SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

1. SELECT * FROM First


2. MINUS
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

Projection operation

The projection operation performs column wise filtering, specific columns are selected
projection operation.
Syntax:
Select columnName1,columnName2, …….. columnName N from table_name;
If all the columns of the table are selected then it cannot be consider as projection.

Example : Select city,state,zipcode from customer;

JOINS

MySQL JOINS are used with SELECT statement. It is used to retrieve data from multiple
tables. It is performed whenever you need to fetch records from two or more tables.

There are three types of MySQL

joins:
o Cartesian join
o INNER JOIN (or sometimes called simple join)
o LEFT OUTER JOIN (or sometimes called LEFT JOIN)
o RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
o SELF join

Cartesian join (cross join)

The CROSS JOIN is used to combine each row of the first table with each row of the second
table. It is also known as the Cartesian join since it returns the Cartesian product of the sets
of rows from the joined tables.

Syntax:

SELECT TableName1.columnName1, TableName2.columnName2 FROM TableNameCR


OSS JOIN TableName2 ON TableName1.ColumnName = TableName2.ColumnName;

Consider we have the following tables with the given data:

Table 1 & 2: MatchScore & Departments

Player Department_id Goals

Franklin 1 2

Alan 1 3

Priyanka 2 2
Rajesh 3 5

Exception Handling in Java - Javatpoint

Department_id Department_name

1 IT

2 HR

3 Marketing
Example :
SELECT * FROM MatchScore CROSS JOIN Departments;
Player Departme Goals Depatment_i Department
nt_id d _name

Franklin 1 2 1 IT

Alan 1 3 1 IT

Priyanka 2 2 1 IT

Rajesh 3 5 1 IT

Franklin 1 2 2 HR

Alan 1 3 2 HR

Priyanka 2 2 2 HR

Rajesh 3 5 2 HR

Franklin 1 2 3 Marketing

Alan 1 3 3 Marketing

Priyanka 2 2 3 Marketing

Rajesh 3 5 3 Marketing

Inner JOIN (Simple Join)


The MySQL INNER JOIN

is used to return all rows from multiple tables where the join condition is satisfied. It is the
most common type of join.

Syntax:408ava

1. SELECT columns
2. FROM table1
3. INNER JOIN table2
4. ON table1.column = table2.column;

Image representation:

Let's take an example:

Consider two tables "officers" and "students", having the following data.

Execute the following query:

1. SELECT officers.officer_name, officers.address, students.course_name


2. FROM officers
3. INNER JOIN students
4. ON officers.officer_id = students.student_id;
Output:

Left Outer Join

The LEFT OUTER JOIN returns all rows from the left hand table specified in the ON
condition and only those rows from the other table where the join condition is fulfilled.

Syntax:

1. SELECT columns
2. FROM table1
3. LEFT [OUTER] JOIN table2
4. ON table1.column = table2.column;

Image representation:

Let's take an example:

Consider two tables "officers" and "students", having the following data.
Execute the following query:

1. SELECT officers.officer_name, officers.address, students.course_name


2. FROM officers
3. LEFT JOIN students
4. ON officers.officer_id = students.student_id;

Output:

Right Outer Join

The MySQL Right Outer Join returns all rows from the RIGHT-hand table specified in the
ON condition and only those rows from the other table where he join condition is fulfilled.
Syntax:

1. SELECT columns
2. FROM table1
3. RIGHT [OUTER] JOIN table2
4. ON table1.column = table2.column;

Image representation:

Let's take an example:

Consider two tables "officers" and "students", having the following data.

Execute the following query:

1. SELECT officers.officer_name, officers.address, students.course_name, students.student_n


ame
2. FROM officers
3. RIGHT JOIN students
4. ON officers.officer_id = students.student_id;
Output:

SELF JOIN:
The SQL SELF JOIN is used to join a table to itself as if the table were two tables;
temporarily renaming at least one table in the SQL statement.
Syntax
The basic syntax of SELF JOIN is as follows −
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
Here, the WHERE clause could be any given expression based on your requirement.
Example
Consider the following table.
CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us join this table using SELF JOIN as follows −
SQL> SELECT a.ID, b.NAME, a.SALARY
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;
This would produce the following result −
+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |
| 1 | Hardik | 2000.00 |
| 2 | Hardik | 1500.00 |
| 3 | Hardik | 2000.00 |
| 4 | Hardik | 6500.00 |
| 6 | Hardik | 4500.00 |
| 1 | Komal | 2000.00 |
| 2 | Komal | 1500.00 |
| 3 | Komal | 2000.00 |
| 1 | Muffy | 2000.00 |
| 2 | Muffy | 1500.00 |
| 3 | Muffy | 2000.00 |
| 4 | Muffy | 6500.00 |
| 5 | Muffy | 8500.00 |
| 6 | Muffy | 4500.00 |
+----+----------+---------+

SQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.

You can add SQL statements and functions to a view and present the data as if the data were
coming from one single table.

A view is created with the CREATE VIEW statement.

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: A view always shows up-to-date data! The database engine recreates the view, every
time a user queries it.
SQL CREATE VIEW Examples

The following SQL creates a view that shows all customers from Brazil:

Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

SQL Updating a View

A view can be updated with the CREATE OR REPLACE VIEW statement.

SQL CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

The following SQL adds the "City" column to the "Brazil Customers" view:

Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';

SQL Sub Query

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

Important Rule:

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

SQL subqueries are most frequently used with the Select statement.

Syntax

1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );

Example

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

You might also like