0% found this document useful (0 votes)
287 views15 pages

DBMS Unit 5

SQL is a language used to manage data in relational database management systems. It is used to create, modify, and extract data from databases. SQL allows users to define and manipulate data, create and drop tables and databases, and set permissions. Some key SQL commands include SELECT, UPDATE, DELETE, CREATE TABLE, and ALTER TABLE. SQL uses data types like strings, numbers, and dates to define the nature of data stored in database tables.

Uploaded by

ashwanimpec20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
287 views15 pages

DBMS Unit 5

SQL is a language used to manage data in relational database management systems. It is used to create, modify, and extract data from databases. SQL allows users to define and manipulate data, create and drop tables and databases, and set permissions. Some key SQL commands include SELECT, UPDATE, DELETE, CREATE TABLE, and ALTER TABLE. SQL uses data types like strings, numbers, and dates to define the nature of data stored in database tables.

Uploaded by

ashwanimpec20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Database Management System (CS/IT 4th SEM) unit 5

SQL
SQL (Structured Query Language) is used to perform operations on the records stored in the
database such as updating records, deleting records, creating and modifying tables, views, etc.
SQL is just a query language; it is not a database. To perform SQL queries, you need to install
any database, for example, Oracle, MySQL, MongoDB, PostGre SQL, SQL Server, DB2, etc.

What is SQL?
SQL stands for Structured Query Language.
It is designed for managing data in a relational database management system (RDBMS).
It is pronounced as S-Q-L or sometime See-Qwell.
SQL is a database language, it is used for database creation, deletion, fetching rows, and
modifying rows, etc.
SQL is based on relational algebra and tuple relational calculus.
All DBMS like MySQL, Oracle, MS Access, Sybase, Informix, PostgreSQL, and SQL
Server use SQL as standard database language.

Why SQL is required?


SQL is required:
 To create new databases, tables and views
 To insert records in a database
 To update records in a database
 To delete records from a database
 To retrieve data from a database
What SQL does?
 With SQL, we can query our database in several ways, using English-like statements.
 With SQL, a user can access data from a relational database management system.
 It allows the user to describe the data.
 It allows the user to define the data in the database and manipulate it when needed.
 It allows the user to create and drop database and table.

1
Database Management System (CS/IT 4th SEM) unit 5

 It allows the user to create a view, stored procedure, function in a database.


 It allows the user to set permission on tables, procedures, and views.
SQL Syntax
 SQL follows some unique set of rules and guidelines called syntax. Here, we are
providing all the basic SQL syntax.
 SQL is not case sensitive. Generally SQL keywords are written in uppercase.
 SQL statements are dependent on text lines. We can place a single SQL statement on one
or multiple text lines.
 You can perform most of the action in a database with SQL statements.
 SQL depends on relational algebra and tuple relational calculus.
SQL statement
SQL statements are started with any of the SQL commands/keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP etc. and the statement ends with a semicolon (;).
Example of SQL statement:
SELECT "column_name" FROM "table_name";
Why semicolon is used after SQL statements?
Semicolon is used to separate SQL statements. It is a standard way to separate SQL statements in
a database system in which more than one SQL statements are used in the same call.
SQL Commands
These are the some important SQL command:
 SELECT: it extracts data from a database.
 UPDATE: it updates data in database.
 DELETE: it deletes data from database.
 CREATE TABLE: it creates a new table.
 ALTER TABLE: it is used to modify the table.
 DROP TABLE: it deletes a table.
 CREATE DATABASE: it creates a new database.
 ALTER DATABASE: It is used to modify a database.
 INSERT INTO: it inserts new data into a database.
 CREATE INDEX: it is used to create an index (search key).

2
Database Management System (CS/IT 4th SEM) unit 5

 DROP INDEX: it deletes an index.


SQL Data Types
Data types are used to represent the nature of the data that can be stored in the database table. For
example, in a particular column of a table, if we want to store a string type of data then we will
have to declare a string data type of this column.
Data types mainly classified into three categories for every database.
 String Data types
 Numeric Data types
 Date and time Data types
Data Types in MySQL Databases
MySQL Data Types

A list of data types used in MySQL database. This is based on MySQL 8.0.

MySQL String Data Types

CHAR(Size) It is used to specify a fixed length string that can contain numbers,
letters, and special characters. Its size can be 0 to 255 characters.
Default is 1.

VARCHAR(Size) It is used to specify a variable length string that can contain numbers,
letters, and special characters. Its size can be from 0 to 65535
characters.

BINARY(Size) It is equal to CHAR() but stores binary byte strings. Its size parameter
specifies the column length in the bytes. Default is 1.

