Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

SQL

The document provides an overview of Structured Query Language (SQL), detailing its purpose in managing relational databases, its history, and its various commands and data types. It explains the different types of SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), along with examples of their usage. Additionally, it covers SQL constraints, data types, and specific commands for creating, altering, and dropping database objects.

Uploaded by

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

SQL

The document provides an overview of Structured Query Language (SQL), detailing its purpose in managing relational databases, its history, and its various commands and data types. It explains the different types of SQL commands, including Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), along with examples of their usage. Additionally, it covers SQL constraints, data types, and specific commands for creating, altering, and dropping database objects.

Uploaded by

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

Database Management

System (DBMS)
UNIT 2
Structured Query Language (SQL)
SYLLABUS
Structured Query Language (SQL)
SQL is Structured Query Language that is used for storing and
managing data in RDMS.
 Structured means only related to relational data.
 It allows users to communicate with relational database and
retrieve data from the tables.
 All RDBMS like MySQL, Oracle, DB2, MS Access, Informix
uses SQL as an standard database language.
 SQL allows users to query the database in a number of ways,
using English-like statements.
 SQL is mostly used by engineers in software development for
data storage.
Relational Model and SQL: Key Highlights
 Dr. E.F. Codd introduced the Relational Model (based on Relational
Algebra and Tuple Relational Calculus) in his paper published in the
ACM journal in 1970.
 IBM implemented the SQL language, originally called SEQUEL
(Structured English Query Language) as part of the System R
project in the early 1970s.
 SEQUEL is renamed/ shortened to SQL.
 1986/87: SQL became a standard:
• American National Standards Institute, ANSI (1986)
• International Organization for Standardization, ISO (1987)
 SQL Versions: SQL-86, SQL-89, SQL-92, SQL:1999, SQL:2003,
SQL:2006, SQL:2008, SQL:2011, SQL:2016, SQL:2023.
 Commercial Vendors (Oracle, SQL Server, etc.) implement standard
features with proprietary extensions.
SQL: Introduction
 SQL is Non-Procedural, Domain-Specific Language, which allows
to declare what we want to do, but not how to do.
 SQL lets you access and manipulate databases.
 SQL is NOT case sensitive. For Example, select is the same as
SELECT.
 But names of the database, tables and columns are case sensitive.
• For Example, In the given SQL query, table named as STUDENT is
different from student
SELECT * from STUDENT;
SELECT * from student;
SQL statements can use multiple lines.
SQL: Rules
 Structure query language is not case sensitive. Generally, keywords
of SQL are written in uppercase.
 Every SQL statements should ends with a semicolon.
 Statements of SQL are dependent on text lines. We can use a single
SQL statement on one or multiple text line.
 Using the SQL statements, you can perform most of the actions in a
database.
 SQL depends on tuple relational calculus and relational algebra.
What Can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views
What Can SQL do?
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
SQL Datatypes
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.
1. String Data types
2. Numeric Data types
3. Date and time Data types
MySQL String Data Types
Data Type Description
It is used to specify a fixed length string that can contain
CHAR(Size) numbers, letters, and special characters. Its size can be 0 to
255 characters.
It is used to specify a variable length string that can contain
VARCHAR(Size) numbers, letters, and special characters. Its size can be from 0
to 65535 characters.
It is equal to CHAR() but stores binary byte strings. Its size
BINARY(Size)
parameter specifies the column length in the bytes.
It is equal to VARCHAR() but stores binary byte strings. Its size
VARBINARY(Size)
parameter specifies the maximum column length in bytes.
It holds a string that can contain a maximum length of 255
TEXT(Size)
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.
MySQL String Data Types
Data Type Description
It holds a string with a maximum length of 4,294,967,295
LONGTEXT
characters.
It is used when a string object having only one value, chosen
ENUM(val1, from a list of possible values. It contains 65535 values in an
val2, val3,...) ENUM list. If you insert a value that is not in the list, a blank
value will be inserted.
It is used to specify a string that can have 0 or more values,
SET( val1,val2,v
chosen from a list of possible values. You can list up to 64
al3,....)
values at one time in a SET list.
It is used for BLOBs (Binary Large Objects). It can hold up to
BLOB(size)
65,535 bytes.
MySQL Numeric Data Types
Data Type Description
It is used for a bit-value type. The number of bits per value is
BIT(Size)
specified in size. Its size can be 1 to 64. The default value is 1.
It is used for the integer value. Its signed range varies from -
2147483648 to 2147483647 and unsigned range varies from 0
INT(size)
to 4294967295. The size parameter specifies the max display
width that is 255.
INTEGER(siz
It is equal to INT(size).
e)
It is used to specify a floating point number. Its size parameter
FLOAT(size,
specifies the total number of digits. The number of digits after
d)
the decimal point is specified by d parameter.

