Microsoft SQL Server Certification Course
- 6k Enrolled Learners
- Weekend
- Live Class
In the era where data is being generated in humongous amounts, there is a constant need to handle data in databases. Relational databases are one of the most popular databases, and SQL is the basis of relational databases. Therefore SQL skills are indispensable in most of the job roles. In this article on SQL Commands, I will discuss the top commands and statements that you need to understand in SQL.
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:
In this article on SQL Commands, I am going to consider the below database as an example, to show you how to write commands.
EmployeeID | EmployeeName | Emergency ContactName | PhoneNumber | Address | City | Country |
01 | Shanaya | Abhinay | 9898765612 | Oberoi Street 23 | Mumbai | India |
02 | Anay | Soumya | 9432156783 | Marathalli House No 23 | Delhi | India |
03 | Preeti | Rohan | 9764234519 | Queens Road 45 | Bangalore | India |
04 | Vihaan | Akriti | 9966442211 | Brigade Road Block 4 | Hyderabad | India |
05 | Manasa | Shourya | 9543176246 | Mayo Road 23 | Kolkata | India |
There are two ways in which you can comment in SQL, i.e. either the Single-Line Comments or the Multi-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.
--Select all: SELECT * FROM Employee_Info;
The Multi-line comments start with /* and end with */. So, any text mentioned between /* and */ will be ignored by the compiler.
/*Select all the columns of all the records from the Employee_Info table:*/ SELECT * FROM Students;
This section of the article will give you an insight into the commands through which you can define your database. The commands are as follows:
This statement is used to create a table or a database.
As the name suggests, this statement is used to create a database.
CREATE DATABASE DatabaseName;
CREATE DATABASE Employee;
This statement is used to create a table.
CREATE TABLE TableName ( Column1 datatype, Column2 datatype, Column3 datatype, .... ColumnN datatype );
CREATE TABLE Employee_Info ( EmployeeID int, EmployeeName varchar(255), Emergency ContactName varchar(255), PhoneNumber int, Address varchar(255), City varchar(255), Country varchar(255) );
You can also create a table using another table. Refer the below sytax and example:
CREATE TABLE NewTableName AS SELECT Column1, column2,..., ColumnN FROM ExistingTableName WHERE ....;
CREATE TABLE ExampleTable AS SELECT EmployeeName, PhoneNumber FROM Employee_Info;
This statement is used to drop an existing table or a database.
This statement is used to drop an existing database. When you use this statement, complete information present in the database will be lost.
DROP DATABASE DatabaseName;
DROP DATABASE Employee;
This statement is used to drop an existing table. When you use this statement, complete information present in the table will be lost.
DROP TABLE TableName;
DROP Table Employee_Info;
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.
TRUNCATE TABLE TableName;
TRUNCATE Table Employee_Info;
This command is used to delete, modify or add constraints or columns in an existing table.
This statement is used to add, delete, modify columns in an existing table.
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.
ALTER TABLE TableName ADD ColumnName Datatype; ALTER TABLE TableName DROP COLUMN ColumnName;
--ADD Column BloodGroup: ALTER TABLE Employee_Info ADD BloodGroup varchar(255); --DROP Column BloodGroup: ALTER TABLE Employee_Info DROP COLUMN BloodGroup ;
Discover the secrets of efficient data management through our SQL Online Course.
This statement is used to change the datatype of an existing column in a table.
ALTER TABLE TableName ALTER COLUMN ColumnName Datatype;
--Add a column DOB and change the data type to Date. ALTER TABLE Employee_Info ADD DOB year; ALTER TABLE Employee_Info ALTER DOB date;
This statement is used to create a full backup of an existing database.
BACKUP DATABASE DatabaseName TO DISK = 'filepath';
BACKUP DATABASE Employee TO DISK = 'C:UsersSahitiDesktop';
You can also use a differential back up. This type of back up only backs up the parts of the database, which have changed since the last complete backup of the database.
BACKUP DATABASE DatabaseName TO DISK = 'filepath' WITH DIFFERENTIAL;
BACKUP DATABASE Employee TO DISK = 'C:UsersSahitiDesktop' WITH DIFFERENTIAL;
Now that you know the data definition commands, let me take you through the various types of Keys and Constraints that you need to understand before learning how to manipulate the databases.
There are mainly 7 types of Keys, that can be considered in a database. I am going to consider the below tables to explain to you the various keys.
Constraints are used in a database to specify the rules for data in a table. The following are the different types of constraints:
This constraint ensures that a column cannot have a NULL value.
--NOT NULL on Create Table CREATE TABLE Employee_Info ( EmployeeID int NOT NULL, EmployeeName varchar(255) NOT NULL, Emergency ContactName varchar(255), PhoneNumber int NOT NULL, Address varchar(255), City varchar(255), Country varchar(255) ); --NOT NULL on ALTER TABLE ALTER TABLE Employee_Info MODIFY PhoneNumber int NOT NULL;
This constraint ensures that all the values in a column are unique.
--UNIQUE on Create Table CREATE TABLE Employee_Info ( EmployeeID int NOT NULL UNIQUE, EmployeeName varchar(255) NOT NULL, Emergency ContactName varchar(255), PhoneNumber int NOT NULL, Address varchar(255), City varchar(255), Country varchar(255) ); --UNIQUE on Multiple Columns CREATE TABLE Employee_Info ( EmployeeID int NOT NULL, EmployeeName varchar(255) NOT NULL, Emergency ContactName varchar(255), PhoneNumber int NOT NULL, Address varchar(255), City varchar(255), Country varchar(255), CONSTRAINT UC_Employee_Info UNIQUE(Employee_ID, PhoneNumber) ); --UNIQUE on ALTER TABLE ALTER TABLE Employee_Info ADD UNIQUE (Employee_ID); --To drop a UNIQUE constraint ALTER TABLE Employee_Info DROP CONSTRAINT UC_Employee_Info;
This constraint ensures that all the values in a column satisfy a specific condition.
--CHECK Constraint on CREATE TABLE CREATE TABLE Employee_Info ( EmployeeID int NOT NULL, EmployeeName varchar(255), Emergency ContactName varchar(255), PhoneNumber int, Address varchar(255), City varchar(255), Country varchar(255) CHECK (Country=='India') ); --CHECK Constraint on multiple columns CREATE TABLE Employee_Info ( EmployeeID int NOT NULL, EmployeeName varchar(255), Emergency ContactName varchar(255), PhoneNumber int, Address varchar(255), City varchar(255), Country varchar(255) CHECK (Country = 'India' AND Cite = 'Hyderabad') ); --CHECK Constraint on ALTER TABLE ALTER TABLE Employee_Info ADD CHECK (Country=='India'); --To give a name to the CHECK Constraint ALTER TABLE Employee_Info ADD CONSTRAINT CheckConstraintName CHECK (Country=='India'); --To drop a CHECK Constraint ALTER TABLE Employee_Info DROP CONSTRAINT CheckConstraintName;
This constraint consists of a set of default values for a column when no value is specified.
--DEFAULT Constraint on CREATE TABLE CREATE TABLE Employee_Info ( EmployeeID int NOT NULL, EmployeeName varchar(255), Emergency ContactName varchar(255), PhoneNumber int, Address varchar(255), City varchar(255), Country varchar(255) DEFAULT 'India' ); --DEFAULT Constraint on ALTER TABLE ALTER TABLE Employee_Info ADD CONSTRAINT defau_Country DEFAULT 'India' FOR Country; --To drop the Default Constraint ALTER TABLE Employee_Info ALTER COLUMN Country DROP DEFAULT;
This constraint is used to create indexes in the table, through which you can create and retrieve data from the database very quickly.
--Create an Index where duplicate values are allowed CREATE INDEX IndexName ON TableName (Column1, Column2, ...ColumnN); --Create an Index where duplicate values are not allowed CREATE UNIQUE INDEX IndexName ON TableName (Column1, Column2, ...ColumnN);
CREATE INDEX idex_EmployeeName ON Persons (EmployeeName); --To delete an index in a table DROP INDEX Employee_Info.idex_EmployeeName;
Now, let us look into the next part of this article i.e. DML Commands.
This section of the article will give you an insight into the commands through which you can manipulate the database. The commands are as follows:
Apart from these commands, there are also other manipulative operators/functions such as:
The USE statement is used to select the database on which you want to perform operations.
USE DatabaseName;
USE Employee;
This statement is used to insert new records into the table.
INSERT INTO TableName (Column1, Column2, Column3, ...,ColumnN) VALUES (value1, value2, value3, ...); --If you don't want to mention the column names then use the below syntax INSERT INTO TableName VALUES (Value1, Value2, Value3, ...);
Example
INSERT INTO Employee_Info(EmployeeID, EmployeeName, Emergency ContactName, PhoneNumber, Address, City, Country) VALUES ('06', 'Sanjana','Jagannath', '9921321141', 'Camel Street House No 12', 'Chennai', 'India'); INSERT INTO Employee_Info VALUES ('07', 'Sayantini','Praveen', '9934567654', 'Nice Road 21', 'Pune', 'India');
This statement is used to modify the records already present in the table.
UPDATE TableName SET Column1 = Value1, Column2 = Value2, ... WHERE Condition;
UPDATE Employee_Info SET EmployeeName = 'Aahana', City= 'Ahmedabad' WHERE EmployeeID = 1;
This statement is used to delete the existing records in a table.
DELETE FROM TableName WHERE Condition;
DELETE FROM Employee_Info WHERE EmployeeName='Preeti';
This statement is used to select data from a database and the data returned is stored in a result table, called the result-set.
SELECT Column1, Column2, ...ColumN FROM TableName; --(*) is used to select all from the table SELECT * FROM table_name; -- To select the number of records to return use: SELECT TOP 3 * FROM TableName;
SELECT EmployeeID, EmployeeName FROM Employee_Info; --(*) is used to select all from the table SELECT * FROM Employee_Info; -- To select the number of records to return use: SELECT TOP 3 * FROM Employee_Info;
Apart from just using the SELECT keyword individually, you can use the following keywords with the SELECT statement:
This statement is used to return only different values.
SELECT DISTINCT Column1, Column2, ...ColumnN FROM TableName;
SELECT DISTINCT PhoneNumber FROM Employee_Info;
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.
SELECT Column1, Column2, ...ColumnN FROM TableName ORDER BY Column1, Column2, ... ASC|DESC;
-- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName: SELECT * FROM Employee_Info ORDER BY EmergencyContactName; -- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName in Descending order: SELECT * FROM Employee_Info ORDER BY EmergencyContactName DESC; -- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName and EmployeeName: SELECT * FROM Employee_Info ORDER BY EmergencyContactName, EmployeeName; /* Select all employees from the 'Employee_Info' table sorted by EmergencyContactName in Descending order and EmployeeName in Ascending order: */ SELECT * FROM Employee_Info ORDER 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 hyderabad | SQL Course in Kolkata |
This ‘GROUP BY’ statement is used with the aggregate functions to group the result-set by one or more columns.
SELECT Column1, Column2,..., ColumnN FROM TableName WHERE Condition GROUP BY ColumnName(s) ORDER BY ColumnName(s);
-- To list the number of employees from each city. SELECT COUNT(EmployeeID), City FROM Employee_Info GROUP BY City;
The ‘HAVING’ clause is used in SQL because the WHERE keyword cannot be used everywhere.
SELECT ColumnName(s) FROM TableName WHERE Condition GROUP BY ColumnName(s) HAVING Condition ORDER BY ColumnName(s);
/* To list the number of employees in each city. The employees should be sorted high to low and only those cities must be included who have more than 5 employees:*/ SELECT COUNT(EmployeeID), City FROM Employee_Info GROUP BY City HAVING COUNT(EmployeeID) > 2 ORDER BY COUNT(EmployeeID) DESC;
The ‘SELECT INTO’ statement is used to copy data from one table to another.
SELECT * INTO NewTable [IN ExternalDB] FROM OldTable WHERE Condition;
-- To create a backup of database 'Employee' SELECT * INTO EmployeeBackup FROM Employee; --To select only few columns from Employee SELECT EmployeeName, PhoneNumber INTO EmployeeContactDetails FROM Employee; SELECT * INTO BlrEmployee FROM Employee WHERE City = 'Bangalore';
Now, as I mentioned before, let us move onto our next section in this article on SQL Commands, i.e. the Operators.
The different set of operators available in SQL are as follows:
Let us look into each one of them, one by one.
Operator | Description |
% | Modulous [A % B] |
/ | Division [A / B] |
* | Multiplication [A * B] |
– | Subtraction [A – B] |
+ | Addition [A + B] |
Operator | Description |
^ | Bitwise Exclusive OR (XOR) [A ^ B] |
| | Bitwise OR [A | B] |
& | Bitwise AND [A & B] |
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] |
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] |
The Logical operators present in SQL are as follows:
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.
SELECT Column1, Column2, ..., ColumnN FROM TableName WHERE Condition1 AND Condition2 AND Condition3 ...;
SELECT * FROM Employee_Info WHERE City='Mumbai' AND City='Hyderabad';</pre>
This operator displays all those records which satisfy any of the conditions separated by OR and give the output TRUE.
SELECT Column1, Column2, ..., ColumnN FROM TableName WHERE Condition1 OR Condition2 OR Condition3 ...;
SELECT * FROM Employee_Info WHERE City='Mumbai' OR City='Hyderabad';
The NOT operator is used, when you want to display the records which do not satisfy a condition.
SELECT Column1, Column2, ..., ColumnN FROM TableName WHERE NOT Condition;
SELECT * FROM Employee_Info WHERE NOT City='Mumbai';
SELECT * FROM Employee_Info WHERE NOT Country='India' AND (City='Bangalore' OR City='Hyderabad');
SELECT * FROM Employee_Info WHERE NOT Country='India' AND (City='Bangalore' OR City='Hyderabad');
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.
SELECT ColumnName(s) FROM TableName WHERE ColumnName BETWEEN Value1 AND Value2;
SELECT * FROM Employee_Salary WHERE Salary BETWEEN 40000 AND 50000;
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column of a table. There are mainly two wildcards that are used in conjunction with the LIKE operator:
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.
SELECT * FROM Employee_Info WHERE EmployeeName LIKE 'S%';
This operator is used for multiple OR conditions. This allows you to specify multiple values in a WHERE clause.
SELECT ColumnName(s) FROM TableName WHERE ColumnName IN (Value1,Value2...);
SELECT * FROM Employee_Info WHERE City IN ('Mumbai', 'Bangalore', 'Hyderabad');
The EXISTS operator is used to test if a record exists or not.
SELECT ColumnName(s) FROM TableName WHERE EXISTS (SELECT ColumnName FROM TableName WHERE condition);
SELECT EmergencyContactName FROM Employee_Info WHERE EXISTS (SELECT EmergencyContactName FROM Employee_Info WHERE EmployeeId = 05 AND City = 'Kolkata');
The ALL operator is used with a WHERE or HAVING clause and returns TRUE if all of the subquery values meet the condition.
SELECT ColumnName(s) FROM TableName WHERE ColumnName operator ALL (SELECT ColumnName FROM TableName WHERE condition);
SELECT EmployeeName FROM Employee_Info WHERE EmployeeID = ALL (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad');
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.
SELECT ColumnName(s) FROM TableName WHERE ColumnName operator ANY (SELECT ColumnName FROM TableName WHERE condition);
SELECT EmployeeName FROM Employee_Info WHERE EmployeeID = ANY (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad' OR City = 'Kolkata');
Next, in this article on SQL Commands, let us look into the various Aggregate Functions provided in SQL.
This section of the article will include the following functions:
The MIN function returns the smallest value of the selected column in a table.
SELECT MIN(ColumnName) FROM TableName WHERE Condition;
SELECT MIN(EmployeeID) AS SmallestID FROM Employee_Info;
The MAX function returns the largest value of the selected column in a table.
SELECT MAX(ColumnName) FROM TableName WHERE Condition;
SELECT MAX(Salary) AS LargestFees FROM Employee_Salary;
The COUNT function returns the number of rows which match the specified criteria.
SELECT COUNT(ColumnName) FROM TableName WHERE Condition;
SELECT COUNT(EmployeeID) FROM Employee_Info;
The SUM function returns the total sum of a numeric column that you choose.
SELECT SUM(ColumnName) FROM TableName WHERE Condition;
SELECT SUM(Salary) FROM Employee_Salary;
The AVG function returns the average value of a numeric column that you choose.
SELECT AVG(ColumnName) FROM TableName WHERE Condition;
SELECT AVG(Salary) FROM Employee_Salary;
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().
SELECT EmployeeID * (Month_Year_of_Salary + ISNULL(Salary, 0)) FROM Employee_Salary;
In this section of this article on SQL Commands, you will go through the Aliases and Case statement one after the other.
Aliases are used to give a column/table a temporary name and only exists for a duration of the query.
--Alias Column Syntax SELECT ColumnName AS AliasName FROM TableName; --Alias Table Syntax SELECT ColumnName(s) FROM TableName AS AliasName;
SELECT EmployeeID AS ID, EmployeeName AS EmpName FROM Employee_Info; SELECT EmployeeName AS EmpName, EmergencyContactName AS [Contact Name] FROM Employee_Info;
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.
CASE WHEN Condition1 THEN Result1 WHEN Condition2 THEN Result2 WHEN ConditionN THEN ResultN ELSE Result END;
SELECT EmployeeName, City FROM Employee_Info ORDER BY (CASE WHEN City IS NULL THEN 'Country is India by default' ELSE City END);
Now, that I have told you a lot about DML commands in this article on SQL Commands, let me just tell you in short about Nested Queries, Joins, Set Operations, and Dates & Auto Increment.
Nested queries are those queries which have an outer query and inner subquery. So, basically, the subquery is a query which is nested within another query such as SELECT, INSERT, UPDATE or DELETE. Refer to the image below:
JOINS are used to combine rows from two or more tables, based on a related column between those tables. The following are the types of joins:
Refer to the image below.
Let’s consider the below table apart from the Employee_Info table, to understand the syntax of joins.
TechID | EmpID | TechName | ProjectStartDate |
1 | 10 | DevOps | 04-01-2019 |
2 | 11 | Blockchain | 06-07-2019 |
3 | 12 | Python | 01-03-2019 |
INNER JOIN
SELECT ColumnName(s) FROM Table1 INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Technologies.TechID, Employee_Info.EmployeeName FROM Technologies INNER JOIN Employee_Info ON Technologies.EmpID = Employee_Info.EmpID;
SELECT ColumnName(s) FROM Table1 FULL OUTER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Employee_Info.EmployeeName, Technologies.TechID FROM Employee_Info FULL OUTER JOIN Orders ON Employee_Info.EmpID=Employee_Salary.EmpID ORDER BY Employee_Info.EmployeeName;
SELECT ColumnName(s) FROM Table1 LEFT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Employee_Info.EmployeeName, Technologies.TechID FROM Employee_Info LEFT JOIN Technologies ON Employee_Info.EmployeeID = Technologies.EmpIDID ORDER BY Employee_Info.EmployeeName;
SELECT ColumnName(s) FROM Table1 RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Technologies.TechID FROM Technologies RIGHT JOIN Employee_Info ON Technologies.EmpID = Employee_Info.EmployeeID ORDER BY Technologies.TechID;
There are mainly three set operations:UNION, INTERSECT, EXCEPT. You can refer to the image below to understand the set operations in SQL.
This operator is used to combine the result-set of two or more SELECT statements.
SELECT ColumnName(s) FROM Table1 UNION SELECT ColumnName(s) FROM Table2;
This clause used to combine two SELECT statements and return the intersection of the data-sets of both the SELECT statements.
SELECT Column1 , Column2 .... FROM TableName WHERE Condition INTERSECT SELECT Column1 , Column2 .... FROM TableName WHERE Condition
This operator returns those tuples that are returned by the first SELECT operation, and are not returned by the second SELECT operation.
SELECT ColumnName FROM TableName EXCEPT SELECT ColumnName FROM TableName;
Next, in this article, let us look into the date functions and auto-increment fields.
In this section of this article, I will explain to you how to use the Date functions and also the Auto-Increment fields.
The following data types are present in a SQL Server to store a date or a date/time value in a database.
Data Type | Format |
DATE | YYYY-MM-DD |
DATETIME | YYYY-MM-DD HH:MI:SS |
SMALLDATETIME | YYYY-MM-DD HH:MI:SS |
TIMESTAMP | A Unique Number |
SELECT * FROM Technologies WHERE ProjectStartDate='2019-04-01'
This field generates a unique number automatically when a new record is inserted into a table. The MS SQL Server uses the IDENTITY keyword for this feature.
<span>/* To define the "EmployeeID" column to be an auto-increment primary key field in the "Employee_Info" table */</span> <span>CREATE TABLE Employee_Info (</span> <span>EmployeeID INT IDENTITY(1,1) PRIMARY KEY,</span> <span>EmployeeName VARCHAR(255) NOT NULL</span> <span>EmergencyContactName VARCHAR(255) NOT NULL,</span> <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.
This section of the article will give you an insight into the commands which aDMLre used to enforce database security in multiple user database environments. The commands are as follows:
This command is used to provide access or privileges on the database and its objects to the users.
GRANT PrivilegeName ON ObjectName TO {UserName |PUBLIC |RoleName} [WITH GRANT OPTION];
-- To grant SELECT permission to Employee_Info table to user1 GRANT SELECT ON Employee_Info TO user1;
This command is used to withdraw the user’s access privileges given by using the GRANT command.
REVOKE PrivilegeName ON ObjectName FROM {UserName |PUBLIC |RoleName}
-- To revoke the granted permission from user1 REVOKE SELECT ON Employee_Info TO user1;
Now, next in this article on SQL Commands, I will discuss Views, Stored Procedures, and Triggers.
A view in SQL is a single table, which is derived from other tables. So, a view contains rows and columns similar to a real table and has fields from one or more table.
This statement is used to create a view, from a table.
CREATE VIEW ViewName AS SELECT Column1, Column2, ..., ColumnN FROM TableName WHERE Condition;
CREATE VIEW [Kolkata Employees] AS SELECT EmployeeName, PhoneNumber FROM Employee_Info WHERE City = "Kolkata";
This statement is used to update a view.
CREATE VIEW OR REPLACE ViewName AS SELECT Column1, Column2, ..., ColumnN FROM TableName WHERE Condition;
CREATE VIEW OR REPLACE [Kolkata Employees] AS SELECT EmployeeName, PhoneNumber FROM Employee_Info WHERE City = "Kolkata";
This statement is used to delete a view.
DROP VIEW ViewName;
DROP VIEW [Kolkata Employees];
A code which you can save and reuse it again is known as StoredProcedures.
CREATE PROCEDURE ProcedureName AS SQLStatement GO;
EXEC ProcedureName;
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.
CREATE TRIGGER [TriggerName] [BEFORE | AFTER] {INSERT | UPDATE | DELETE} on [TableName] [FOR EACH ROW] [TriggerBody]
Now, let’s move on to the last section of this article on SQL Commands i.e. the Transaction Control Language Commands.
This section of the article will give you an insight into the commands which are used to manage transactions in the database. The commands are as follows:
This command is used to save the transaction into the database.
COMMIT;
This command is used to restore the database to the last committed state.
ROLLBACK;
This command is used to temporarily save a transaction. So if you wish to rollback to any point, then you can save that point as a ‘SAVEPOINT’.
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.
INSERT INTO Employee_Table VALUES(05, 'Avinash'); COMMIT; UPDATE Employee_Table SET name = 'Akash' WHERE id = '05'; SAVEPOINT S1; INSERT INTO Employee_Table VALUES(06, 'Sanjana'); SAVEPOINT S2; INSERT INTO Employee_Table VALUES(07, 'Sanjay'); SAVEPOINT S3; INSERT INTO Employee_Table VALUES(08, 'Veena'); SAVEPOINT S4; SELECT * 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.
ROLLBACK TO S2; SELECT * FROM Employee_Table;
EmployeeID | EmployeeName |
01 | Ruhaan |
02 | Suhana |
03 | Aayush |
04 | Rashi |
05 | Akash |
06 | Sanjana |
Learn about How to Change Column Name in SQL?
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.
Course Name | Date | Details |
---|---|---|
Microsoft SQL Server Certification Course | Class Starts on 7th December,2024 7th December SAT&SUN (Weekend Batch) | View Details |
edureka.co