SQL Commands

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

SQL

SQL is a language to operate databases; it includes database creation,


deletion, fetching rows, modifying rows, etc. SQL is an ANSI (American
National Standards Institute) standard language, but there are many
different versions of the SQL language.

What is SQL?
SQL is Structured Query Language, which is a computer language for
storing, manipulating and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the
Relational Database Management Systems (RDMS) like MySQL, MS Access,
Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their
standard database language.

Why SQL?
SQL is widely popular because it offers the following advantages −
 Allows users to access data in the relational database management
systems.
 Allows users to describe the data.
 Allows users to define the data in a database and manipulate that
data.
 Allows to embed within other languages using SQL modules, libraries
& pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a
database.
 Allows users to set permissions on tables, procedures and views.

A Brief History of SQL


 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of
relational databases. He described a relational model for databases.
 1974 − Structured Query Language appeared.
 1978 − IBM worked to develop Codd's ideas and released a product
named System/R.
 1986 − IBM developed the first prototype of relational database and
standardized by ANSI. The first relational database was released by
Relational Software which later came to be known as Oracle.
SQL Process
When you are executing an SQL command for any RDBMS, the system
determines the best way to carry out your request and SQL engine figures
out how to interpret the task.
There are various components included in this process.
These components are −

 Query Dispatcher
 Optimization Engines
 Classic Query Engine
 SQL Query Engine, etc.
A classic query engine handles all the non-SQL queries, but a SQL query
engine won't handle logical files.
Following is a simple diagram showing the SQL Architecture −

DDL Commands & Syntax

Data Definition Language(DDL) is a subset of SQL and a part


of DBMS(Database Management System). DDL consist of commands like
CREATE, ALTER, TRUNCATE and DROP. These commands are used to
create or modify the tables in SQL.
DDLCommands:
In this section, We will cover the following DDL commands as follows.
1. Create
2. Alter
3. truncate
4. drop
Let‟s discuss it one by one.
Command-1:
CREATE:
This command is used to create a new table in SQL. The user has to give
information like table name, column names, and their datatypes.

Syntax –
CREATE TABLE table_name
(
column_1 datatype,
column_2 datatype,
column_3 datatype,
....
);
Example –
We need to create a table for storing Student information of a particular
College. Create syntax would be as below.
CREATE TABLE Student_info
(
College_Id number(2),
College_name varchar(30),
Branch varchar(10)
);
Command-2:
ALTER:
This command is used to add, delete or change columns in the existing
table. The user needs to know the existing table name and can do add,
delete or modify tasks easily.
Syntax–
Syntax to add a column to an existing table.
ALTER TABLE table_name
ADD column_name datatype;
Example–
In our Student_info table, we want to add a new column for CGPA. The
syntax would be as below as follows.
ALTER TABLE Student_info
ADD CGPA number;
Command-3:
TRUNCATE:
This command is used to remove all rows from the table, but the structure
of the table still exists.
Syntax–
Syntax to remove an existing table.
TRUNCATE TABLE table_name;
Example–
The College Authority wants to remove the details of all students for new
batches but wants to keep the table structure. The command they can use
is as follows.
TRUNCATE TABLE Student_info;
Command-4:
DROP:
This command is used to remove an existing table along with its structure
from the Database.
Syntax–
Syntax to drop an existing table.
DROP TABLE table_name
Example–
If the College Authority wants to change their Database by deleting the
Student_info Table.
DROP TABLE Student_info;
DML commands in DBMS

The structured query language (SQL) commands deal with the manipulation
of data present in the database that belongs to the DML or Data
Manipulation Language. This includes most of the SQL statements.
The examples of DML in the Database Management System (DBMS) are as
follows −

 SELECT − Retrieve data from the database.

 INSERT − Insert data into a table.

 UPDATE − Update existing data within a table.

 DELETE − Delete records from a database table.

Syntax for DML Commands


