SQL Commands
SQL Commands
SQL
Last updated on Jun 19,2023288.2K Views
Share
Sahiti Kappagantula
Bookmark
The topics covered in this blog are mainly divided into 4 categories:
Apart from the above commands, the following topics will also be covered
in this article:
Comments in SQL
Different Types Of Keys In Database
Constraints Used In Database
Nested Queries
Joins
Set Operations
Dates & Auto Increment
Views
Stored Procedures
Triggers
Emergency
EmployeeI EmployeeNa PhoneNumb Countr
ContactNa Address City
D me er y
me
Oberoi
01 Shanaya Abhinay 9898765612 Mumbai India
Street 23
Marathal
02 Anay Soumya 9432156783 li House Delhi India
No 23
Queens Bangalor
03 Preeti Rohan 9764234519 India
Road 45 e
Brigade
Hyderaba
04 Vihaan Akriti 9966442211 Road India
d
Block 4
Mayo
05 Manasa Shourya 9543176246 Kolkata India
Road 23
So, let’s get started now!
Comments in SQL
There are two ways in which you can comment in SQL, i.e. either the Single-
Line Comments or the Multi-Line Comments.
Single-Line Comments
The single line comment starts with two hyphens (–). So, any text mentioned
after (–), till the end of a single line will be ignored by the compiler.
Example:
1--Select all:
2SELECT * FROM Employee_Info;
Multi-Line Comments
The Multi-line comments start with /* and end with */. So, any text
mentioned between /* and */ will be ignored by the compiler.
Example:
CREATE
DROP
TRUNCATE
ALTER
BACKUP DATABASE
CREATE
Syntax
Syntax
ColumnN datatype
);
Example
1
2CREATE TABLE Employee_Info
(
3
EmployeeID int,
4EmployeeName varchar(255),
5Emergency ContactName varchar(255),
6PhoneNumber int,
7Address varchar(255),
8City varchar(255),
9Country varchar(255)
10);
You can also create a table using another table. Refer the below sytax and
example:
Syntax
This statement is used to drop an existing database. When you use this
statement, complete information present in the database will be lost.
Syntax
This statement is used to drop an existing table. When you use this
statement, complete information present in the table will be lost.
Syntax
This command is used to delete the information present in the table but
does not delete the table. So, once you use this command, your information
will be lost, but not the table.
Syntax
You can use the ALTER TABLE statement with ADD/DROP Column command
according to your need. If you wish to add a column, then you will use the
ADD command, and if you wish to delete a column, then you will use the
DROP COLUMN command.
Syntax
Syntax
Syntax
Syntax
NOT NULL
UNIQUE
CHECK
DEFAULT
INDEX
NOT NULL
Example
1
2--NOT NULL on Create Table
3
4CREATE TABLE Employee_Info
5(
6EmployeeID int NOT NULL,
7EmployeeName varchar(255) NOT NULL,
Emergency ContactName varchar(255),
8
PhoneNumber int NOT NULL,
9Address varchar(255),
10City varchar(255),
11Country varchar(255)
12);
13
14--NOT NULL on ALTER TABLE
15
16ALTER TABLE Employee_Info
17MODIFY PhoneNumber int NOT NULL;
UNIQUE
This constraint ensures that all the values in a column are unique.
Example
This constraint ensures that all the values in a column satisfy a specific
condition.
Example
Example
1
2--DEFAULT Constraint on CREATE TABLE
3
4CREATE TABLE Employee_Info
5(
6EmployeeID int NOT NULL,
7EmployeeName varchar(255),
8Emergency ContactName varchar(255),
9PhoneNumber int,
10Address varchar(255),
11City varchar(255),
Country varchar(255) DEFAULT 'India'
12
);
13
14--DEFAULT Constraint on ALTER TABLE
15
16ALTER TABLE Employee_Info
17ADD CONSTRAINT defau_Country
18DEFAULT 'India' FOR Country;
19
20--To drop the Default Constraint
21
22ALTER TABLE Employee_Info
23ALTER COLUMN Country DROP DEFAULT;
INDEX
This constraint is used to create indexes in the table, through which you can
create and retrieve data from the database very quickly.
Syntax
Explore Curriculum
USE
INSERT INTO
UPDATE
DELETE
SELECT
Operators
Aggregate Functions
NULL Functions
Aliases & Case Statement
USE
The USE statement is used to select the database on which you want to
perform operations.
Syntax
USE DatabaseName;
Example
1USE Employee;
INSERT INTO
Syntax
--If you don't want to mention the column names then use the
below syntax
This statement is used to modify the records already present in the table.
Syntax
UPDATE TableName
SET Column1 = Value1, Column2 = Value2, ...
WHERE Condition;
Example
1UPDATE Employee_Info
2SET EmployeeName = 'Aahana', City= 'Ahmedabad'
3WHERE EmployeeID = 1;
DELETE
Syntax
This statement is used to select data from a database and the data returned
is stored in a result table, called the result-set.
Syntax
DISTINCT
ORDER BY
GROUP BY
HAVING Clause
INTO
The ‘SELECT DISTINCT’ Statement
Syntax
The ‘ORDER BY’ statement is used to sort the required results in ascending
or descending order. The results are sorted in ascending order by default.
Yet, if you wish to get the required results in descending order, you have to
use the DESC keyword.
Syntax
1
2-- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName:
3SELECT * FROM Employee_Info
4ORDER BY EmergencyContactName;
5
-- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName in De
6
SELECT * FROM Employee_Info
7ORDER BY EmergencyContactName DESC;
8
9-- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName and E
10SELECT * FROM Employee_Info
11ORDER BY EmergencyContactName, EmployeeName;
12
13/* Select all employees from the 'Employee_Info' table sorted by EmergencyContactName in De
14SELECT * FROM Employee_Info
15ORDER BY EmergencyContactName ASC, EmployeeName DESC;
Find out our MS SQL Course in Top Cities
India India
SQL Training in Bangalore SQL Course in Pune
SQL Training in Chennai SQL Course in Mumbai
SQL Training in
SQL Course in Kolkata
hyderabad
The ‘GROUP BY’ Statement
This ‘GROUP BY’ statement is used with the aggregate functions to group
the result-set by one or more columns.
Syntax
The ‘HAVING’ clause is used in SQL because the WHERE keyword cannot be
used everywhere.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
HAVING Condition
ORDER BY ColumnName(s);
Example
/* To list the number of employees in each city. The employees should be sorted high to low
1employees:*/
2
3SELECT COUNT(EmployeeID), City
4FROM Employee_Info
5GROUP BY City
6HAVING COUNT(EmployeeID) > 2
7ORDER BY COUNT(EmployeeID) DESC;
The ‘SELECT INTO’ Statement
The ‘SELECT INTO’ statement is used to copy data from one table to
another.
Syntax
SELECT *
INTO NewTable [IN ExternalDB]
FROM OldTable
WHERE Condition;
Example
1
-- To create a backup of database 'Employee'
2
SELECT * INTO EmployeeBackup
3FROM Employee;
4
5--To select only few columns from Employee
6SELECT EmployeeName, PhoneNumber INTO EmployeeContactDetails
7FROM Employee;
8
9SELECT * INTO BlrEmployee
10FROM Employee
11WHERE City = 'Bangalore';
Now, as I mentioned before, let us move onto our next section in this article
on SQL Commands, i.e. the Operators.
Operators in SQL
Arithmetic Operators
Operator Description
% Modulous [A % B]
/ Division [A / B]
* Multiplication [A * B]
– Subtraction [A – B]
+ Addition [A + B]
Bitwise Operators
Operator Description
^ Bitwise Exclusive OR (XOR) [A ^ B]
| Bitwise OR [A | B]
& Bitwise AND [A & B]
Comparison Operators
Operator Description
<> Not Equal to [A < > B]
<= Less than or equal to [A <= B]
>= Greater than or equal to [A >= B]
< Less than [A < B]
> Greater than [A > B]
= Equal to [A = B]
Compound Operators
Operator Description
|*= Bitwise OR equals [A |*= B]
^-= Bitwise Exclusive equals [A ^-= B]
&= Bitwise AND equals [A &= B]
%= Modulo equals [A %= B]
/= Divide equals [A /= B]
*= Multiply equals [A*= B]
-= Subtract equals [A-= B]
+= Add equals [A+= B]
Logical Operators
AND
OR
NOT
BETWEEN
LIKE
IN
EXISTS
ALL
ANY
AND Operator
This operator is used to filter records that rely on more than one condition.
This operator displays the records, which satisfy all the conditions
separated by AND, and give the output TRUE.
Syntax
This operator displays all those records which satisfy any of the conditions
separated by OR and give the output TRUE.
Syntax
The NOT operator is used, when you want to display the records which do
not satisfy a condition.
Syntax
The BETWEEN operator is used, when you want to select values within a
given range. Since this is an inclusive operator, both the starting and ending
values are considered.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName BETWEEN Value1 AND Value2;
Example
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName LIKE pattern;
Refer to the following table for the various patterns that you can mention
with the LIKE operator.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName IN (Value1,Value2...);
Example
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE EXISTS
(SELECT ColumnName FROM TableName WHERE condition);
Example
1SELECT EmergencyContactName
2FROM Employee_Info
3WHERE EXISTS (SELECT EmergencyContactName FROM Employee_Info WHERE EmployeeId = 05 AND City
ALL Operator
The ALL operator is used with a WHERE or HAVING clause and returns TRUE
if all of the subquery values meet the condition.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName operator ALL
(SELECT ColumnName FROM TableName WHERE condition);
Example
1SELECT EmployeeName
2FROM Employee_Info
3WHERE EmployeeID = ALL (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad');
ANY Operator
Similar to the ALL operator, the ANY operator is also used with a WHERE
or HAVING clause and returns true if any of the subquery values meet the
condition.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName operator ANY
(SELECT ColumnName FROM TableName WHERE condition);
Example
1SELECT EmployeeName
2FROM Employee_Info
3WHERE EmployeeID = ANY (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad' OR Cit
Next, in this article on SQL Commands, let us look into the various
Aggregate Functions provided in SQL.
Aggregate Functions
MIN()
MAX()
COUNT()
SUM()
AVG()
MIN() Function
The MIN function returns the smallest value of the selected column in a
table.
Syntax
SELECT MIN(ColumnName)
FROM TableName
WHERE Condition;
Example
The MAX function returns the largest value of the selected column in a
table.
Databases Training
Next
Syntax
SELECT MAX(ColumnName)
FROM TableName
WHERE Condition;
Example
Syntax
SELECT COUNT(ColumnName)
FROM TableName
WHERE Condition;
Example
1SELECT COUNT(EmployeeID)
2FROM Employee_Info;
SUM() Function
The SUM function returns the total sum of a numeric column that you
choose.
Syntax
SELECT SUM(ColumnName)
FROM TableName
WHERE Condition;
Example
1SELECT SUM(Salary)
2FROM Employee_Salary;
AVG() Function
The AVG function returns the average value of a numeric column that you
choose.
Syntax
SELECT AVG(ColumnName)
FROM TableName
WHERE Condition;
Example
1SELECT AVG(Salary)
2FROM Employee_Salary;
NULL Functions
The NULL functions are those functions which let you return an alternative
value if an expression is NULL. In the SQL Server, the function is ISNULL().
Example
Aliases
Aliases are used to give a column/table a temporary name and only exists
for a duration of the query.
Syntax
SELECT ColumnName(s)
FROM TableName AS AliasName;
Example
This statement goes through all the conditions and returns a value when
the first condition is met. So, if no conditions are TRUE, it returns the value
in the ELSE clause. Also, if no conditions are true and there is no ELSE part,
then it returns NULL.
Syntax
CASE
WHEN Condition1 THEN Result1
WHEN Condition2 THEN Result2
WHEN ConditionN THEN ResultN
ELSE Result
END;
Example
INNER JOIN: This join returns those records which have matching
values in both the tables.
FULL JOIN: This join returns all those records which either have a
match in the left or the right table.
LEFT JOIN: This join returns records from the left table, and also
those records which satisfy the condition from the right table.
RIGHT JOIN: This join returns records from the right table, and also
those records which satisfy the condition from the left table.
Syntax
SELECT ColumnName(s)
FROM Table1
INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
Syntax
SELECT ColumnName(s)
FROM Table1
FULL OUTER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
Syntax
SELECT ColumnName(s)
FROM Table1
LEFT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
Syntax
SELECT ColumnName(s)
FROM Table1
RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
1SELECT Technologies.TechID
2FROM Technologies
3RIGHT JOIN Employee_Info ON Technologies.EmpID = Employee_Info.EmployeeID
4ORDER BY Technologies.TechID;
SQL Commands: Set Operations
There are mainly three set operations:UNION, INTERSECT, EXCEPT. You can
refer to the image below to understand the set operations in SQL.
UNION
Syntax
This clause used to combine two SELECT statements and return the
intersection of the data-sets of both the SELECT statements.
Syntax
INTERSECT
Syntax
SELECT ColumnName
FROM TableName
EXCEPT
SELECT ColumnName
FROM TableName;
Next, in this article, let us look into the date functions and auto-increment
fields.
Dates
The following data types are present in a SQL Server to store a date or a
date/time value in a database.
Example
1<span>/* To define the "EmployeeID" column to be an auto-increment primary key field in the
2
3<span>CREATE TABLE Employee_Info (</span>
4<span>EmployeeID INT IDENTITY(1,1) PRIMARY KEY,</span>
5<span>EmployeeName VARCHAR(255) NOT NULL</span>
6<span>EmergencyContactName VARCHAR(255) NOT NULL,</span>
7<span>);</span>
Now, that you guys know the DML commands, let’s move onto our next
section in this article on SQL Commands i.e. the DCL commands.
GRANT
REVOKE
GRANT
Syntax
GRANT PrivilegeName
ON ObjectName
TO {UserName |PUBLIC |RoleName}
[WITH GRANT OPTION];
where,
Example
Syntax
REVOKE PrivilegeName
ON ObjectName
FROM {UserName |PUBLIC |RoleName}
Example
Syntax
Syntax
Syntax
1EXEC ProcedureName;
SQL Commands: Triggers
Triggers are a set of SQL statements which are stored in the database
catalog. These statements are executed whenever an event associated with
a table occurs. So, a trigger can be invoked either BEFORE or AFTER the
data is changed by INSERT, UPDATE or DELETE statement. Refer to the
image below.
Syntax
COMMIT
ROLLBACK
SAVEPOINT
COMMIT
Syntax
COMMIT;
ROLLBACK
This command is used to restore the database to the last committed state.
Syntax
ROLLBACK;
NOTE: When you use ROLLBACK with SAVEPOINT, then you can directly
jump to a savepoint in an ongoing transaction. Syntax: ROLLBACK TO
SavepointName;
SAVEPOINT
Syntax
SAVEPOINT SAVEPOINTNAME;
Consider the below example to understand the working of transactions in
the database.
EmployeeID EmployeeName
01 Ruhaan
02 Suhana
03 Aayush
04 Rashi
Now, use the below SQL queries to understand the transactions in the
database.
1
2INSERT INTO Employee_Table VALUES(05, 'Avinash');
3COMMIT;
UPDATE Employee_Table SET name = 'Akash' WHERE id = '05';
4
SAVEPOINT S1;
5INSERT INTO Employee_Table VALUES(06, 'Sanjana');
6SAVEPOINT S2;
7INSERT INTO Employee_Table VALUES(07, 'Sanjay');
8SAVEPOINT S3;
9INSERT INTO Employee_Table VALUES(08, 'Veena');
10SAVEPOINT S4;
11SELECT * FROM Employee_Table;
The output to the above set of queries would be as follows:
EmployeeID EmployeeName
01 Ruhaan
02 Suhana
03 Aayush
04 Rashi
05 Akash
06 Sanjana
07 Sanjay
08 Veena
Now, if you rollback to S2 using the below queries, the output is
mentioned in the below table.
1ROLLBACK TO S2;
2SELECT * FROM Employee_Table;
EmployeeID EmployeeName
01 Ruhaan
02 Suhana
03 Aayush
04 Rashi
05 Akash
06 Sanjana
By this, I come to the end of this article on SQL Commands. I hope you
enjoyed reading this article on SQL Commands. We have seen the different
commands that will help you write queries and play around with your
databases. If you wish to learn more about MySQL and get to know this open
source relational database, then check out our MySQL DBA Certification
Training which comes with instructor-led live training and real-life project
experience. This training will help you understand MySQL in depth and help you
achieve mastery over the subject.
Got a question for us? Please mention it in the comments section of ”SQL
Commands” and I will get back to you.