EIT Unit - IV CSE 6th Semester
EIT Unit - IV CSE 6th Semester
1. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis
for SQL, and for all modern database systems like MS SQL Server, IBM DB2,
Oracle, MySQL, and Microsoft Access.
Furthermore, RDBMSes make it easy to add new data to the system or alter
existing tables while ensuring consistency with the previously available content.
Flexibility -- updating data is more efficient since the changes only need to be
made in one place.
Data structure -- the table format used in RDBMSes is easy to understand and
provides an organized and structural manner through which entries are matched by
firing queries.
On the other hand, relational database management systems do not come without
their disadvantages. For example, in order to implement an RDBMS, special
software must be purchased. This introduces an additional cost for execution. Once
the software is obtained, the setup process can be tedious since it requires millions
of lines of content to be transferred into the RDBMS tables. This process may
require the additional help of a programmer or a team of data entry specialists.
Special attention must be paid to the data during entry to ensure sensitive
information is not placed into the wrong hands.
Some other drawbacks of the RDBMS include the character limit placed on certain
fields in the tables and the inability to fully understand new forms of data -- such
as complex numbers, designs and images.
Uses of RDBMS
Some examples of specific systems that use RDBMS include IBM, Oracle,
MySQL, Microsoft SQLServer and PostgreSQL.
What is a table?
The data in an RDBMS is stored in database objects which are called as tables. This
table is basically a collection of related data entries and it consists of numerous
columns and rows.
Remember, a table is the most common and simplest form of data storage in a
relational database. The following program is an example of a CUSTOMERS table −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
What is a field?
Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about
every record in the table.
What is a column?
A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents
location description and would be as shown below −
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+
2. SQL Constraints
Constraints are the rules enforced on data columns on a table. These 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 database.
Constraints can either be column level or table level. Column level constraints are
applied only to one column whereas, table level constraints are applied to the entire
table.
Following are some of the most commonly used constraints available in SQL −
• NOT NULL Constraint − Ensures that a column cannot have a NULL value.
• DEFAULT Constraint − Provides a default value for a column when none is specified.
• UNIQUE Constraint − Ensures that all the values in a column are different.
• PRIMARY Key − Uniquely identifies each row/record in a database table.
• FOREIGN Key − Uniquely identifies a row/record in any another database table.
• CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy
certain conditions.
• INDEX − Used to create and retrieve data from the database very quickly.
3. Data Integrity
The following categories of data integrity exist with each RDBMS −
• Entity Integrity − There are no duplicate rows in a table.
• Domain Integrity − Enforces valid entries for a given column by restricting the type, the
format, or the range of values.
• Referential integrity − Rows cannot be deleted, which are used by other records.
• User-Defined Integrity − Enforces some specific business rules that do not fall into entity,
domain or referential integrity.
4. Database Normalization
Database normalization is the process of efficiently organizing data in a database.
There are two reasons of this normalization process −
• Eliminating redundant data, for example, storing the same data in more than one table.
• Ensuring data dependencies make sense.
Both these reasons are worthy goals as they reduce the amount of space a database
consumes and ensures that data is logically stored. Normalization consists of a series
of guidelines that help guide you in creating a good database structure.
Normalization guidelines are divided into normal forms; think of a form as the format or
the way a database structure is laid out. The aim of normal forms is to organize the
database structure, so that it complies with the rules of first normal form, then second
normal form and finally the third normal form.
It is your choice to take it further and go to the fourth normal form, fifth normal form and
so on, but in general, the third normal form is more than enough.
Example: Suppose a company wants to store the names and contact details of its employees. It
creates a table that looks like this:
9900012222
9990000123
Two employees (Jon & Lester) are having two mobile numbers so the company stored them in
the same field as you can see in the table above.
This table is not in 1NF as the rule says “each attribute of a table must have atomic (single)
values”, the emp_mobile values for employees Jon & Lester violates that rule.
To make the table complies with 1NF we should have the data like this:
An attribute that is not part of any candidate key is known as non-prime attribute.
Example: Suppose a school wants to store the data of teachers and the subjects they teach. They
create a table that looks like this: Since a teacher can teach more than one subjects, the table can
have multiple rows for a same teacher.
111 Maths 38
111 Physics 38
222 Biology 38
333 Physics 40
333 Chemistry 40
The table is in 1 NF because each attribute has atomic values. However, it is not in 2NF because
non prime attribute teacher_age is dependent on teacher_id alone which is a proper subset of
candidate key. This violates the rule for 2NF as the rule says “no non-prime attribute is
dependent on the proper subset of any candidate key of the table”.
To make the table complies with 2NF we can break it in two tables like this:
teacher_details table:
teacher_id teacher_age
111 38
222 38
333 40
teacher_subject table:
teacher_id subject
111 Maths
111 Physics
222 Biology
333 Physics
333 Chemistry
In other words 3NF can be explained like this: A table is in 3NF if it is in 2NF and for each
functional dependency X-> Y at least one of the following conditions hold:
An attribute that is a part of one of the candidate keys is known as prime attribute.
Example: Suppose a company wants to store the complete address of each employee, they create
a table named employee_details that looks like this:
Here, emp_state, emp_city & emp_district dependent on emp_zip. And, emp_zip is dependent on
emp_id that makes non-prime attributes (emp_state, emp_city & emp_district) transitively
dependent on super key (emp_id). This violates the rule of 3NF.
To make this table complies with 3NF we have to break the table into two tables to remove the
transitive dependency:
employee table:
employee_zip table:
emp_zip emp_state emp_city emp_district
Example: Suppose there is a company wherein employees work in more than one department.
They store the data like this:
The table is not in BCNF as neither emp_id nor emp_dept alone are keys.
To make the table comply with BCNF we can break the table in three tables like this:
emp_nationality table:
emp_id emp_nationality
1001 Austrian
1002 American
emp_dept table:
emp_dept_mapping table:
emp_id emp_dept
1001 stores
1002 design and technical support
Functional dependencies:
emp_id -> emp_nationality
emp_dept -> {dept_type, dept_no_of_emp}
Candidate keys:
For first table: emp_id
For second table: emp_dept
For third table: {emp_id, emp_dept}
This is now in BCNF as in both the functional dependencies left side part is a key.
5. ORACLE
It is a very large multi-user based database management system. Oracle is a relational
database management system developed by 'Oracle Corporation'.
Oracle works to efficiently manage its resources, a database of information among the
multiple clients requesting and sending data in the network.
It is an excellent database server choice for client/server computing. Oracle supports
all major operating systems for both clients and servers, including MSDOS, NetWare,
UnixWare, OS/2 and most UNIX flavors.
History
Oracle began in 1977 and celebrating its 32 wonderful years in the industry (from 1977
to 2009).
• 1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development Laboratories
to undertake development work.
• 1979 - Version 2.0 of Oracle was released and it became first commercial relational
database and first SQL database. The company changed its name to Relational Software
Inc. (RSI).
• 1981 - RSI started developing tools for Oracle.
• 1982 - RSI was renamed to Oracle Corporation.
• 1983 - Oracle released version 3.0, rewritten in C language and ran on multiple platforms.
• 1984 - Oracle version 4.0 was released. It contained features like concurrency control -
multi-version read consistency, etc.
• 1985 - Oracle version 4.0 was released. It contained features like concurrency control -
multi-version read consistency, etc.
• 2007 - Oracle released Oracle11g. The new version focused on better partitioning, easy
migration, etc.
Features
• Concurrency
• Read Consistency
• Locking Mechanisms
• Quiesce Database
• Portability
• Self-managing database
• SQL*Plus
• ASM
• Scheduler
• Resource Manager
• Data Warehousing
• Materialized views
• Bitmap indexes
• Table compression
• Parallel Execution
• Analytic SQL
• Data mining
• Partitioning
6. Data Model
Data Model gives us an idea that how the final system will look like after its
complete implementation. It defines the data elements and the relationships
between the data elements. Data Models are used to show how data is stored,
connected, accessed and updated in the database management system. Here, we
use a set of symbols and text to represent the information so that members of the
organisation can communicate and understand it. Though there are many data
models being used nowadays but the Relational model is the most widely used
model. Apart from the Relational model, there are many other types of data models
about which we will study in details in this blog. Some of the Data Models in
DBMS are:
1. Hierarchical Model
2. Network Model
3. Entity-Relationship Model
4. Relational Model
5. Object-Oriented Data Model
6. Object-Relational Data Model
7. Flat Data Model
8. Semi-Structured Data Model
9. Associative Data Model
10.Context Data Model
Entity-Relationship Model
Entity-Relationship Model or simply ER Model is a high-level data model
diagram. In this model, we represent the real-world problem in the pictorial form to
make it easy for the stakeholders to understand. It is also very easy for the
developers to understand the system by just looking at the ER diagram. We use the
ER diagram as a visual tool to represent an ER Model. ER diagram has the
following three components:
Features of ER Model
Relational Model
Relational Model is the most widely used model. In this model, the data is
maintained in the form of a two-dimensional table. All the information is stored in
the form of row and columns. The basic structure of a relational model is tables.
So, the tables are also called relations in the relational model. Example: In this
example, we have an Employee table.
• Tuples: Each row in the table is called tuple. A row contains all the
information about any instance of the object. In the above example, each
row has all the information about any specific individual like the first row
has information about John.
• Attribute or field: Attributes are the property which defines the table or
relation. The values of the attribute should be from the same domain. In the
above example, we have different attributes of the employee like Salary,
Mobile_no, etc.
Advnatages of Relational Model
• Hardware Overheads: For hiding the complexities and making things easier
for the user this model requires more powerful hardware computers and data
storage devices.
• Bad Design: As the relational model is very easy to design and use. So the
users don't need to know how the data is stored in order to access it. This
ease of design can lead to the development of a poor database which would
slow down if the database grows.
But all these disadvantages are minor as compared to the advantages of the
relational model. These problems can be avoided with the help of proper
implementation and organisation.
A simple ER Diagram:
In the following diagram we have two entities Student and College and their
relationship. The relationship between Student and College is many to one as a
college can have many students however a student cannot study in multiple
colleges at the same time. Student entity has attributes such as Stu_Id, Stu_Name
& Stu_Addr and College entity has attributes such as Col_ID & Col_Name.
Here are the geometric shapes and their meaning in an E-R Diagram. We will
discuss these terms in detail in the next section(Components of a ER Diagram) of
this guide so don’t worry too much about these terms now, just go through them
once.
Components of a ER Diagram
1. Entity
Weak Entity:
An entity that cannot be uniquely identified by its own attributes and relies on the
relationship with other entity is called weak entity. The weak entity is represented
by a double rectangle. For example – a bank account cannot be uniquely identified
without knowing the bank to which the account belongs, so bank account is a weak
entity.
2. Attribute
1. Key attribute
2. Composite attribute
3. Multivalued attribute
4. Derived attribute
1. Key attribute:
A key attribute can uniquely identify an entity from an entity set. For example,
student roll number can uniquely identify a student from a set of students. Key
attribute is represented by oval same as other attributes however the text of key
attribute is underlined.
2. Composite attribute:
4. Derived attribute:
A derived attribute is one whose value is dynamic and derived from another
attribute. It is represented by dashed oval in an ER Diagram. For example –
Person age is a derived attribute as it changes over time and can be derived from
another attribute (Date of birth).
3. Relationship
When a single instance of an entity is associated with more than one instances of
another entity then it is called one to many relationship. For example – a customer
can place many orders but a order cannot be placed by many customers.
When more than one instances of an entity is associated with a single instance of
another entity then it is called many to one relationship. For example – many
students can study in a single college but a student cannot study in many colleges
at the same time.
4. Many to Many Relationship
When more than one instances of an entity is associated with more than one
instances of another entity then it is called many to many relationship. For
example, a can be assigned to many projects and a project can be assigned to many
students.
A Total participation of an entity set represents that each entity in entity set must
have at least one relationship in a relationship set. For example: In the below
diagram each college must have at-least one associated Student.
Problem-01:
Find the minimum number of tables required for the following ER diagram in relational
model-
Solution-
Problem-02:
Find the minimum number of tables required to represent the given ER diagram in
relational model-
Solution-
Problem-03:
Find the minimum number of tables required to represent the given ER diagram in
relational model-
Solution-
Problem-04:
Find the minimum number of tables required to represent the given ER diagram in
relational model-
Solution-
Problem-05:
Find the minimum number of tables required to represent the given ER diagram in
relational model-
Solution-
Applying the rules that we have learnt, minimum 6 tables will be required-
• Account (Ac_no , Balance , b_name)
• Branch (b_name , b_city , Assets)
• Loan (L_no , Amt , b_name)
• Borrower (C_name , L_no)
• Customer (C_name , C_street , C_city)
• Depositor (C_name , Ac_no)
.
Following rules are used for converting an ER diagram into the tables-
A strong entity set with only simple attributes will require only one table in relational
model.
• Attributes of the table will be the attributes of the entity set.
• The primary key of the table will be the key attribute of the entity set.
Example-
• A strong entity set with any number of composite attributes will require only one table in
relational model.
• While conversion, simple attributes of the composite attributes are taken into account and not
the composite attribute itself.
Example-
A strong entity set with any number of multi valued attributes will require two tables in
relational model.
• One table will contain all the simple attributes with the primary key.
• Other table will contain the primary key and all the multi valued attributes.
Example-
Roll_no City
Roll_no Mobile_no
Rule-04: Translating Relationship Set into a Table-
Example-
NOTE-
If we consider the overall ER diagram, three tables will be required in relational model-
• One table for the entity set “Employee”
• One table for the entity set “Department”
• One table for the relationship set “Works in”
NOTE- Here, combined table will be drawn for the entity set B and relationship set R.
NOTE- Here, combined table will be drawn for the entity set A and relationship set R.
Case-04: For Binary Relationship With Cardinality Ratio 1:1
Here, two tables will be required. Either combine ‘R’ with ‘A’ or ‘B’
Way-01:
1. AR ( a1 , a2 , b1 )
2. B ( b1 , b2 )
Way-02:
1. A ( a1 , a2 )
2. BR ( a1 , b1 , b2 )
While determining the minimum number of tables required for binary relationships with given
cardinality ratios, following thumb rules must be kept in mind-
• For binary relationship with cardinality ration m : n , separate and individual tables will be drawn for each
entity set and relationship.
• For binary relationship with cardinality ratio either m : 1 or 1 : n , always remember “many side will consume
the relationship” i.e. a combined table will be drawn for many side entity set and relationship set.
• For binary relationship with cardinality ratio 1 : 1 , two tables will be required. You can combine the
relationship set with any one of the entity sets.
Case-01: For Binary Relationship With Cardinality Constraint and Total Participation
Constraint From One Side-
Because cardinality ratio = 1 : n , so we will combine the entity set B and relationship set
R.
Then, two tables will be required-
1. A ( a1 , a2 )
2. BR ( a1 , b1 , b2 )
Because of total participation, foreign key a1 has acquired NOT NULL constraint, so it
can’t be null now.
Case-02: For Binary Relationship With Cardinality Constraint and Total Participation
Constraint From Both Sides-
If there is a key constraint from both the sides of an entity set with total participation,
then that binary relationship is represented using only single table.
Here, Only one table is required.
• ARB ( a1 , a2 , b1 , b2 )
Weak entity set always appears in association with identifying relationship with total
participation constraint.
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
In this article on SQL Commands, I am going to consider the below database as an example, to
show you how to write commands.
Emergency
EmployeeID EmployeeName PhoneNumber Address City Country
ContactName
Oberoi
01 Shanaya Abhinay 9898765612 Mumbai India
Street 23
Marathalli
02 Anay Soumya 9432156783 House No Delhi India
23
Queens
03 Preeti Rohan 9764234519 Bangalore India
Road 45
Brigade
04 Vihaan Akriti 9966442211 Road Block Hyderabad India
4
Mayo Road
05 Manasa Shourya 9543176246 Kolkata India
23
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:
2 SELECT * 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:
1 /*Select all the columns
•
▪ CREATE
▪ DROP
▪ TRUNCATE
▪ ALTER
▪ BACKUP DATABASE
CREATE
This statement is used to create a table or a database.
Syntax
CREATE DATABASE DatabaseName;
Example
1 CREATE DATABASE Employee;
Syntax
CREATE TABLE TableName (
Column1 datatype,
Column2 datatype,
Column3 datatype,
....
ColumnN datatype
);
Example
1
CREATE TABLE Employee_Info
2
(
3 EmployeeID int,
4 EmployeeName varchar(255),
6 PhoneNumber int,
7 Address varchar(255),
City varchar(255),
8
Country varchar(255)
9
);
10
You can also create a table using another table. Refer the below sytax and example:
3 FROM Employee_Info;
DROP
This statement is used to drop an existing table or a database.
Syntax
DROP TABLE TableName;
Example
1 DROP Table Employee_Info;
TRUNCATE
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
TRUNCATE TABLE TableName;
Example
1 TRUNCATE Table Employee_Info;
ALTER
This command is used to delete, modify or add constraints or columns in an existing table.
Syntax
ALTER TABLE TableName
ADD ColumnName Datatype;
2
ALTER TABLE Employee_Info
3 ADD BloodGroup varchar(255);
6
ALTER TABLE Employee_Info
7
DROP COLUMN BloodGroup ;
8
Syntax
ALTER TABLE TableName
ALTER COLUMN ColumnName Datatype;
Example
1 --Add a column DOB and change the data type to Date.
BACKUP DATABASE
This statement is used to create a full backup of an existing database.
Syntax
BACKUP DATABASE DatabaseName
TO DISK = 'filepath';
Example
1 BACKUP DATABASE Employee
2 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.
Syntax
BACKUP DATABASE DatabaseName
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Example
1 BACKUP DATABASE Employee
2 TO DISK = 'C:UsersSahitiDesktop'
3 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.
▪ NOT NULL
▪ UNIQUE
▪ CHECK
▪ DEFAULT
▪ INDEX
NOT NULL
This constraint ensures that a column cannot have a NULL value.
Example
--NOT NULL on Create Table
1
2
CREATE TABLE Employee_Info
3
(
4
EmployeeID int NOT NULL,
5 EmployeeName varchar(255) NOT NULL,
12
--NOT NULL on ALTER TABLE
13
16
17
UNIQUE
This constraint ensures that all the values in a column are unique.
Example
1 --UNIQUE on Create Table
2
CREATE TABLE Employee_Info
3
(
4
EmployeeID int NOT NULL UNIQUE,
5
EmployeeName varchar(255) NOT NULL,
6
Emergency ContactName varchar(255),
7
PhoneNumber int NOT NULL,
8
Address varchar(255),
9 City varchar(255),
10 Country varchar(255)
11 );
12
14
CREATE TABLE Employee_Info
15
(
16
EmployeeID int NOT NULL,
17
EmployeeName varchar(255) NOT NULL,
18
Emergency ContactName varchar(255),
19
PhoneNumber int NOT NULL,
20 Address varchar(255),
21 City varchar(255),
22 Country varchar(255),
);
24
25
--UNIQUE on ALTER TABLE
26
27
ALTER TABLE Employee_Info
28
ADD UNIQUE (Employee_ID);
29
30
--To drop a UNIQUE constraint
31
32
ALTER TABLE Employee_Info
33 DROP CONSTRAINT UC_Employee_Info;
34
35
36
CHECK
This constraint ensures that all the values in a column satisfy a specific condition.
Example
1 --CHECK Constraint on CREATE TABLE
(
4
EmployeeID int NOT NULL,
5
EmployeeName varchar(255),
6
Emergency ContactName varchar(255),
7
PhoneNumber int,
8
Address varchar(255),
9 City varchar(255),
11 );
12
14
CREATE TABLE Employee_Info
15
(
16
EmployeeID int NOT NULL,
17
EmployeeName varchar(255),
18
Emergency ContactName varchar(255),
19
PhoneNumber int,
20 Address varchar(255),
21 City varchar(255),
24
26
ALTER TABLE Employee_Info
27
ADD CHECK (Country=='India');
28
29
--To give a name to the CHECK Constraint
30
31
ALTER TABLE Employee_Info
32
ADD CONSTRAINT CheckConstraintName CHECK (Country=='India');
33
34
--To drop a CHECK Constraint
35
38
39
40
DEFAULT
This constraint consists of a set of default values for a column when no value is specified.
Example
1 --DEFAULT Constraint on CREATE TABLE
4 (
PhoneNumber int,
8
Address varchar(255),
9
City varchar(255),
10
Country varchar(255) DEFAULT 'India'
11
);
12
13
--DEFAULT Constraint on ALTER TABLE
14
18
20
ALTER TABLE Employee_Info
21
ALTER COLUMN Country DROP DEFAULT;
22
23
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
--Create an Index where duplicate values are allowed
CREATE INDEX IndexName
ON TableName (Column1, Column2, ...ColumnN);
2 ON Persons (EmployeeName);
Now, let us look into the next part of this article i.e. DML Commands.
▪ USE
▪ INSERT INTO
▪ UPDATE
▪ DELETE
▪ SELECT
Apart from these commands, there are also other manipulative operators/functions such as:
▪ 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
1 USE Employee;
INSERT INTO
This statement is used to insert new records into the table.
Syntax
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
UPDATE
This statement is used to modify the records already present in the table.
Syntax
UPDATE TableName
SET Column1 = Value1, Column2 = Value2, ...
WHERE Condition;
Example
1 UPDATE Employee_Info
3 WHERE EmployeeID = 1;
DELETE
This statement is used to delete the existing records in a table.
Syntax
DELETE FROM TableName WHERE Condition;
Example
1 DELETE FROM Employee_Info
2 WHERE EmployeeName='Preeti';
SELECT
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
SELECT Column1, Column2, ...ColumN
FROM TableName;
2 FROM Employee_Info;
Apart from just using the SELECT keyword individually, you can use the following keywords
with the SELECT statement:
•
▪ DISTINCT
▪ ORDER BY
▪ GROUP BY
▪ HAVING Clause
▪ INTO
Syntax
SELECT DISTINCT Column1, Column2, ...ColumnN
FROM TableName;
Example
1 SELECT DISTINCT PhoneNumber FROM Employee_Info;
Syntax
SELECT Column1, Column2, ...ColumnN
FROM TableName
ORDER BY Column1, Column2, ... ASC|DESC;
Example
1
-- Select all employees from the 'Employee_Info' table so
2 SELECT * FROM Employee_Info
3 ORDER BY EmergencyContactName
ORDER BY EmergencyContactName D
7
8
-- Select all employees from the 'Employee_Info' table sorted by
9
SELECT * FROM Employee_Info
10
ORDER BY EmergencyContactName, Emplo
11
12
/* Select all employees from the 'Employee_Info' table sorted by EmergencyContactName
13 */
Syntax
SELECT Column1, Column2,..., ColumnN
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
ORDER BY ColumnName(s);
Example
1 -- To list the number of employees from each city.
4 FROM Employee_Info
5 GROUP BY City;
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
HAVING Condition
ORDER BY ColumnName(s);
Example
1 /* To list the number of employees in each city. The employees should be s
who have more than 5 employees:
2
3
SELECT COUNT(EmployeeID), City
4
FROM Employee_Info
5 GROUP BY City
Syntax
SELECT *
INTO NewTable [IN ExternalDB]
FROM OldTable
WHERE Condition;
Example
1
-- To create a backup of database 'Employee'
2
SELECT * INTO EmployeeBackup
3 FROM Employee;
7 FROM Employee;
8
SELECT * INTO BlrEmployee
9
FROM Employee
10
WHERE City = 'Bangalore';
11
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
The different set of operators available in SQL are as follows:
% Modulous [A % B]
/ Division [A / B]
* Multiplication [A * B]
– Subtraction [A – B]
+ Addition [A + B]
Bitwise Operators
Operator Description
| Bitwise OR [A | B]
Comparison Operators
Operator Description
= Equal to [A = B]
Compound Operators
Operator Description
/= Divide equals [A /= B]
Logical Operators
The Logical operators present in SQL are as follows:
•
▪ 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
OR Operator
This operator displays all those records which satisfy any of the conditions separated by OR and
give the output TRUE.
Syntax
NOT Operator
The NOT operator is used, when you want to display the records which do not satisfy a
condition.
Syntax
NOTE: You can also combine the above three operators and write a query as
follows:
1 SELECT * FROM Employee_Info
NOTE: You can also combine the above three operators and write a query as
follows:
1 SELECT * FROM Employee_Info
BETWEEN Operator
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
LIKE Operator
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:
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.
WHERE CustomerName LIKE ‘v% Finds any values that start with “v”
WHERE CustomerName LIKE ‘%v’ Finds any values that end with “v”
WHERE CustomerName LIKE ‘%and%’ Finds any values that have “and” in any position
WHERE CustomerName LIKE ‘_q%’ Finds any values that have “q” in the second position.
Finds any values that start with “u” and are at least 3
WHERE CustomerName LIKE ‘u_%_%’
characters in length
WHERE ContactName LIKE ‘m%a’ Finds any values that start with “m” and end with “a”
Example
IN Operator
This operator is used for multiple OR conditions. This allows you to specify multiple values in a
WHERE clause.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName IN (Value1,Value2...);
Example
1 SELECT * FROM Employee_Info
SELECT ColumnName(s)
FROM TableName
WHERE EXISTS
(SELECT ColumnName FROM TableName WHERE condition);
Example
1 SELECT EmergencyContactName
2 FROM Employee_Info
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
1 SELECT EmployeeName
2 FROM Employee_Info
3 WHERE EmployeeID = ALL (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyder
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
1 SELECT EmployeeName
2 FROM Employee_Info
3 WHERE EmployeeID = ANY (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyde
Next, in this article on SQL Commands, let us look into the various Aggregate Functions
provided in SQL.
Aggregate Functions
This section of the article will include the following 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
1 SELECT MIN(EmployeeID) AS SmallestID
2 FROM Employee_Info;
MAX() Function
The MAX function returns the largest value of the selected column in a table.
Syntax
SELECT MAX(ColumnName)
FROM TableName
WHERE Condition;
Example
1 SELECT MAX(Salary) AS LargestFees
2 FROM Employee_Salary;
COUNT() Function
The COUNT function returns the number of rows which match the specified criteria.
Syntax
SELECT COUNT(ColumnName)
FROM TableName
WHERE Condition;
Example
1 SELECT COUNT(EmployeeID)
2 FROM 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
1 SELECT SUM(Salary)
2 FROM 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
1 SELECT AVG(Salary)
2 FROM 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
1 SELECT EmployeeID * (Month_Year_of_Salary + ISNULL(Salary, 0))
2 FROM Employee_Salary;
Aliases & Case Statement
In this section of this article on SQL Commands, you will go through the Aliases and Case
statement one after the other.
Aliases
Aliases are used to give a column/table a temporary name and only exists for a duration of the
query.
Syntax
--Alias Column Syntax
SELECT ColumnName(s)
FROM TableName AS AliasName;
Example
1 SELECT EmployeeID AS ID, EmployeeName AS EmpName
2 FROM Employee_Info;
5 FROM Employee_Info;
Case Statement
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
SELECT EmployeeName, City
1
FROM Employee_Info
2
ORDER BY
3 (CASE
ELSE City
5
END);
6
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.
• 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.
Let’s consider the below table apart from the Employee_Info table, to understand the syntax of
joins.
1 10 DevOps 04-01-2019
2 11 Blockchain 06-07-2019
3 12 Python 01-03-2019
INNER JOIN
Syntax
SELECT ColumnName(s)
FROM Table1
INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
1 SELECT Technologies.TechID, Employee_Info.EmployeeName
2 FROM Technologies
FULL JOIN
Syntax
SELECT ColumnName(s)
FROM Table1
FULL OUTER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
1 SELECT Employee_Info.EmployeeName, Technologies.TechID
2 FROM Employee_Info
ORDER BY Employee_Info.EmployeeName;
4
LEFT JOIN
Syntax
SELECT ColumnName(s)
FROM Table1
LEFT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
1 SELECT Employee_Info.EmployeeName, Technologies.TechID
2 FROM Employee_Info
4 ORDER BY Employee_Info.EmployeeName;
RIGHT JOIN
Syntax
SELECT ColumnName(s)
FROM Table1
RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example
1 SELECT Technologies.TechID
2 FROM Technologies
4 ORDER BY Technologies.TechID;
Syntax
SELECT ColumnName(s) FROM Table1
UNION
SELECT ColumnName(s) FROM Table2;
INTERSECT
This clause used to combine two SELECT statements and return the intersection of the data-sets
of both the SELECT statements.
Syntax
SELECT Column1 , Column2 ....
FROM TableName
WHERE Condition
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.
DATE YYYY-MM-DD
Example
1 SELECT * FROM Technologies WHERE ProjectStartDate='2019-04-01'
Auto Increment
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.
Example
1 <span>/* To define the "EmployeeID" column to be an auto-increment primary key
<span>);</span>
7
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.
SQL Commands: Data Control Language Commands
(DCL)
This section of the article will give you an insight into the commands which are used to enforce
database security in multiple user database environments. The commands are as follows:
•
▪ GRANT
▪ REVOKE
GRANT
This command is used to provide access or privileges on the database and its objects to the users.
Syntax
GRANT PrivilegeName
ON ObjectName
TO {UserName |PUBLIC |RoleName}
[WITH GRANT OPTION];
where,
Example
1 -- To grant SELECT permission to Employee_Info table to user1
REVOKE
This command is used to withdraw the user’s access privileges given by using
the GRANT command.
Syntax
REVOKE PrivilegeName
ON ObjectName
FROM {UserName |PUBLIC |RoleName}
Example
1 -- To revoke the granted permission from user1
Syntax
CREATE VIEW ViewName AS
SELECT Column1, Column2, ..., ColumnN
FROM TableName
WHERE Condition;
Example
1 CREATE VIEW [Kolkata Employees] AS
3 FROM Employee_Info
Syntax
CREATE VIEW OR REPLACE ViewName AS
SELECT Column1, Column2, ..., ColumnN
FROM TableName
WHERE Condition;
Example
1 CREATE VIEW OR REPLACE [Kolkata Employees] AS
3 FROM Employee_Info
Syntax
DROP VIEW ViewName;
Example
1 DROP VIEW [Kolkata Employees];
Syntax
CREATE PROCEDURE ProcedureName
AS
SQLStatement
GO;
Example
1 EXEC ProcedureName;
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:
•
▪ COMMIT
▪ ROLLBACK
▪ SAVEPOINT
COMMIT
This command is used to save the transaction into the database.
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
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’.
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.
2 COMMIT;
9 SAVEPOINT S4;
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.
1 ROLLBACK TO S2;
EmployeeID EmployeeName
01 Ruhaan
02 Suhana
03 Aayush
04 Rashi
05 Akash
06 Sanjana