0% found this document useful (0 votes)
3 views

Structured Query Language

Structured Query Language (SQL) is a standard database language used for creating, maintaining, and retrieving relational databases. It includes various operators (arithmetic, comparison, logical) and aggregate functions (COUNT, SUM, AVG, MIN, MAX) to perform operations on data. SQL also supports nested queries and different types of JOINs (INNER, LEFT, RIGHT, FULL) to combine records from multiple tables.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Structured Query Language

Structured Query Language (SQL) is a standard database language used for creating, maintaining, and retrieving relational databases. It includes various operators (arithmetic, comparison, logical) and aggregate functions (COUNT, SUM, AVG, MIN, MAX) to perform operations on data. SQL also supports nested queries and different types of JOINs (INNER, LEFT, RIGHT, FULL) to combine records from multiple tables.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Structured Query Language (SQL)



Structured Query Language is a standard Database language that is used to create, maintain,
and retrieve the relational database. In this article, we will discuss this in detail about SQL.
Following are some interesting facts about SQL. Let’s focus on that.
SQL is case insensitive. But it is a recommended practice to use keywords (like SELECT, UPDATE,
CREATE, etc.) in capital letters and use user-defined things (like table name, column name, etc.)
in small letters.
We can write comments in SQL using “–” (double hyphen) at the beginning of any line. SQL is
the programming language for relational databases (explained below) like MySQL, Oracle,
Sybase, SQL Server, Postgre, etc. Other non-relational databases (also called NoSQL) databases
like MongoDB, DynamoDB, etc. do not use SQL.
Although there is an ISO standard for SQL, most of the implementations slightly vary in syntax.
So we may encounter queries that work in SQL Server but do not work in MySQL.
Additional basic operations:
Structured Query Language is a computer language that we use to interact with a relational
database. In this article we will see all types of SQL operators.
In simple operator can be defined as an entity used to perform operations in a table.
Operators are the foundation of any programming language. We can define operators as
symbols that help us to perform specific mathematical and logical computations on operands.
In other words, we can say that an operator operates the operands. SQL operators have three
different categories.
Types of SQL Operators
 Arithmetic operator
 Comparison operator
 Logical operator
Arithmetic Operators
We can use various arithmetic operators on the data stored in the tables. Arithmetic
Operators are:

Operator Description

+ The addition is used to perform an addition operation on the data values.


Operator Description

– This operator is used for the subtraction of the data values.

/ This operator works with the ‘ALL’ keyword and it calculates division operations.

* This operator is used for multiplying data values.

% Modulus is used to get the remainder when data is divided by another.

Example Query:
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output:

Comparison Operators
Another important operator in SQL is a comparison operator, which is used to compare one
expression’s value to other expressions. SQL supports different types of comparison operator,
which is described below:
Operato
r Description

= Equal to.

> Greater than.


Operato
r Description

< Less than.

>= Greater than equal to.

<= Less than equal to.

<> Not equal to.

Example Query:
SELECT * FROM MATHS WHERE MARKS=50;
Output:

Logical Operators
The Logical operators are those that are true or false. They return true or false values to
combine one or more true or false values.
Operato
r Description

AND Logical AND compares two Booleans as expressions and returns true when both
expressions are true.

OR Logical OR compares two Booleans as expressions and returns true when one of the
expressions is true.

NOT Not takes a single Boolean as an argument and change its value from false to true or
from true to false.

Example Query:
SELECT * FROM employee WHERE emp_city =
'Allahabad' AND emp_country = 'India';
Output:

Null values:
SQL places a NULL value in the field in the absence of a user-defined value. For example, the
Apartment_number attribute of an address applies only to addresses that are in apartment
buildings and not to other types of residences.
So, NULL values are those values in which there is no data value in the particular field in the
table.
Importance of NULL Value
 It is important to understand that a NULL value differs from a zero value.
 A NULL value is used to represent a missing value, but it usually has one of three different
interpretations:
 The value unknown (value exists but is not known)
 Value not available (exists but is purposely withheld)
 Attribute not applicable (undefined for this tuple)

Aggregate functions Aggregate functions in SQL are unique functions that work on a group of
rows in a table and produce a single value as a result. These operations are used to calculate a
set of numbers and produce summary statistics like sum, count, average, maximum, and
minimum.