It is used to specify a floating point number. MySQL used p


parameter to determine whether to use FLOAT or DOUBLE. If p
FLOAT(p)
is between 0 to24, the data type becomes FLOAT (). If p is from
25 to 53, the data type becomes DOUBLE().
MySQL Date and Time Data Types
Data Type Description
It is used to specify date format YYYY-MM-DD. Its
DATE
supported range is from '1000-01-01' to '9999-12-31'.
It is used to specify date and time combination. Its format
DATETIME(fsp) 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'.
It is used to specify the timestamp. Its value is stored as
the number of seconds since the Unix epoch('1970-01-01
TIMESTAMP(fsp) 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.
It is used to specify the time format. Its format is
TIME(fsp) hh:mm:ss. Its supported range is from '-838:59:59' to
'838:59:59'
It is used to specify a year in four-digit format. Values
YEAR
allowed in four digit format from 1901 to 2155, and 0000.
SQL Commands Types
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.
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Control Language (DCL)
4. Transaction Control Language (TCL)
SQL Commands Types
Data Definition Language (DDL) commands are used to define the
structure and schema of the database.
1. CREATE - to create new table or database
2. ALTER - to alter the structure of table
3. DROP - to delete a table from database
4. TRUNCATE - to delete all records from table
5. RENAME - to rename a table

Data Manipulation Language (DML) commands are used for


accessing and manipulating the data stored in the database.
6. SELECT - to retrieve data from the database
7. INSERT - to insert a new row into a table
8. UPDATE - to update existing row in a table
9. DELETE - to delete a row from a table
SQL Commands Types
Data Control Language (DCL) are the commands to control the
access of the data stored in the database
1. GRANT - grant permission to user for database access
2. REVOKE - take back granted permission from user

Transaction Control Language (TCL) commands are used to


manage the changes made by the DML statement.
3. COMMIT - to permanently save the transaction
4. ROLLBACK - to undo transaction
5. SAVEPOINT - to temporarily save a transaction so that you can
rollback to that point whenever necessary

Note: TCL Commands are used for only DML commands while DDL
and DCL commands are committed.
Data Definition Language (DDL)
 DDL is used for creating and modifying the database objects such
as tables, views and users.
 It 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.
 DDL Commands are:
1. CREATE - to create new table or database
2. ALTER - to alter the structure of table
3. DROP - to delete a table from database
4. TRUNCATE - to delete all records from table
5. RENAME - to rename a table
Create Command
CREATE statement is used to create database schema and to define
the datatype and structure of the data to be stored in the database.
CREATE statement can be used to create database and tables.

CREATE DATABASE is used to create a database in RDBMS;


Syntax: CREATE DATABASE database_name;
Example: CREATE DATABASE my_database;

SHOW statement: used to show the existing database and


tables
Syntax: SHOW database;
Example: Show tables;
USE statement: To use or select any existing database
Syntax: USE database_name;
Example: USE my_database;
CREATE TABLE Command
CREATE TABLE statement is used to create a new table in a
database.
 It specifies column names of the table, its data types (e.g. varchar,
integer, date, etc.) and can also specify integrity constraints (e.g.
Primary key, foreign key, not null, unique).
Syntax: CREATE TABLE table_name
( column_name1 datatype,
column_name2 datatype,
..
..
column_name_n datatype,
(Integrity Constraints)
);
CREATE TABLE Command Example
CREATE TABLE Employee ( CREATE TABLE Branch (
E_ID int, B_ID int,
E_Name varchar(20), B_Name varchar(20),
Age int, Assets integer,
Address varchar (100), primary key (B_ID)
Salary numeric (10,2)); check(assets>0));

DESC statement: used to describe the details of the table


structure, but it is not part of the ANSI SQL standard
Syntax: DESC table_name;
Example: DESC Employee;
SQL Constraints
Constraints can be specified when the table is created with
the CREATE TABLE statement, or after the table is created with
the ALTER TABLE statement.
 SQL constraints are used to specify rules for the data in a table.
 They 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.
SQL Constraints
The following constraints are commonly used in SQL:
 NOT NULL - Ensures that a column cannot have a NULL value
 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between
tables
 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
ALTER TABLE Command
The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.

1. To add a column in a table, use the following syntax:


Syntax: ALTER TABLE table_name ADD column_name datatype;
Example: ALTER TABLE Customers ADD Email varchar(255);
2. To delete a column in a table, use the following syntax
(notice that some database systems don't allow deleting a
column):
Syntax: ALTER TABLE table_name DROP COLUMN column_name;
Example: ALTER TABLE Customers DROP COLUMN Email;
ALTER TABLE Command
3. To rename a column in a table, use the following syntax:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;

4. To change the data type of a column in a table, use the


following syntax:
ALTER TABLE Command Example
Let us consider a table “Persons”

Now we want to add a column named "DateOfBirth" in the "Persons"


table.
We use the following SQL statement:
ALTER TABLE Persons ADD DateOfBirth date;
ALTER TABLE Command Example
Let us consider a table “Persons”

Now we want to change the data type of the column named


"DateOfBirth " in the "Persons" table.
We use the following SQL statement:
ALTER TABLE Persons ALTER COLUMN DateOfBirth year;
The "DateOfBirth" column is now of type year and is going to hold a year
in a two- or four-digit format.
RENAME Command
 If you want to rename your table to give it a more relevant name.
 For this purpose, you can use ALTER TABLE to rename the name of the
table.
 SQL ALTER TABLE is a command used to modify the structure of an
existing table in a database.

Syntax:
ALTER TABLE table_name
RENAME TO new_table_name;

ALTER TABLE table_name


RENAME COLUMN old_name TO new_name;
RENAME Command Example
Input Table “Student”

Question: Change the name of column name to FIRST_NAME in


table Student.

ALTER TABLE Student RENAME Column name TO FIRST_NAME;


DROP Command Example
DROP Commend can be used to delete a table, database, column,
constraint, default constraint.

The DROP TABLE command deletes a table in the database.


The following SQL deletes the table "Shippers":
DROP TABLE Shippers;

The DROP COLUMN command is used to delete a column in an


existing table.
The following SQL deletes the "ContactName" column from the
"Customers" table:
ALTER TABLE Customers
DROP COLUMN ContactName;
DROP Command Example
DROP a PRIMARY KEY DROP a FOREIGN KEY
Constraint Constraint
To drop a PRIMARY KEY To drop a FOREIGN KEY
constraint, use the following constraint, use the following
SQL: SQL:
DROP Command Example
The DROP DATABASE command is used is to delete an existing
SQL database.
The following SQL drops a database named "testDB":
DROP DATABASE testDB;
TRUNCATE Command
 The Truncate statement is a DDL command that is used to delete
the complete data from the table without deleting the table
structure.
 You cannot use the WHERE clause with this command; therefore,
you cannot filter the records.
 It only removes the table data, while the table definition remains
the same.
 It is faster than the DELETE command as it removes the record
without logging the individual row deletions.

Syntax for TRUNCATE command in SQL


The syntax for SQL TRUNCATE TABLE is just a one-line command
TRUNCATE TABLE followed by the table_name you want

TRUNCATE TABLE table_name;


TRUNCATE Command Example
CREATE TABLE Student(
RollNo int PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Gender TEXT NOT NULL;
Subject VARCHAR(30),
MARKS INT (3)
);

INSERT INTO Student VALUES (1, Vaibhav, M, Mathematic, 100);


INSERT INTO Student VALUES (2, Vishal, M, Physics, 79);
INSERT INTO Student VALUES (3, Saumya, F, Chemistry, 95);
INSERT INTO Student VALUES (4, Arun, M, English, 78);
INSERT INTO Student VALUES (5, Anjum, F, Hindi, 83);
INSERT INTO Student VALUES (6, Radhika, F, Biology, 57);
INSERT INTO Student VALUES (7, Harpreet, F, Physical Education, 68);

SELECT * FROM Student;


TRUNCATE Command Example 1
Example 1: Use the TRUNCATE TABLE command in the
student table to remove all the records.
TRUNCATE TABLE Student;
SELECT * FROM Student;
TRUNCATE Command Example 2
Example 2: TRUNCATE TABLE command over a partition
TRUNCATE TABLE Student
WITH PARTITIONS (1, 3 TO 5);
TRUNCATE Command Points
 TRUNCATE TABLE is used to empty a table by removing all rows,
but it retains the table structure.
 TRUNCATE TABLE is ideal for quickly removing all data from a table
without deleting the table structure, making it efficient for data
cleanup operations
 TRUNCATE TABLE is faster and uses fewer system and transaction
logs compared to DELETE.
 However, TRUNCATE TABLE typically cannot be rolled back if
executed within a transaction.
SQL TRUNCATE vs DROP
Feature TRUNCATE TABLE DROP TABLE

Removes all rows from a table, leaving the structure Deletes the entire table, including its
Operation
intact. structure.

Generally faster than DELETE since it deallocates Fast operation since it removes both data
Speed
data pages. and structure.

Minimal logging; typically logs page deallocations Fully logged; the entire table drop is
Transaction Log
only. recorded.

Deleted; table structure and data are both


Table Structure Retained; only the data is removed.
removed.

Resets the auto-increment counter to the seed value


Auto-increment Counter No impact, as the entire table is removed.
(if present).

Cannot drop a table if other tables


Cannot truncate a table if it is referenced by a
Foreign Key Constraints reference it unless the foreign key
foreign key.
constraint is removed first.

Used when you need to remove all data from a table Used when you want to completely remove
Usage
but keep the table itself. the table from the database.

Data cannot be recovered unless a backup is The table and its data cannot be recovered
Recovery
available (depends on the database system). unless a backup is available.

Permissions Required Requires ALTER permission on the table. Requires DROP permission on the table.
SQL TRUNCATE vs DELETE
Feature TRUNCATE TABLE DELETE

Removes rows based on a WHERE


Operation Removes all rows from a table clause or all rows if no condition is
specified

WHERE Clause Not supported Supported

Transaction Logging Minimal logging (usually faster) Fully logged (can be slower)

Rollback (Transaction Can be rolled back if within a


Generally cannot be rolled back in some DBMS
Support) transaction

Triggers Does not fire triggers Fires triggers

Cannot truncate a table referenced by a foreign Can delete rows in a table referenced
Foreign Key Constraints
key (without disabling the constraint) by a foreign key

Resets identity seed value (auto-increment


Identity Reset Does not reset the identity seed value
counter)

Can be slower, especially for large


Performance Generally faster for large data volumes
data volumes

Used to remove specific rows based


Usage Typically used to quickly empty a table
on a condition

Retains the table structure, constraints, and Retains the table structure,
Table Structure
indexes constraints, and indexes
DELETE v/s DROP v/s TRUNCATE
Paramete
DELETE Command DROP Command
rs TRUNCATE Command
The DELETE command is Data The DROP command is Data The TRUNCATE command is
Language Manipulation Language Definition Language a Data Definition Language
Command. Command. Command.

The TRUNCATE Command


The DELETE command deletes The DROP Command drops
deletes all the rows from the
Use one or more existing records the complete table from the
existing table, leaving the
from the table in the database. database.
row with the column names.

We can restore any deleted We cannot get the complete We cannot restore all the
row or multiple rows from the table deleted from the deleted rows from the
Transition
database using the ROLLBACK database using the database using the
command. ROLLBACK command. ROLLBACK command.

The DROP command The TRUNCATE command


The DELETE command does
Memory removes the space does not free the space
not free the allocated space of
Space allocated for the table from allocated for the table from
the table from memory.
memory. memory.
DELETE v/s DROP v/s TRUNCATE
Parameters DELETE Command DROP Command TRUNCATE Command

Performanc The DELETE command The DROP Command has faster The TRUNCATE command
e Speed performs slower than the DROP performance than DELETE works faster than the DROP
command and TRUNCATE Command but not as compared command and DELETE
command as it deletes one or to the Truncate Command command because it deletes
more rows based on a specific because the DROP command all the records from the table
condition. deletes the table from the without any condition.
database after deleting the rows.
Integrity The Integrity Constraints The Integrity Constraints get The Integrity Constraints will
Constraints remain the same in the DELETE removed for the DROP not get removed from the
command. command. TRUNCATE command.

Permission DELETE permission is required We need ALTER permission on We need table ALTER
to delete the rows of the table. the schema to which the table permission to use the
belongs and CONTROL TRUNCATE command.
permission on the table to use
the DROP command.

Syntax DELETE FROM table_name DROP TABLE table_name; TRUNCATE TABLE


WHERE condition; table_name;
Data Manipulation Language (DML)
 Data Manipulation Language (DML) is a subset of SQL statements
that allow users to add, delete, update, and retrieve data from
database tables.
 DML is a crucial part of database management, as it provides a
standardized way to interact with and modify data in a database.
 DML is different from DDL, which is a set of SQL statements that
are used to edit and manipulate the structure of databases.

Some examples of DML statements include:


1. INSERT: Adds new data or values to a database
2. SELECT: To retrieve data from the database
3. UPDATE: Changes or updates existing data in a database
4. DELETE: Deletes data or values from a database table
INSERT INTO Command
The INSERT INTO statement is used to insert new records in a
table.
INSERT INTO Command Example 1
Consider the given table named as “customer”

The following SQL statement inserts a new record in the "Customers"


table:

INSERT INTO Customers (CustomerName, ContactName, Address, City,


PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
INSERT INTO Command Example 1
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
INSERT INTO Command Example 2
Insert Data Only in Specified Columns
 It is also possible to only insert data in specific columns.
 The following SQL statement will insert a new record, but only insert
data in the "CustomerName", "City", and "Country" columns
(CustomerID will be updated automatically):

INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');
INSERT INTO Command Example 3
Insert Multiple Rows
 It is also possible to insert multiple rows in one statement.
 To insert multiple rows of data, we use the same INSERT
INTO statement, but with multiple values:

INSERT INTO Customers (CustomerName, ContactName, Address, City,


PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien
15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1
0AA', 'UK’);

Make sure you separate each set of values with a comma ,.


SQL SELECT statement
 The SELECT statement is the most commonly used command in
Structured Query Language.
 It is used to access the records from one or more database tables
and views.
 It also retrieves the selected data that follow the conditions we want.
 By using this command, we can also access the particular record
from the particular column of the table.
 The table which stores the record returned by the SELECT statement
is called a result-set table.
Syntax:
1. SELECT * FROM Name_of_Table
2. SELECT Column_Name_1, Column_Name_2, ....., Column_Name_N
FROM Table_Name;
3. SELECT * FROM Name_of_Table WHERE [condition];
SQL SELECT statement
Consider the given Employee_Details table:

SELECT * FROM Employee_Details WHERE Emp_Panelty = 500


;
SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in
a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Be careful when updating records in a table! Notice the WHERE clause


in the UPDATE statement. The WHERE clause specifies which record(s)
that should be updated. If you omit the WHERE clause, all records in
the table will be updated!
SQL UPDATE Statement Example
Consider the Customers table used in the examples:

The following SQL statement updates the first customer (CustomerID


= 1) with a new contact person and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
SQL UPDATE Statement Example
SQL DELETE Statement
The DELETE statement is used to delete existing records in a
table.

DELETE Syntax:
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice
the WHERE clause in the DELETE statement. The WHERE clause
specifies which record(s) should be deleted. If you omit
the WHERE clause, all records in the table will be deleted!
SQL DELETE Statement
The following SQL statement
deletes the customer "Alfreds
Futterkiste" from the
"Customers" table:
DELETE FROM Customers WHER
E CustomerName='Alfreds
Futterkiste';
SQL DELETE Statement
Delete All Records
It is possible to delete all rows in a table without deleting the table.
This means that the table structure, attributes, and indexes will be
intact:

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers"


table, without deleting the table:

DELETE FROM Customers;

Delete a Table
To delete the table completely, use the DROP TABLE statement:
DROP TABLE Customers;
SQL DELETE Statement
Delete All Records
It is possible to delete all rows in a table without deleting the table.
This means that the table structure, attributes, and indexes will be
intact:

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers"


table, without deleting the table:

DELETE FROM Customers;

Delete a Table
To delete the table completely, use the DROP TABLE statement:
DROP TABLE Customers;
Data Control Language (DCL)
 DCL commands are primarily used to implement access control
on the data stored in the database. It is implemented along
the DML (Data Manipulation Language) and DDL (Data Definition
Language) commands.
 It has a simple syntax and is easiest to implement in a database.
 The administrator can implement DCL commands to add or
remove database permissions on a specific user that uses
the database when required.
 DCL commands are implemented to grant, revoke and deny
permission to retrieve or modify the data in the database.
 The two types of DCL commands are as follows:
1. GRANT
2. REVOKE
GRANT Command
 GRANT, as the name itself suggests, allows the administrator to
provide particular privileges or permissions over a database object,
such as a table, view, or procedure.
 It can provide user access to perform certain database or
component operations.
 In simple language, the GRANT command allows the user to
implement other SQL commands on the database or its objects.
 The primary function of the GRANT command is to provide
administrators the ability to ensure the security and integrity of the
data is maintained in the database.

Syntax:
GRANT privileges_names ON object TO user;
Implementing GRANT Statement
Consider a scenario where you are the database administrator, and a
student table is in the database. Suppose you want a specific user
Aman to only SELECT (read)/ retrieve the data from the student table.
Then you can use GRANT in the below GRANT statement.
GRANT SELECT ON student TO Aman;

Note: Implementing the above statement will also limit Aman's


operations. Aman won't be able to modify the data stored in the
table. It will prevent the user from user to insert, to update, or
deleting the data in the student table in the database.
REVOKE Command
 As the name suggests, revoke is to take away.
 The REVOKE command enables the database administrator to
remove the previously provided privileges or permissions from a
user over a database or database object, such as a table, view, or
procedure.
 The REVOKE commands prevent the user from accessing or
performing a specific operation on an element in the database.
 In simple language, the REVOKE command terminates the ability
of the user to perform the mentioned SQL command in the
REVOKE query on the database or its component.
 The primary reason for implementing the REVOKE query in the
database is to ensure the data's security and integrity.

Syntax:
REVOKE privileges_names ON object TO user;
Implementing REVOKE Statement
Consider a scenario where the user is the database administrator. In
the above implementation of the GRANT command, the user Aman
was provided permission to implement a SELECT query on the
student table that allowed Aman to read or retrieve the data from the
table. Due to certain circumstances, the administrator wants to
revoke the abovementioned permission.
To do so, the administrator can implement the below REVOKE
statement:
REVOKE SELECT ON student TO Aman;
This will stop the user Aman from implementing the SELECT query on
the student table. The user may be able to implement other queries
in the database.
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:
1. COMMIT
2. ROLLBACK
3. SAVEPOINT
Transaction Control Language
1. COMMIT: Commit command is used to save all the transactions to the
database.
Syntax: COMMIT;
Example: DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
2. 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;
3. SAVEPOINT: It is used to roll the transaction back to a certain point
without rolling back the entire transaction.
Syntax: SAVEPOINT SAVEPOINT_NAME;
Transaction Control Language
1. 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;
2. SAVEPOINT: It is used to roll the transaction back to a certain point
without rolling back the entire transaction.
Syntax: SAVEPOINT SAVEPOINT_NAME;
INSERT INTO employees VALUES (1, 'John Doe’);
SAVEPOINT sp1;
INSERT INTO employees VALUES (2, 'Jane Smith’); Rollback
and Savepoint
ROLLBACK TO sp1;
Example
Clause in SQL
A clause in SQL is a built-in function that helps to fetch the required records
from a database table.
WHERE Clause
 The SQL WHERE clause is used to specify a condition while fetching the
data from a single table or by joining with multiple tables.
 If the given condition is satisfied, then only it returns a specific value from
the table. You should use the WHERE clause to filter the records and
fetching only the necessary records.
 The WHERE clause is not only used in the SELECT statement, but it is also
used in the UPDATE, DELETE statement, etc., which we would examine in
the subsequent chapters.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
WHERE Clause in SQL

The following code is an example which would fetch the ID, Name and Salary
fields from the CUSTOMERS table, where the salary is greater than 2000 −
SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >
2000;
WHERE Clause with AND and OR Conjunctive Operators

The SQL AND & OR operators are used to combine multiple conditions to
narrow data in an SQL statement
The basic syntax of the AND operator with a WHERE clause is as follows −
SELECT column1, column2, column FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
INPUT
QUERY OUTPUT
WHERE Clause with AND and OR Conjunctive Operators

The OR operator is used to combine multiple conditions in an SQL


statement's WHERE clause.
Syntax
SELECT column1, column2, column FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
You can combine N number of conditions using the OR operator.
Like Clause in SQL
The SQL LIKE clause is used to compare a value to similar values using
wildcard operators.
There are two wildcards used in conjunction with the LIKE operator.
1. The percent sign (%): The percent sign represents zero, one or
multiple characters.
2. The underscore (_): The underscore represents a single number or
character.
These symbols can be used in combinations.
Syntax: SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Like Clause in SQL
Like Clause in SQL
The SQL LIKE clause is used to compare a value to similar values using wildcard
operators.
TOP, LIMIT or ROWNUM Clause in SQL
The SQL TOP clause is used to fetch a TOP N number or X percent
records from a table.
Note − All the databases do not support the TOP clause. For example
MySQL supports the LIMIT clause to fetch limited number of records while
Oracle uses the ROWNUM command to fetch a limited number of records.
Syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE [condition]
TOP, LIMIT or ROWNUM Clause in SQL
The SQL TOP clause is used to fetch a TOP N number or X percent
records from a table.
TOP, LIMIT or ROWNUM Clause in SQL
 If you are using MySQL server, then here is an equivalent example −
SELECT * FROM CUSTOMERS
LIMIT 3;
 If you are using an Oracle server, then the following code block has an
equivalent example.
SELECT * FROM CUSTOMERS
WHERE ROWNUM <= 3;
ORDER BY Clause in SQL
The SQL ORDER BY clause is used to sort the data in ascending or
descending order, based on one or more columns. Some databases sort the
query results in an ascending order by default.
Syntax:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure
whatever column you are using to sort that column should be in the
column-list.
ORDER BY Clause in SQL: Example 1

The following code block has an example, which would sort the result in an
ascending order by the NAME and the SALARY −
SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY;
ORDER BY Clause in SQL: Example 2

The following code block has an example, which would sort the result in the descending order
by NAME.
SELECT * FROM CUSTOMERS ORDER BY NAME DESC;
IN Operator in SQL
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Syntax:
1. SELECT column_name(s) FROM table_name WHERE column_name IN
(value1, value2, ...);
2. SELECT column_name(s) FROM table_name WHERE column_name IN
(SELECT STATEMENT);
Example:
3. SELECT * FROM Customers WHERE Country IN ('Germany', 'France',
'UK');
4. SELECT * FROM Customers WHERE Country IN (SELECT Country FROM
Suppliers);
BETWEEN Operator in SQL
The BETWEEN operator selects values within a given range. The values can
be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Syntax:
SELECT column_name(s) FROM table_name WHERE column_name
BETWEEN value1 AND value2;
Example:
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
Aggregate functions in SQL
An aggregate function is a function that performs a calculation on a set
of values, and returns a single value.

Aggregate functions are often used with the GROUP BY clause of


the SELECT statement.

The GROUP BY clause splits the result-set into groups of values and the
aggregate function can be used to return a single value for each group.

The most commonly used SQL aggregate functions are:


1. MIN() - returns the smallest value within the selected column
2. MAX() - returns the largest value within the selected column
3. COUNT() - returns the number of rows in a set
4. SUM() - returns the total sum of a numerical column
5. AVG() - returns the average value of a numerical column

Aggregate functions ignore null values (except for COUNT()).


Aggregate functions in SQL
MIN(): The MIN() function returns the smallest value of the selected
column.
Syntax: SELECT MIN(column_name) FROM table_name WHERE condition;
Example: SELECT MIN(Price) AS SmallestPrice FROM Products;

MAX(): The MAX() function returns the largest value of the selected
column.
Syntax: SELECT MAX(column_name) FROM table_name WHERE condition;
Example: SELECT MAX(Price) AS LargestPrice FROM Products;

COUNT(): The COUNT() function returns the number of rows that matches
a specified criterion.
Syntax: SELECT COUNT(column_name) FROM table_name WHERE
condition;
Example: SELECT COUNT(ProductID) FROM Products;
Aggregate functions in SQL
AVG(): The AVG() function returns the average value of a numeric column.
Syntax: SELECT AVG(column_name) FROM table_name WHERE condition;
Example: SELECT AVG(Price) FROM Products;

SUM(): The SUM() function returns the total sum of a numeric column.
Syntax: SELECT SUM(column_name) FROM table_name WHERE condition;
Example: SELECT SUM(Quantity) FROM OrderDetails;
GROUP BY Clause in SQL
 The SQL GROUP BY clause is used in collaboration with the SELECT
statement to arrange identical data into groups.
 The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".
 The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by
one or more columns.
 This GROUP BY clause follows the WHERE clause in a SELECT statement
and precedes the ORDER BY clause.
SYNTAX:
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the number of employee in each department.


SELECT Dept_ID, COUNT(*) Dept_ID COUNT(*)
FROM Emp 500 3
GROUP BY Dept_id; 501 2
502 2
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the number of employee in each department,


sorted low to high
Dept_ID COUNT(*)
SELECT Dept_ID, COUNT(*)
501 2
FROM Emp
502 2
GROUP BY Dept_id 500 3
ORDER BY COUNT(*);
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the sum of salaries of employee in each


department.
Dept_ID SumSalary
SELECT Dept_ID, SUM(Salary) AS ‘SumSalary’
500 5500.00
FROM Emp 501 15000.00
GROUP BY Dept_id; 502 14500.00
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the average of salaries of employee in each


department.
Dept_ID AVG(Salary
SELECT Dept_ID, ROUND(AVG(Salary)) )
FROM Emp 500 1833

GROUP BY Dept_id; 501 7500


502 7250
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the minimum salary and maximum salary of


employee from each department.
Dept_I
SELECT Dept_ID, MIN(Salary), MAX(Salary) MIN(Salar MAX(Salary
D y) )
FROM Emp 500 1500.00 2000.00
GROUP BY Dept_id; 501 6500.00 8500.00
502 4500.00 10000.00
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the number of employee in each department


location wise. Dept_I Address COUNT(*)
SELECT Dept_ID, Adress, COUNT(*) D
500 Delhi 1
FROM Emp
500 Pune 2
GROUP BY Dept_id, Address;
501 Mumbai 2
502 Bilaspur 1
502 Patna 1
HAVING Clause in SQL
 The HAVING clause is used to apply a filter on the result of GROUP BY
based on the specified condition.
 The HAVING clause places the condition in the groups defined by the
GROUP BY clause in the SELECT statement.
 This clause is used in SQL because we cannot use the WHERE clause
with the SQL aggregate functions. Both WHERE and HAVING clauses are
used for filtering the records in SQL queries.
SYNTAX:
SELECT column_name(s), aggregate_function (column_Name)
FROM table_name
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
HAVING Clause in SQL
Consider the given table named as “Emp”

Write a query to display departments where the number of


employee is greater than 2.
Dept_ID COUNT(*)
SELECT Dept_ID, COUNT(*)
500 3
FROM Emp
GROUP BY Dept_id
HAVING COUNT(*)>2;
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the department for which the sum of salaries
of employees is more than 10000.
Dept_ID SumSalary
SELECT Dept_ID, SUM(Salary)
501 15000.00
FROM Emp 502 14500.00
GROUP BY Dept_id
HAVING SUM(Salary)>10000;
GROUP BY Clause in SQL
Consider the given table named as “Emp”

Write a query to find the sum of salaries of employee that lives at


same location.
Address SUM(Salary
SELECT Address, SUM(Salary) )
FROM Emp Mumbai 15000.00

GROUP BY Address Pune 3500.00

HAVING COUNT(Address)>=2;
HAVING Clause V/S WHERE Clause in SQL
HAVING WHERE

1. The HAVING clause is used in database systems to 1. The WHERE clause is used in database systems
fetch the data/values from the groups according to the to fetch the data/values from the tables according
given condition. to the given condition.
2. The HAVING clause is always executed with the 2. The WHERE clause can be executed without the
GROUP BY clause. GROUP BY clause.

3. The HAVING clause can include SQL aggregate 3. We cannot use the SQL aggregate function with
functions in a query or statement. WHERE clause in statements.

4. We can only use SELECT statement with HAVING 4. Whereas, we can easily use WHERE clause with
clause for filtering the records. UPDATE, DELETE, and SELECT statements.
5. The HAVING clause is used in SQL queries after the 5. The WHERE clause is always used before the
GROUP BY clause. GROUP BY clause in SQL queries.

6. We can implements this SQL clause in column 6. We can implements this SQL clause in row
operations. operations.

7. It is a post-filter. 7. It is a pre-filter.

8. It is used to filter groups. 8. It is used to filter the single record of the table.
JOINS in SQL
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.

Different types of Joins:


1. (INNER) JOIN: Returns records that have matching values in both tables
2. LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
3. RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
4. FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
INNER JOIN in SQL
The INNER JOIN keyword selects records that have matching values in both
tables.
Syntax: SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example: SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID =

Customers.CustomerID;
JOINS in SQL
Table 1: Order

Table 2: Customer

Example: SELECT Orders.OrderID, Customers.CustomerName


FROM Orders INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;
LEFT(OUTER) JOIN in SQL
The LEFT JOIN keyword returns all records from the left table (table1), and
the matching records from the right table (table2). The result is 0 records
from the right side, if there is no match.
Syntax: SELECT column_name(s)
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example: SELECT Customers.CustomerName, Orders.OrderID
FROM Customers LEFT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Table 1: Order
Table 2: Customer
RIGHT(OUTER) JOIN in SQL
The RIGHT JOIN keyword returns all records from the right table (table2),
and the matching records from the left table (table1). The result is 0
records from the left side, if there is no match.
Syntax: SELECT column_name(s)
FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example: SELECT Orders.OrderID, Employees.LastName,
Employees.FirstName
FROM Orders RIGHT JOIN Employees
ON Orders.CustomerID = Employees.CustomerID
ORDER BY Orders.OrderID;
Table 1: Order
Table 2: Customer
FULL(OUTER) JOIN in SQL
The FULL OUTER JOIN keyword returns all records when there is a match in
left (table1) or right (table2) table records.
Syntax: SELECT column_name(s)
FROM table1 FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
Example: SELECT Customers.CustomerName, Orders.OrderID
FROM Customers FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Table 1: Order
Table 2: Customer
UNION in SQL
The UNION operator is used to combine the result-set of two or more
SELECT statements.
 Every SELECT statement within UNION must have the same number of
columns
 The columns must also have similar data types
 The columns in every SELECT statement must also be in the same order.
The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL.
Syntax: SELECT column_name(s) FROM table1 UNION SELECT

column_name(s) FROM table2;


SELECT column_name(s) FROM table1 UNION ALL
SELECT
column_name(s) FROM table2;
Example: SELECT City FROM Customers UNION SELECT City FROM

You might also like