The syntax for the DML commands are as follows −

INSERT
Insert command is used to insert data into a table.

The syntax for insert command is as follows −

Syntax

Insert into <table_name> (column list) values (column values);

For example, if we want to insert multiple rows to the Employee table, we


can use the following command −

Example

Insert into Employee(Emp_id, Emp_name) values (001, “ bhanu”);


Insert into Employee(Emp_id, Emp_name) values (002, “ hari”);
Insert into Employee(Emp_id, Emp_name) values (003, “ bob”);
SELECT
Select command is used to retrieve data from the database.

The syntax for the select command is as follows −

Syntax

SELECT * from <table_name>;

For example, if we want to select all rows from the Employee database, we
can use the following command −

Example

SELECT * from Employee;


DELETE
Delete command is used to delete records from a database table.
The syntax for the delete command is as follows -

Syntax

Delete from <table_name>WHERE condition;

For example, if we want to delete an entire row of employee id 002, we can


use the following command −

Example

DELETE from Employee WHERE Emp_id=002;


UPDATE
Update command is used to update existing data within a table.

The syntax for the update command is as follows -

Syntax

UPDATE <table_name> SET column_number =value_number WHERE


condition;

For example, if we want to update the name of the employee having the
employee id 001, we can use the command given below −

Example

UPDATE Employee SET Emp_name= Ram WHERE Emp_id= 001;


DCL
DCL stands for Data Control Language in Structured Query Language
(SQL). As the name suggests these commands are used to control privilege
in the database. The privileges (Right to access the data) are required for
performing all the database operations like creating tables, views, or
sequences.
DCL command is a statement that is used to perform the work related to the
rights, permissions, and other control of the database system.

There are two types of Privileges in database:


 System Privilege
 Object Privilege
Need Of DCL commands
 Unauthorized access to the data should be prevented in order to achieve
security in our database
 DCL commands maintain the database effectively than anyone else other
than database administrator is not allowed to access the data without
permission.
 These commands provide flexibility to the data administrator to set and
remove database permissions in granular fashion.
Commands in DCL
The two most important DCL commands are:
 GRANT
 REVOKE
GRANT
This command is used to grant permission to the user to perform a
particular operation on a particular object. If you are a database
administrator and you want to restrict user accessibility such as one who
only views the data or may only update the data. You can give the privilege
permission to the users according to your wish.

Syntax:
GRANT privilege_list
ON Object_name
TO user_name;
REVOKE
This command is used to take permission/access back from the user. If you
want to return permission from the database that you have granted to the
users at that time you need to run REVOKE command.
Syntax:
REVOKE privilege_list
ON object_name
FROM user_name;
Following commands are granted to the user as a Privilege List:
 EXECUTE
 UPDATE
 SELECT
 DELETE
 ALTER
 ALL
Advantages Of DCL commands
 It allows restricting the user from accessing data in database.
 It ensures security in database when the data is exposed to multiple
users.
 It is the wholesome responsibility of the data owner or data administrator
to maintain the authority of grant and revoke privileges to the users
preventing any threat to data.
 It prevents other users to make changes in database who have no access
to Database
SQL Transaction Control Language (TCL)
 TCL stands for Transaction Control Language.
 This command is used to manage the changes made by DML statements.
 TCL allows the statements to be grouped together into logical transactions.
TCL commands are as follows:
1. COMMIT
2. SAVEPOINT
3. ROLLBACK
4. SET TRANSACTION

1. COMMIT COMMAND

 COMMIT command saves all the work done.


 It ends the current transaction and makes permanent changes during the
transaction.
Syntax:
commit;

2. SAVEPOINT COMMAND

 SAVEPOINT command is used for saving all the current point in the
processing of a transaction.
 It marks and saves the current point in the processing of a transaction.

Syntax:
SAVEPOINT <savepoint_name>

Example:
SAVEPOINT no_update;

 It is used to temporarily save a transaction, so that you can rollback to that