ADVERTISEMENT

1. Count()
2. Sum()
3. Avg()
4. Min()
5. Max()

1. COUNT():

This function returns the number of records(rows) in a table. The Syntax of the count() function
is mentioned below.

Syntax:

1. SELECT COUNT(column_name) FROM table_name WHERE condition;

Here column_name is the name of the column that you want to know about the number of
values and the WHERE clause is used only when specific data which satisfies a condition is
extracted.

Ex: consider below "Student" table for understanding the functioning of the Count() function.

Roll_no Student_name Department

421 Abhishek CSE

422 Praveen EEE

423 Rehman ECE

424 Priyanka IT
425 Anish CSE

Student

1. select COUNT(*) FROM Student;

Output

COUNT(*)

Now, let us attach the WHERE clause to the COUNT() and see how it works.

select COUNT(*) FROM Student WHERE Department = 'CSE';

Output:

COUNT(*)

2. SUM():

This function returns the sum of all values of a column in a table. Here is the syntax for the
sum() function.

Syntax:

1. SELECT SUM(column_name) FROM table_name WHERE condition;

Ex: observe the below example for understanding the functioning of the SUM function.

Table: sales
Product_id Product_name Price

1 Laptop 50000

2 Shirt 500

3 Watch 700

4 Mobile 20000

5 Keyboard 1800

6 Mobile 18000

1. select SUM(Price) FROM sales;

Output:

SUM(Price)

91000

Now let us calculate the sum of the prices of mobiles which are present in the sales table.

1. select SUM(price) FROM sales WHERE Product_name = 'Mobile';

Output:

SUM(Price)

38000
3. AVG()

This function will return the average of all values present in a column. The syntax of the AVG()
function is given below.

Syntax:

1. SELECT AVG(column_name) FROM table_name WHERE condition;

Here column_name is the name of the column for which you need to find the average of the
values present in the column and the WHERE clause is used only when you wanted to apply
AVG() function to the data which satisfies the condition.

Let us consider again the "sales" table for applying the AVG() on it and let us see how it works.

Table: Sales

Product_id Product_name Price

1 Laptop 50000

2 Shirt 500

3 Watch 700

4 Mobile 20000

5 Keyboard 1800

6 Mobile 18000

Now let us find out the average of all prices of the products using the AVG() function.

1. SELECT AVG(Price) FROM sales;

Output:
AVG(Price)

15166

Now let us find the average price of only mobiles by using the WHERE clause in combination
with AVG() function.

1. SELECT AVG(Price) FROM sales WHERE Product_name = 'Mobile';

Output:

AVG(Price)

19000

4. MIN():

This function produces the lowest value in a column for a group of rows that satisfy a given
criterion. The Syntax of the MIN() function is as follows

Syntax:

1. SELECT MIN(column_name) FROM table_name WHERE condition;

Let us consider the below employees table to illustrate the functioning of the MIN function.

employees

emp_id emp_name salary department

155 Hafeez 40000 Sales

156 Krishna 25000 Marketing

157 Kalyan 20000 R&D


158 Kaveri 50000 R&D

159 Lavanya 60000 HR

160 Hrithik 12000 Marketing

Now let us apply the MIN function to find out the minimum value in the salary column.

1. SELECT MIN(salary) FROM employees;

output:

MIN(salary)

12000

Now let us find us find out the minimum salary from the R&D department.

1. SELECT MIN(salary) FROM employees WHERE department = 'R&D';

Output:

MIN(salary)

20000

5. MAX()

The MAX function in SQL is used to return the highest value in a column for a group of rows
that satisfy a given condition in a table. The MAX syntax is as follows:

Syntax:
1. SELECT MAX(column_name) FROM table_name WHERE condition;

Consider again the employees table to understand the functioning of MAX function.

employees

emp_id emp_name salary department

155 Hafeez 40000 Sales

156 Krishna 25000 Marketing

157 Kalyan 20000 R&D

158 Kaveri 50000 R&D

159 Lavanya 60000 HR

160 Hrithik 12000 Marketing

Now let us find us find out the maximum value in the salary column using MAX() function.

1. select MAX(salary) FROM employees;

Output:

MAX(salary)

60000

Now find out the highest salary of the marketing department by using the WHERE clause in
combination with MAX() function.