VARBINARY(Size) It is equal to VARCHAR() but stores binary byte strings. Its size
parameter specifies the maximum column length in bytes.

TEXT(Size) It holds a string that can contain a maximum length of 255 characters.

TINYTEXT It holds a string with a maximum length of 255 characters.

MEDIUMTEXT It holds a string with a maximum length of 16,777,215.

LONGTEXT It holds a string with a maximum length of 4,294,967,295 characters.

3
Database Management System (CS/IT 4th SEM) unit 5

ENUM(val1, val2, It is used when a string object having only one value, chosen from a
val3,...) list of possible values. It contains 65535 values in an ENUM list. If
you insert a value that is not in the list, a blank value will be inserted.

SET( It is used to specify a string that can have 0 or more values, chosen
val1,val2,val3,....) from a list of possible values. You can list up to 64 values at one time
in a SET list.

BLOB(size) It is used for BLOBs (Binary Large Objects). It can hold up to 65,535
bytes.

MySQL Numeric Data Types

BIT(Size) It is used for a bit-value type. The number of bits per value is specified
in size. Its size can be 1 to 64. The default value is 1.

INT(size) It is used for the integer value. Its signed range varies from -
2147483648 to 2147483647 and unsigned range varies from 0 to
4294967295. The size parameter specifies the max display width that
is 255.

INTEGER(size) It is equal to INT(size).

FLOAT(size, d) It is used to specify a floating point number. Its size parameter


specifies the total number of digits. The number of digits after the
decimal point is specified by d parameter.

FLOAT(p) It is used to specify a floating point number. MySQL used p parameter


to determine whether to use FLOAT or DOUBLE. If p is between 0
to24, the data type becomes FLOAT (). If p is from 25 to 53, the data
type becomes DOUBLE().

DOUBLE(size, d) It is a normal size floating point number. Its size parameter specifies
the total number of digits. The number of digits after the decimal is

4
Database Management System (CS/IT 4th SEM) unit 5

specified by d parameter.

DECIMAL(size, d) It is used to specify a fixed point number. Its size parameter specifies
the total number of digits. The number of digits after the decimal
parameter is specified by d parameter. The maximum value for the
size is 65, and the default value is 10. The maximum value for d is 30,
and the default value is 0.

DEC(size, d) It is equal to DECIMAL(size, d).

BOOL It is used to specify Boolean values true and false. Zero is considered
as false, and nonzero values are considered as true.

MySQL Date and Time Data Types

DATE It is used to specify date format YYYY-MM-DD. Its supported range


is from '1000-01-01' to '9999-12-31'.

DATETIME(fsp) It is used to specify date and time combination. Its format is YYYY-
MM-DD hh:mm:ss. Its supported range is from '1000-01-01 00:00:00'
to 9999-12-31 23:59:59'.

TIMESTAMP(fsp) It is used to specify the timestamp. Its value is stored as the number of
seconds since the Unix epoch('1970-01-01 00:00:00' UTC). Its format
is YYYY-MM-DD hh:mm:ss. Its supported range is from '1970-01-01
00:00:01' UTC to '2038-01-09 03:14:07' UTC.

TIME(fsp) It is used to specify the time format. Its format is hh:mm:ss. Its
supported range is from '-838:59:59' to '838:59:59'

YEAR It is used to specify a year in four-digit format. Values allowed in four


digit format from 1901 to 2155, and 0000.

5
Database Management System (CS/IT 4th SEM) unit 5

SQL Operators
SQL statements generally contain some reserved words or characters that are used to perform
operations such as comparison and arithmetical operations etc. These reserved words or
characters are known as operators.
Generally there are three types of operators in SQL:
 SQL Arithmetic Operators
 SQL Comparison Operators
 SQL Logical Operators
SQL Arithmetic Operators:
Let's assume two variables "a" and "b". Here "a" is valued 50 and "b" valued 100.
Example:

Operators Descriptions Examples

+ It is used to add containing values of both operands a+b will give 150

- It subtracts right hand operand from left hand operand a-b will give -50

* It multiply both operand's values a*b will give 5000

/ It divides left hand operand by right hand operand b/a will give 2

% It divides left hand operand by right hand operand and b%a will give 0
returns reminder

SQL Comparison Operators:


Let's take two variables "a" and "b" that are valued 50 and 100.

Operator Description Example

= Examine both operands value that are equal or not,if yes (a=b) is not
condition become true. true

!= This is used to check the value of both operands equal or not,if (a!=b) is true
not condition become true.

6
Database Management System (CS/IT 4th SEM) unit 5