point whenever necessary.

3. ROLLBACK COMMAND

 ROLLBACK command restores database to original since the last COMMIT.


 It is used to restores the database to last committed state.
Syntax:
ROLLBACK TO SAVEPOINT <savepoint_name>;

Example:
ROLLBACK TO SAVEPOINT no_update;

4. SET TRANSACTION

 SET TRANSACTION is used for placing a name on a transaction.

Syntax:
SET TRANSACTION [Read Write | Read Only];

Difference between ROLLBACK and COMMIT commands.

ROLLBACK COMMIT

ROLLBACK command is The COMMIT command is used to


used to undo the changes save the modifications done to the
made by the DML database values by the DML
commands. commands.

It rollbacks all the changes of It will make all the changes


the current transaction. permanent that cannot be rolled
back.

Syntax: Syntax:
DELETE FROM table_name COMMIT;
ROLLBACK

SQL | Functions (Aggregate and Scalar Functions)


For doing operations on data sql has many built-in functions, they are
categorised in two categories and further sub-categorised in different seven
functions under each category. The categories are:

1. Aggregate functions:
These functions are used to do operations from the values of the column
and a single value is returned.
1. AVG()
2. COUNT()
3. FIRST()
4. LAST()
5. MAX()
6. MIN()
7. SUM()
2. Scalar functions:
These functions are based on user input, these too returns single value.
1. UCASE()
2. LCASE()
3. MID()
4. LEN()
5. ROUND()
6. NOW()
7. FORMAT()

Students-Table

Aggregate Functions
 AVG(): It returns average value after calculating from values in a numeric
column.
Syntax:
SELECT AVG(column_name) FROM table_name;
 Queries:
1. Computing average marks of students.
SELECT AVG(MARKS) AS AvgMarks FROM Students;
1. Output:

AvgMarks

80

1. Computing average age of students.


SELECT AVG(AGE) AS AvgAge FROM Students;
1. Output:

AvgAge

19.4

 COUNT(): It is used to count the number of rows returned in a SELECT


statement. It can‟t be used in MS ACCESS.
Syntax:
SELECT COUNT(column_name) FROM table_name;
 Queries:
1. Computing total number of students.
SELECT COUNT(*) AS NumStudents FROM Students;
1. Output:

NumStudents

1. Computing number of students with unique/distinct age.


SELECT COUNT(DISTINCT AGE) AS NumStudents FROM Students;
1. Output:

NumStudents

 FIRST(): The FIRST() function returns the first value of the selected
column.
Syntax:
SELECT FIRST(column_name) FROM table_name;
 Queries:
1. Fetching marks of first student from the Students table.
SELECT FIRST(MARKS) AS MarksFirst FROM Students;
1. Output:

MarksFirst

90

1. Fetching age of first student from the Students table.


SELECT FIRST(AGE) AS AgeFirst FROM Students;
1. Output:

AgeFirst

19

 LAST(): The LAST() function returns the last value of the selected
column. It can be used only in MS ACCESS.
Syntax:
SELECT LAST(column_name) FROM table_name;
 Queries:
1. Fetching marks of last student from the Students table.
SELECT LAST(MARKS) AS MarksLast FROM Students;
1. Output:

MarksLast

82

1. Fetching age of last student from the Students table.


SELECT LAST(AGE) AS AgeLast FROM Students;
1. Output:

AgeLast

18

 MAX(): The MAX() function returns the maximum value of the selected
column.
Syntax:
SELECT MAX(column_name) FROM table_name;
 Queries:
1. Fetching maximum marks among students from the Students table.
SELECT MAX(MARKS) AS MaxMarks FROM Students;
1. Output:

MaxMarks

95

1. Fetching max age among students from the Students table.


SELECT MAX(AGE) AS MaxAge FROM Students;
1. Output:

MaxAge

21

 MIN(): The MIN() function returns the minimum value of the selected