1. select MAX(salary) FROM employees WHERE department = 'Marketing';


Output:

MAX(salary)

25000

Nested Subqueries: Nested queries are a way to perform complex queries by embedding one
query within another. The outer query can apply some conditions on the results of the inner
query. Let usl use STUDENT, COURSE, STUDENT_COURSE tables for understanding nested
queries.
STUDENT

S_ID S_NAME S_ADDRESS S_PHONE S_AGE

S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18

COURSE

C_ID C_NAME

C1 DSA

C2 Programming

C3 DBMS

STUDENT_COURSE

S_ID C_ID

S1 C1
S_ID C_ID

S1 C3

S2 C1

S3 C2

S4 C2

S4 C3

EXAMPLE IN SQL CODE:


SELECT StudentName
FROM Students
WHERE StudentID IN (
SELECT StudentID
FROM Grades
WHERE Subject = ‘Mathematics’ AND Score > 90
);

SQL JOIN

JOIN means to combine something. In case of SQL, JOIN means "to combine two or more
tables".

In SQL, JOIN clause is used to combine the records from two or more tables in a database.

Types of SQL JOIN


1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN

Sample Table

EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT

PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.

Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN

The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

3. RIGHT JOIN

In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the
matched values from the left table. If there is no matching in both tables, it will return NULL.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have
all the records from both tables. It puts NULL on the place of matches not found.

ADVERTISEMENT

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

SQL JOIN

As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".

In SQL, JOIN clause is used to combine the records from two or more tables in a database.

Types of SQL JOIN


1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN

Sample Table

EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

3 Christian Denver 100000 42

4 Kristen Washington 500000 29

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT

ADVERTISEMENT

PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

1. INNER JOIN

In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN

The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

3. RIGHT JOIN

In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the
matched values from the left table. If there is no matching in both tables, it will return NULL.

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN

In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have
all the records from both tables. It puts NULL on the place of matches not found.

ADVERTISEMENT

Syntax

1. SELECT table1.column1, table1.column2, table2.column1,....


2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;

Query

1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

Views: SQL provides the concept of VIEW, which hides the complexity of the data and restricts
unnecessary access to the database. It permits the users to access only a particular column
rather than the whole data of the table.

The View in the Structured Query Language is considered as the virtual table, which depends
on the result-set of the predefined SQL statement.

Create a SQL View

You can easily create a View in Structured Query Language by using the CREATE VIEW
statement. You can create the View from a single table or multiple tables.

Syntax to Create View from Single Table

1. CREATE VIEW View_Name AS


2. SELECT Column_Name1, Column_Name2, ....., Column_NameN
3. FROM Table_Name
4. WHERE condition;

In the syntax, View_Name is the name of View you want to create in SQL. The SELECT command
specifies the rows and columns of the table, and the WHERE clause is optional, which is used to
select the particular record from the table.

Syntax to Create View from Multiple Tables

You can create a View from multiple tables by including the tables in the SELECT statement.

1. REATE VIEW View_Name AS


2. SELECT Table_Name1.Column_Name1, Table_Name1.Column_Name2, Table_Name2.Column_
Name2, ....., Table_NameN.Column_NameN
3. FROM Table_Name1, Table_Name2, ....., Table_NameN
4. WHERE condition;
Sql datatypes:
An SQL developer must be aware of what type of data will be stored inside each column while
creating a table. The data type guideline for SQL is to understand what type of data is
expected inside each column and it also identifies how SQL will interact with the stored data.
For every database, data types are primarily classified into three categories.
 Numeric Datatypes
 Date and Time Database
 String Database
Like in other programming languages, SQL also has certain datatypes available. A brief idea of
all the datatypes is discussed below.
Numeric Data Types in MYSQL
Exact Numeric Datatype
There are nine subtypes which are given below in the table. The table contains the range of
data in a particular type.
Data Type From To

BigInt -263 (-9,223,372,036,854,775,808) 263 -1 (9,223,372,036,854,775,807)

Int -231 (-2,147,483,648) 231-1 (2,147,483,647)

smallint -215 (-32,768) 215-1 (32,767)

tinyint 0 28-1 (255)


Data Type From To

bit 0 1

decimal -1038+1 1038-1

numeric -1038+1 1038-1

money -922,337,203,685,477.5808 922,337,203,685,477.5807