<> Examines the operand's value equal or not, if values are not (a<>b) is true
equal condition is true

> Examine the left operand value is greater than right Operand, if (a>b) is not
yes condition becomes true true

< Examines the left operand value is less than right Operand, if (a<="" td="">
yes condition becomes true

>= Examines that the value of left operand is greater than or equal (a>=b) is not
to the value of right operand or not,if yes condition become true
true

<= Examines that the value of left operand is less than or equal to (a<=b) is true
the value of right operand or not, if yes condition becomes true

!< Examines that the left operand value is not less than the right (a!<=""
operand value td="">

!> Examines that the value of left operand is not greater than the (a!>b) is true
value of right operand
SQL Logical Operators:
This is the list of logical operators used in SQL.

Operator Description

ALL This is used to compare a value to all values in another value set.

AND This operator allows the existence of multiple conditions in an SQL


statement.

ANY This operator is used to compare the value in list according to the condition.

BETWEEN this operator is used to search for values, that are within a set of values

IN this operator is used to compare a value to that specified list value

NOT the NOT operator reverse the meaning of any logical operator

7
Database Management System (CS/IT 4th SEM) unit 5

OR this operator is used to combine multiple conditions in SQL statements

EXISTS the EXISTS operator is used to search for the presence of a row in a specified
table

LIKE this operator is used to compare a value to similar values using wildcard
operator

SQL CREATE Database

The SQL CREATE DATABASE statement is used by a developer to create a database.

Let's see the syntax of SQL CREATE DATABASE:

CREATE DATABASE database_name;

If you want to add tables in that database, you can use CREATE TABLE statement.

Create Database in MySQL

In MySQL, same command is used to create a database.

CREATE DATABASE database_name;


SQL DROP Database

SQL DROP statement is used to delete or remove indexes from a table in the database.
If you want to delete or drop an existing database in a SQL schema, you can use SQL DROP
DATABASE
Let's see the syntax of SQL DROP DATABASE:
DROP DATABASE database_name;

SQL RENAME Database


SQL RENAME DATABASE is used when you need to change the name of your database.
Sometimes it is used because you think that the original name is not more relevant to the
database or you want to give a temporary name to that database.

8
Database Management System (CS/IT 4th SEM) unit 5

Let's see how to rename MySql and SQL Server databases.


Rename MySQL database
To rename the mysql database, you need to follow the following syntax:

RENAME DATABASE old_db_name TO new_db_name;


SQL SELECT Database
In MySQL database, you need to select a database first before executing any query on table,
view etc. To do so, we use following query:
USE DATABASE database_name;

SQL Table

Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.

Table is the simple form of data storage. A table is also considered as a convenient
representation of relations.
Let's see an example of an employee table:

Employee

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000


In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY"
are the column names. The combination of data of multiple columns forms a row e.g. "Ankit",
"Lucknow" and 15000 are the data of one row.
SQL TABLE Variable
The SQL Table variable is used to create, modify, rename, copy and delete tables. Table
variable was introduced by Microsoft.
It was introduced with SQL server 2000 to be an alternative of temporary tables.

9
Database Management System (CS/IT 4th SEM) unit 5

It is a variable where we temporary store records and results. This is same like temp table but in
the case of temp table we need to explicitly drop it.
Table variables are used to store a set of records. So declaration syntax generally looks like
CREATE TABLE syntax.
create table "tablename"
("column1" "data type",
"column2" "data type",
...
"columnN" "data type");
When a transaction rolled back the data associated with table variable is not rolled back.
A table variable generally uses lesser resources than a temporary variable.
Table variable cannot be used as an input or an output parameter.
SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.
Table is the simple form of data storage. A table is also considered as a convenient
representation of relations.
Let's see an example of an employee table:

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000

In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY"
are the column names. The combination of data of multiple columns forms a row e.g. "Ankit",
"Lucknow" and 15000 are the data of one row.

SQL TABLE Variable

The SQL Table variable is used to create, modify, rename, copy and delete tables. Table
variable was introduced by Microsoft.

10
Database Management System (CS/IT 4th SEM) unit 5

It was introduced with SQL server 2000 to be an alternative of temporary tables.


It is a variable where we temporary store records and results. This is same like temp table but in
the case of temp table we need to explicitly drop it.
Table variables are used to store a set of records. So declaration syntax generally looks like
CREATE TABLE syntax.
create table "tablename"
("column1" "data type",
"column2" "data type",
...
"columnN" "data type");
When a transaction rolled back the data associated with table variable is not rolled back.
A table variable generally uses lesser resources than a temporary variable.
Table variable cannot be used as an input or an output parameter.
SQL CREATE TABLE
SQL CREATE TABLE statement is used to create table in a database.
If you want to create a table, you should name the table and define its column and each column's
data type.
Let's see the simple syntax to create the table.
create table "tablename"
("column1" "data type",
"column2" "data type",
"column3" "data type",
...
"columnN" "data type");

The data type of the columns may vary from one database to another. For example, NUMBER is
supported in Oracle database for integer value whereas INT is supported in MySQL.
Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL
are the constraint showing that these fields cannot be NULL while creating records in the table.
SQL> CREATE TABLE STUDENTS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,

11
Database Management System (CS/IT 4th SEM) unit 5

ADDRESS CHAR (25),


PRIMARY KEY (ID)
);

You can verify it, if you have created the table successfully by looking at the message displayed
by the SQL Server, else you can use DESC command as follows:
SQL> DESC STUDENTS;

FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL

Now you have the STUDENTS table available in your database and you can use to store required
information related to students.

SQL CREATE TABLE Example in MySQL


Let's see the command to create a table in MySQL database.
CREATE TABLE Employee
(
EmployeeID int,
FirstName varchar(255),
LastName varchar(255),
Email varchar(255),
AddressLine varchar(255),
City varchar(255)
);
SQL DROP TABLE
A SQL DROP TABLE statement is used to delete a table definition and all data from a table.
This is very important to know that once a table is deleted all the information available in the
table is lost forever, so we have to be very careful when using this command.
Let's see the syntax to drop the table from the database.

12
Database Management System (CS/IT 4th SEM) unit 5

DROP TABLE "table_name";


Let us take an example:
First we verify STUDENTS table and then we would delete it from the database.
SQL> DESC STUDENTS;

FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL


This shows that STUDENTS table is available in the database, so we can drop it as follows:
SQL>DROP TABLE STUDENTS;
Now, use the following command to check whether table exists or not.
SQL> DESC STUDENTS;
Query OK, 0 rows affected (0.01 sec)
As you can see, table is dropped so it doesn't display it.

SQL DROP TABLE Example in MySQL


Let's see the command to drop a table from the MySQL database.
DROP TABLE table_name;
SQL DELETE TABLE
The DELETE statement is used to delete rows from a table. If you want to remove a specific row
from a table you should use WHERE condition.
DELETE FROM table_name [WHERE condition];
But if you do not specify the WHERE condition it will remove all the rows from the table.
DELETE FROM table_name;
There are some more terms similar to DELETE statement like as DROP statement and
TRUNCATE statement but they are not exactly same there are some differences between them.

13
Database Management System (CS/IT 4th SEM) unit 5

Difference between DELETE and TRUNCATE statements


There is a slight difference b/w delete and truncate statement. The DELETE statement only
deletes the rows from the table based on the condition defined by WHERE clause or delete all
the rows from the table when condition is not specified.
But it does not free the space containing by the table.
The TRUNCATE statement: it is used to delete all the rows from the table and free the
containing space.
Let's see an "employee" table.

Emp_id Name Address Salary

1 Aryan Allahabad 22000

2 Shurabhi Varanasi 13000

3 Pappu Delhi 24000


Execute the following query to truncate the table:
TRUNCATE TABLE employee;
Difference b/w DROP and TRUNCATE statements
When you use the drop statement it deletes the table's row together with the table's definition so
all the relationships of that table with other tables will no longer be valid.
When you drop a table:
Table structure will be dropped
Relationship will be dropped
Integrity constraints will be dropped
Access privileges will also be dropped
On the other hand when we TRUNCATE a table, the table structure remains the same, so you
will not face any of the above problems.
SQL RENAME TABLE
SQL RENAME TABLE syntax is used to change the name of a table. Sometimes, we choose
non-meaningful name for the table. So it is required to be changed.
Let's see the syntax to rename a table from the database.
ALTER TABLE table_name

14
Database Management System (CS/IT 4th SEM) unit 5

RENAME TO new_table_name;
Optionally, you can write following command to rename the table.
RENAME old_table _name To new_table_name;
Let us take an example of a table named "STUDENTS", now due to some reason we want to
change it into table name "ARTISTS".
Table1: students

Name Age City

Amrita gill 25 Amritsar

Amrender sirohi 22 Ghaziabad

Divya khosla 20 Delhi


You should use any one of the following syntax to RENAME the table name:
ALTER TABLE STUDENTS
RENAME TO ARTISTS;
Or
RENAME STUDENTS TO ARTISTS;
After that the table "students" will be changed into table name "artists"

15

You might also like