column.
Syntax:
SELECT MIN(column_name) FROM table_name;
 Queries:
1. Fetching minimum marks among students from the Students table.
SELECT MIN(MARKS) AS MinMarks FROM Students;
1. Output:

MinMarks

50

1. Fetching minimum age among students from the Students table.


SELECT MIN(AGE) AS MinAge FROM Students;
1. Output:

MinAge

18

 SUM(): The SUM() function returns the sum of all the values of the
selected column.
Syntax:
SELECT SUM(column_name) FROM table_name;
 Queries:
1. Fetching summation of total marks among students from the
Students table.
SELECT SUM(MARKS) AS TotalMarks FROM Students;
1. Output:

TotalMarks

400

1. Fetching summation of total age among students from the Students


table.

SELECT SUM(AGE) AS TotalAge FROM Students;


1. Output:

TotalAge

97

Scalar Functions
 UCASE(): It converts the value of a field to uppercase.
Syntax:
SELECT UCASE(column_name) FROM table_name;
 Queries:
1. Converting names of students from the table Students to uppercase.
SELECT UCASE(NAME) FROM Students;
1. Output:

NAME

HARSH

SURESH

PRATIK

DHANRAJ

RAM

 LCASE(): It converts the value of a field to lowercase.


Syntax:
SELECT LCASE(column_name) FROM table_name;
 Queries:
1. Converting names of students from the table Students to lowercase.
SELECT LCASE(NAME) FROM Students;
1. Output:

NAME

harsh

suresh

pratik

dhanraj

ram

 MID(): The MID() function extracts texts from the text field.
Syntax:
SELECT MID(column_name,start,length) AS some_name FROM table_name;

specifying length is optional here, and start signifies start position ( starting
from 1 )
 Queries:
1. Fetching first four characters of names of students from the Students
table.
SELECT MID(NAME,1,4) FROM Students;
1. Output:

NAME

HARS

SURE

PRAT

DHAN
RAM

 LEN(): The LEN() function returns the length of the value in a text field.
Syntax:
SELECT LENGTH(column_name) FROM table_name;
 Queries:
1. Fetching length of names of students from Students table.
SELECT LENGTH(NAME) FROM Students;
1. Output:

NAME

 ROUND(): The ROUND() function is used to round a numeric field to the


number of decimals specified.NOTE: Many database systems have
adopted the IEEE 754 standard for arithmetic operations, which says
that when any numeric .5 is rounded it results to the nearest even
integer i.e, 5.5 and 6.5 both gets rounded off to 6.
Syntax:
SELECT ROUND(column_name,decimals) FROM table_name;

decimals- number of decimals to be fetched.


 Queries:
1. Fetching maximum marks among students from the Students table.
SELECT ROUND(MARKS,0) FROM table_name;
1. Output:

MARKS
90

50

80

95

85

 NOW(): The NOW() function returns the current system date and time.
Syntax:
SELECT NOW() FROM table_name;
 Queries:
1. Fetching current system time.
SELECT NAME, NOW() AS DateTime FROM Students;
1. Output:

NAME DateTime

HARSH 1/13/2017 1:30:11 PM

SURESH 1/13/2017 1:30:11 PM

PRATIK 1/13/2017 1:30:11 PM

DHANRAJ 1/13/2017 1:30:11 PM

RAM 1/13/2017 1:30:11 PM

 FORMAT(): The FORMAT() function is used to format how a field is to be


displayed.
Syntax:
SELECT FORMAT(column_name,format) FROM table_name;
 Queries:
1. Formatting current date as „YYYY-MM-DD‟.

SELECT NAME, FORMAT(Now(),'YYYY-MM-DD') AS Date FROM Students;


 Output:
NAME Date

HARSH 2017-01-13

SURESH 2017-01-13

PRATIK 2017-01-13

DHANRAJ 2017-01-13

RAM 2017-01-13

You might also like