smallmoney -214,748.3648 214,748.3647

Approximate Numeric Datatype


The subtypes of this datatype are given in the table with the range.
Data Type From To

Float -1.79E+308 1.79E+308

Real -3.40E+38 3.40E+38

String Data Types in MYSQL


Character String Datatype
The subtypes are given in below table –
Data Type Description

The maximum length of 8000 characters.(Fixed-Length non-Unicode


char
Characters)

The maximum length of 8000 characters.(Variable-Length non-Unicode


varchar
Characters)

The maximum length of 231 characters(SQL Server 2005 only).(Variable


varchar(max)
Length non-Unicode data)

The maximum length of 2,127,483,647 characters(Variable Length non-


text
Unicode data)
Unicode Character String Datatype
The details are given in below table –
Data Type Description

nchar The maximum length of 4000 characters(Fixed-Length Unicode Characters)

The maximum length of 4000 characters.(Variable-Length Unicode


Nvarchar
Characters)

The maximum length of 231 characters(SQL Server 2005 only).(Variable


nvarchar(max)
Length Unicode data)

Server String Data Type in SQL


There are four subtypes of this datatype which are given below:
Datatypes Description

Binary The maximum length of 8000 bytes(Fixed-Length binary data)

varbinary The maximum length of 8000 bytes(Variable Length binary data)

The maximum length of 231 bytes(SQL Server 2005 only).(Variable Length


varbinary(max)
binary data)

text Maximum Length of 2,147,483,647 bytes(Variable Length binary data)

Server Date and Time Data Type in SQL


The details are given in the below table.
Data Type Description

DATE A data type is used to store the data of date in a record

TIME A data type is used to store the data of time in a record

DATETIME A data type is used to store both the data,date, and time in the record.

Other Data Types


XML Datatype
XML data type allows storage of XML documents and fragments in a SQL Server database
DataType Description

XML Datatype A Datatype used to store data in the format of XML datatype

Spatial Dataype
A datatype is used for storing planar spatial data, such as points, lines, and polygons, in a
database table.
DataType Description

A datatype is used for storing planar spatial data, such as points, lines, and
Geometry
polygons, in a database table.

Triggers: A Trigger in Structured Query Language is a set of procedural statements which are
executed automatically when there is any response to certain events on the particular table in
the database. Triggers are used to protect the data integrity in the database.

In SQL, this concept is the same as the trigger in real life. For example, when we pull the gun
trigger, the bullet is fired.

In Structured Query Language, triggers are called only either before or after the below events:

1. INSERT Event: This event is called when the new row is entered in the table.
2. UPDATE Event: This event is called when the existing record is changed or modified in
the table.
3. DELETE Event: This event is called when the existing record is removed from the table.

Types of Triggers in SQL

Following are the six types of triggers in SQL:

1. AFTER INSERT Trigger


This trigger is invoked after the insertion of data in the table.
2. AFTER UPDATE Trigger
This trigger is invoked in SQL after the modification of the data in the table.
3. AFTER DELETE Trigger
This trigger is invoked after deleting the data from the table.
4. BEFORE INSERT Trigger
This trigger is invoked before the inserting the record in the table.
5. BEFORE UPDATE Trigger
This trigger is invoked before the updating the record in the table.
6. BEFORE DELETE Trigger
This trigger is invoked before deleting the record from the table.

Syntax of Trigger in SQL


1. CREATE TRIGGER Trigger_Name
2. [ BEFORE | AFTER ] [ Insert | Update | Delete]
3. ON [Table_Name]
4. [ FOR EACH ROW | FOR EACH COLUMN ]
5. AS
6. Set of SQL Statement

Example of Trigger in SQL

To understand the concept of trigger in SQL, first, we have to create the table on which trigger
is to be executed.

The following query creates the Student_Trigger table in the SQL database:

1. CREATE TABLE Student_Trigger


2. (
3. Student_RollNo INT NOT NULL PRIMARY KEY,
4. Student_FirstName Varchar (100),
5. Student_EnglishMarks INT,
6. Student_PhysicsMarks INT,
7. Student_ChemistryMarks INT,
8. Student_MathsMarks INT,
9. Student_TotalMarks INT,
10. Student_Percentage );

The following query shows the structure of theStudent_Trigger table:

1. DESC Student_Trigger;

You might also like