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

SQLPDF

Uploaded by

ganeshvinnakota6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

SQLPDF

Uploaded by

ganeshvinnakota6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

SQL (Structured query language)

Overview of DBMS
DAY-1: Introduction
o SQL stands for Structured Query Language. It is used for storing and managing data in relational
database management system (RDMS).
o It is a standard language for Relational Database System. It enables a user to create, read, update and
delete relational databases and tables.
o All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their standard
database language.
o SQL allows users to query the database in a number of ways, using English-like statements.

SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is known as relation
and row as tuple.

Table is the simple form of data storage. A table is also considered as a convenient representation of relations.

Let's see an example of an employee table:

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000

In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY" are the column
names. The combination of data of multiple columns forms a row e.g., "Ankit", "Lucknow" and 15000 are the
data of one row.

SQL TABLE Variable


The SQL Table variable is used to create, modify, rename, copy and delete tables. Table variable was introduced
by Microsoft.

It was introduced with SQL server 2000 to be an alternative of temporary tables.

It is a variable where we temporary store records and results. This is same like temp table but in the case of
temp table we need to explicitly drop it.
Table variables are used to store a set of records. So, declaration syntax generally looks like CREATE TABLE
syntax.

1. create table "table name"


2. ("column1" "data type",
3. "column2" "data type",
4. ...
5. "Column N" "data type");

When a transaction rolled back the data associated with table variable is not rolled back.

A table variable generally uses lesser resources than a temporary variable.

Table variable cannot be used as an input or an output parameter.

Features

1. Now, let's discuss some of the features of SQL. It is extremely manageable and simple to learn the

language. SQL is flexible as it works with information base frameworks from Oracle, IBM,

Microsoft, and so forth. Also, it is an ANSI and ISO standard language for information base creation and

control.

2. There are other features moreover like it is quick in recovering a lot of information proficiently. It has a

very much characterized structure as it utilizes since quite a while ago settled guidelines and it lets you

oversee databases without knowing part of coding.

Applications of SQL
Here, we will see some applications of SQL that render it so valuable in a data-driven world where governing
massive databases is the criterion of the day.

 SQL is used as a Data Definition Language (DDL) which means you can autonomously make a database,
characterize its structure, use it and afterwards dispose of it when you are finished with it. It is
additionally conveyed as a Data Control Language (DCL) which determines how you can ensure your
information base against debasement and misuse.

 SQL is used as a Data Manipulation Language (DML) which implies you can use it for keeping up a

previously existing database. Hence, it is an incredible language for entering information, changing

information, and separating information with respect to a database.


 It is broadly used as a client or Server language to interface the front-end with the back-end

consequently supporting the customer or worker architecture. Likewise, it can be used in the three-

level design of a customer, an application worker, and a database which characterizes the Internet

architecture.

SQL DATABASE
 SQL create database
 SQL drop database
 SQL rename database
 SQL select database

SQL Create Database:

In SQL, the 'Create Database' statement is a first step for storing the structured data in the database.

The database developers and the users use this statement in SQL for creating the new database in the database
systems. It creates the database with the name which has been specified in the Create Database statement.

Syntax of Create Database statement in SQL


1. CREATE DATABASE Database_Name;

In this syntax, Database_Name specifies the name of the database which we want to create in the system. We
have to type the database name in query just after the 'Create Database' keyword.

Following are the most important points which are required to learn while creating a database:

o The database we want to create should be a simple and unique name, which can be easily identified.
o Database name should be no more than 128 characters.

SQL DROP Database

The SQL Drop Database statement deletes the existing database permanently from the database system. This
statement deletes all the views and tables if stored in the database, so be careful while using this query in SQL.

Following are the most important points which are required to learn before removing the database from the
database system:
o This statement deletes all the data from the database. If you want to restore the deleted data in the
future, you should keep the backup of data of that database which you want to delete.
o Another most important point is that you cannot delete that database from the system which is currently
in use by another database user. If you do so, then the drop statement shows the following error on
screen:

Syntax of Drop Database Statement in SQL


1. DROP DATABASE Database_Name;

In this SQL syntax, we have to specify the name of that database which we want to delete permanently
from the database system.

DROP DATABASE Database_Name1, [ Database_Name2, ......., Database_NameN];

Using this statement, we have no need to write multiple statements for deleting multiple databases. We can
specify all the databases by using a comma in a single statement, as shown in the above syntax.

SQL RENAME Database

In some situations, database users and administrators want to change the name of the database for some
technical reasons. So, the Rename Database statement in SQL is used to change the name of the existing
database.

Sometimes, the Rename Database statement is used because the developers think that the original name is not
more relevant to the data of the database, or they want to give a temporary name to that database.

Syntax of Rename Database in SQL


1. ALTER DATABASE old_database_name MODIFY NAME = new_database_name;
EXEC sp_renamedb'old_database_name’, 'new_database_name'

This syntax is used when we want to change the name of the database in MySQL.

SQL SELECT Database

Suppose database users and administrators want to perform some operations on tables, views, and indexes on
the specific existing database in SQL. Firstly, they have to select the database on which they want to run the
database queries.

Any database user and administrator can easily select the particular database from the current database server
using the USE statement in SQL.
Syntax of USE statement in SQL
USE database name;

In this syntax, we have to define the name of the database after the USE keyword and the name of the database
must be unique.

Syntax of USE statement in MySQL


1. USE database name;

Entity Relationship (ER) Diagram


ER Diagram stands for Entity Relationship Diagram, also known as ERD is a diagram that displays the relationship of entity sets

stored in a database. In other words, ER diagrams help to explain the logical structure of databases. ER diagrams are created

based on three basic concepts: entities, attributes and relationships.


ER Diagrams contain different symbols that use rectangles to represent entities, ovals to define attributes and diamond
shapes to represent relationships.

At first look, an ER diagram looks very similar to the flowchart. However, ER Diagram includes many specialized symbols, and
its meanings make this model unique. The purpose of ER Diagram is to represents the entity infrastructural.

What is ER Model?
ER Model stands for Entity Relationship Model is a high-level conceptual data model diagram. ER model helps
to systematically analyze data requirements to produce a well-designed database. The ER Model represents
real-world entities and the relationships between them. Creating an ER Model in DBMS is considered as a best
practice before implementing your database.
ER Modeling helps you to analyze data requirements systematically to produce a well-designed database. So,
it is considered a best practice to complete ER modeling before implementing your database.

Following are the main components and its symbols in ER Diagrams:

 Rectangles: This Entity Relationship Diagram symbol represents entity types


 Ellipses: Symbol represent attributes
 Diamonds: This symbol represents relationship types
 Lines: It links attributes to entity types and entity types with other relationship types
 Primary key: attributes are underlined
 Double Ellipses: Represent multi-valued attributes
Components of the ER Diagram
This model is based on three basic concepts:

 Entities
 Attributes
 Relationships

ER Diagram Examples

For example, in a university database, we might have entities for Students, Courses, and Lecturers. Students’
entity can have attributes like Rollno, Name, and DeptID. They might have relationships with Courses and
Lecturers.

ENTITY
A real-world thing either living or non-
living that is easily recognizable and
nonrecognizable. It is anything in the
enterprise that is to be represented in our
database. It may be a physical thing or
simply a fact about the enterprise or an
event that happens in the real world.

An entity can be place, person, object,


event or a concept, which stores data in
the database. The characteristics of
entities are must have an attribute, and a
unique key. Every entity is made up of
some ‘attributes’ which represent that
entity.
Examples of entities:
 Person: Employee, Student, Patient
 Place: Store, Building
 Object: Machine, product, and Car
 Event: Sale, Registration, Renewal
 Concept: Account, Course

Notation of an Entity

Entity set:
Student

An entity set is a group of similar kind of entities. It may contain entities with attribute sharing similar values.
Entities are represented by their properties, which also called attributes. All attributes have their separate
values. For example, a student entity may have a name, age, class, as attributes.

Example of Entities:

A university may have some departments. All these departments employ various lecturers and offer several
programs.

Some courses make up each program. Students register in a particular program and enroll in various courses.
A lecturer from the specific department takes each course, and each lecturer teaches a various group of
students.

Relationship

Relationship is nothing but an association among two or more entities. E.g., Tom works in the Chemistry
department.
Entities take part in relationships. We can often identify relationships with verbs or verb phrases.

For example:

 You are attending this lecture


 I am giving the lecture
 Just loke entities, we can classify relationships according to relationship-types:
 A student attends a lecture
 A lecturer is giving a lecture.

DAY 2:

Weak Entities
A weak entity is a type of entity which doesn’t have its key attribute. It can be identified uniquely by
considering the primary key of another entity. For that, weak entity sets need to have participation.
Attributes
It is a single-valued property of either an entity-type or a relationship-type.

For example, a lecture might have attributes: time, date, duration, place, etc.

An attribute in ER Diagram examples, is represented by an Ellipse


Cardinality
Defines the numerical attributes of the relationship between two entities or entity sets.

Different types of cardinal relationships are:

 One-to-One Relationships
 One-to-Many Relationships
 May to One Relationships
 Many-to-Many Relationships
1.One-to-one:
One entity from entity set X can be associated with at most one entity of entity set Y and vice versa.

Example: One student can register for numerous courses. However, all those courses have a single line back to
that one student.

2.One-to-many:
One entity from entity set X can be associated with multiple entities of entity set Y, but an entity from entity
set Y can be associated with at least one entity.

For example, one class is consisting of multiple students.

3. Many to One
More than one entity from entity set X can be associated with at most one entity of entity set Y. However, an
entity from entity set Y may or may not be associated with more than one entity from entity set X.

For example, many students belong to the same class.


4. Many to Many:
One entity from X can be associated with more than one entity from Y and vice versa.

For example, Students as a group are associated with multiple faculty members, and faculty members can be
associated with multiple students.

How to draw an Entity Relationship Diagram (ERD )


Now in this ERD Diagram Tutorial, we will learn how to create an ER Diagram. Following are the steps to create
an ER Diagram:

Steps to Create an
ER Diagram

Let’s study them with an Entity Relationship Diagram Example:

In a university, a student enrolls in Courses. A student must be assigned to at least one or more Courses. Each
course is taught by a single Professor. To maintain instruction quality, a professor can deliver only one course
Step 1) Entity Identification
We have three entities

 Student
 Course
 Professor

Step 2) Relationship Identification


We have the following two relationships

 The student is assigned a course


 Professor delivers a course

Step 3) Cardinality Identification


For them problem statement we know that,

 A student can be assigned multiple courses


 A Professor can deliver only one course
Step 4) Identify Attributes
You need to study the files, forms, reports, data currently maintained by the organization to identify
attributes. You can also conduct interviews with various stakeholders to identify entities. Initially, it’s
important to identify the attributes without mapping them to a particular entity.

Once, you have a list of Attributes, you need to map them to the identified entities. Ensure an attribute is to
be paired with exactly one entity. If you think an attribute should belong to more than one entity, use a
modifier to make it unique.

Once the mapping is done, identify the primary Keys. If a unique key is not readily available, create one.

Step 5) Create the ER Diagram


A more modern representation of Entity Relationship Diagram Example

Best Practices for Developing Effective ER Diagrams


Here are some best practice or example for Developing Effective ER Diagrams.

 Eliminate any redundant entities or relationships


 You need to make sure that all your entities and relationships are properly labeled
 There may be various valid approaches to an ER diagram. You need to make sure that the ER diagram
supports all the data you need to store
 You should assure that each entity only appears a single time in the ER diagram
 Name every relationship, entity, and attribute are represented on your diagram
 Never connect relationships to each other
 You should use colors to highlight important portions of the ER diagram

DAY 3:
INSTALL MYSQL IN WINDOWS

MySQL is one of the most popular relational database management software that is widely used in today's
industry. It provides multi-user access support with various storage engines. It is backed by Oracle Company

Step 1: Go to the official website


of MySQL and download the community server edition software. Here, you will see the option to choose the
Operating System, such as Windows.

Step 2: Next, there are two options available to download the setup. Choose the version number for the MySQL
community server, which you want. If you have good internet connectivity, then choose the MySQL-installer-
web-community. Otherwise, choose the other one.

Step 3: After downloading the setup, unzip it anywhere and double click the MSI installer .exe file. It will give
the following screen:

Step 4: In the next wizard, choose the Setup Type. There are several types available, and you need to choose
the appropriate option to install MySQL product and features

. Here, we are going to select the Full option and click on the Next button.

This option will install the following things: MySQL Server, MySQL Shell, MySQL Router, MySQL Workbench

, MySQL Connectors, documentation, samples and examples, and many more.

Step 5: Once we click on the Next button, it may give information about some features that may fail to install
on your system due to a lack of requirements. We can resolve them by clicking on the Execute button that will
install all requirements automatically or can skip them. Now, click on the Next button.
Step 6: In the next wizard, we will see a dialog box that asks for our confirmation of a few products not getting
installed. Here, we have to click on the Yes button.

After clicking on the Yes button, we will see the list of the products which are going to be installed. So, if we
need all products, click on the Execute button.
Step 7: Once we click on the Execute button, it will download and install all the products. After completing the
installation, click on the Next button.

button.

Step 8: In the next wizard, we need to configure the MySQL Server and Router. Here, I am not going to configure
the Router because there is no need to use it with MySQL. We are going to show you how to configure the
server only. Now, click on the Next button.
Step 9: As soon as you will click on the Next button, you can see the screen below. Here, we have to configure
the MySQL Server. Now, choose the Standalone MySQL Server/Classic MySQL Replication option and click on
Next. Here, you can also choose the InnoDB Cluster based on your needs.

Step 10: In the next screen, the system will ask you to choose the Config Type and other connectivity options.
Here, we are going to select the Config Type as 'Development Machine' and Connectivity as TCP/IP, and Port
Number is 3306, then click on Next.

Step 11: Now, select the Authentication Method and click on Next. Here, I am going to select the first option.
Step 12: The next screen will ask you to mention the MySQL Root Password. After filling the password details,
click on the Next button.

Step 13: The next screen will ask you to configure the Windows Service to start the server. Keep the default
setup and click on the Next button.

button.
Step 14: In the next wizard, the system will ask you to apply the Server Configuration. If you agree with this
configuration, click on the Execute button.
Step 15: Once the configuration has completed, you will get the screen below. Now, click on the Finish button

to continue

Step 16: In the next screen, you can see that the Product Configuration is completed. Keep the default setting
and click on the Next-> Finish button to complete the MySQL package installation.

Step 17: In the next wizard, we can choose to configure the Router. So, click on Next->Finish and then click the
Next button.
Step 18: In the next wizard, we will see the Connect to Server option. Here, we have to mention the root
password, which we had set in the previous steps.

In this screen, it is also required to check about the connection is successful or not by clicking on the Check
button. If the connection is successful, click on the Execute button. Now, the configuration is complete, click on
Next.

Step 19: In the next wizard, select the applied configurations and click on the Execute button.
Step 20: After completing the above step, we will get the following screen. Here, click on the Finish button.

Step 21: Now, the MySQL installation is complete. Click on the Finish button.
Verify MySQL installation

DAY 4:
ADVANTAGES OF T-SQL
T-SQL is known as Transact Structured Query Language, which is the product of Microsoft.

TSQL has several advantages that make this language popular and easy to use. T_SQL is reliable in nature and
an efficient language that helps to establish communication with the relational database. Some of the
common advantages of T-SQL are mentioned below:

1. Processing of query is fast – The T-SQL language is capable of processing huge chunks of data very fast
and also helps the data administrator to fetch the data from the database. All the data-related
operations like deletion, insertion, and manipulation can be easily performed without taking much
time.
2. Secure transaction – Data access from the database is secure in nature and also uniform in nature. All
the business policies and business rules are present in encapsulated form.
3. No extra knowledge– The T-SQL language is easy to use and no additional effort is required by the data
administrator for the data retrieval process from the database. The T-SQL language supports all the
necessary operations like INSERT, SELECT, UPDATE, and many more.
4. Interactive in nature – The T-SQL language is interactive in nature as the language is capable of writing
complex business rules to fetch the data from the database. The T-SQL language is easy to use and easy
to understand.
5. User-defined function – One of the major advantages of the T-SQL language is providing functionality
to defined user-defined functions that help to form the structure for the transactions which can be
used in different platforms like e-commerce platform that helps to fetch the data in an efficient
manner.
6. Less -effort – The T-SQL language provides the functionality to write the program in which all
commands are submitted to the server in one go that helps to save time.

OLAP (Online Analytical Processing)

OLAP stands for On-Line Analytical Processing. OLAP is a classification of software technology which authorizes
analysts, managers, and executives to gain insight into information through fast, consistent, interactive access
in a wide variety of possible views of data that has been transformed from raw information to reflect the real
dimensionality of the enterprise as understood by the clients.

OLAP implement the multidimensional analysis of business information and support the capability for complex
estimations, trend analysis, and sophisticated data modeling. It is rapidly enhancing the essential foundation for
Intelligent Solutions containing Business Performance Management, Planning, Budgeting, Forecasting, Financial
Documenting, Analysis, Simulation-Models, Knowledge Discovery, and Data Warehouses Reporting. OLAP
enables end-clients to perform ad hoc analysis of record in multiple dimensions, providing the insight and
understanding they require for better decision making.

1. Multidimensional conceptual view: OLAP systems let business users have a dimensional and logical view
of the data in the data warehouse. It helps in carrying slice and dice operations.
2. Multi-User Support: Since the OLAP techniques are shared, the OLAP operation should provide normal
database operations, containing retrieval, update, adequacy control, integrity, and security.
3. Accessibility: OLAP acts as a mediator between data warehouses and front-end. The OLAP operations
should be sitting between data sources (e.g., data warehouses) and an OLAP front-end.
4. Storing OLAP results: OLAP results are kept separate from data sources.
5. Uniform documenting performance: Increasing the number of dimensions or database size should not
significantly degrade the reporting performance of the OLAP system.
6. OLAP provides for distinguishing between zero values and missing values so that aggregates are
computed correctly.
7. OLAP system should ignore all missing values and compute correct aggregate values.
8. OLAP facilitate interactive query and complex analysis for the users.
9. OLAP allows users to drill down for greater details or roll up for aggregations of metrics along a single
business dimension or across multiple dimensions.
10. OLAP provides the ability to perform intricate calculations and comparisons.
11. OLAP presents results in a number of meaningful ways, including charts and graphs.

OLTP:
OLTP (On-Line Transaction Processing) is featured by a large number of short on-line transactions (INSERT,
UPDATE, and DELETE). The primary significance of OLTP operations is put on very rapid query processing,
maintaining record integrity in multi-access environments, and effectiveness consistent by the number of
transactions per second. In the OLTP database, there is an accurate and current record, and schema used to
save transactional database is the entity model (usually 3NF).

ADVANTAGES

 Single Platform. OLTP integrates all business analytical needs in a single platform.
 Database Consistency. ...
 Security Restrictions. ...
 Expands Customer Base. ...
 Timely Transaction Modifications. ...
 Large Database Support. ...
 Atomicity. ...
 Facilitates Data Manipulation.

ODS:
The development of the operational data store (ODS) has been driven by business needs. An ODS contains
operational data from different sources with the purpose of providing end-users with an integrated view of
enterprise data. By storing a snapshot of current data, it is ideally suited for real-time or near real-time
decision making and reporting.

An ODS is different from a data warehouse in terms of its update frequency. An ODS is updated daily, hourly,
or even immediately after transactions on operational data. It overwrites operational data as new, current
information comes in.

Main advantages of an ODS

 The ODS offers more accessibility to operational data and handles uncomplicated querying on a small
quantity of data. It may lack the benefits of a data warehouse but it has the advantage of being fast
and light.

 An ODS offers information for operational and tactical decisions based on current or near real-time
data. Data can be used almost immediately when accounting for timing differences from the different
reporting applications.

 The ODS integrates data from new and existing systems, creating a central repository for data. Instead
of limited reporting offered by using source systems, this enables the creation of more comprehensive
operational reports.

 Organizations have a more complete view of various business functions and the current state view
makes it easier to identify and diagnose issues when they happen, such as when a customer order goes
astray.

 Businesses can build rules on an ODS so that data changes in a particular system trigger an action on
another system.
 Only a few people have the security to access systems of record but an ODS does not have the same
security issues and is more resilient to cyber-attacks. More people have access to reporting.

 The ODS can act as an intermediate stage before data goes to the data warehouse. It can put data in a
consistent format and therefore improve the quality of data in the data warehouse.

SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is known as relation
and row as tuple.

Let's see an example of an employee table:

Employee

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000

In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY" are the column
names. The combination of data of multiple columns forms a row e.g., "Ankit", "Lucknow" and 15000 are the
data of one row.

The SQL Table variable is used to create, modify, rename, copy and delete tables. Table variable was introduced
by Microsoft.

SQL CREATE TABLE

SQL CREATE TABLE statement is used to create table in a database.

If you want to create a table, you should name the table and define its column and each column's data type.

Let's see the simple syntax to create the table.

1. create table "table name"


2. ("column1" "data type",
3. "column2" "data type",
4. "column3" "data type",
5. ...
6. "Column N" "data type");
The data type of the columns may vary from one database to another. For example, NUMBER is supported in
Oracle database for integer value whereas INT is supported in MySQL.

Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL are the constraint
showing that these fields cannot be NULL while creating records in the table.

1. SQL> CREATE TABLE STUDENTS (


2. ID INT NOT NULL,
3. NAME VARCHAR (20) NOT NULL,
4. AGE INT NOT NULL,
5. ADDRESS CHAR (25),
6. PRIMARY KEY (ID)
7. );

SYNTAX: Create table name (column name datatypes [….]);

SQL DROP TABLE

A SQL DROP TABLE statement is used to delete a table definition and all data from a table.

This is very important to know that once a table is deleted all the information available in the table is lost forever,
so we have to be very careful when using this command.

syntax to drop the table from the database.

1. DROP TABLE "table name";

SQL DELETE TABLE

The DELETE statement is used to delete rows from a table. If you want to remove a specific row from a table
you should use WHERE condition.

DELETE FROM table name [WHERE condition];

But if you do not specify the WHERE condition it will remove all the rows from the table.

DELETE FROM table name;


There are some more terms similar to DELETE statement like as DROP statement and TRUNCATE statement but
they are not exactly same there are some differences between them.

SQL RENAME TABLE

In some situations, database administrators and users want to change the name of the table in the SQL database
because they want to give a more relevant name to the table.

Any database user can easily change the name by using the RENAME TABLE and ALTER TABLE statement in
Structured Query Language.

The RENAME TABLE and ALTER TABLE syntax help in changing the name of the table.

Syntax of RENAME statement in SQL

RENAME old table _name to new_table_name

SQL TRUNCATE TABLE

A truncate SQL statement is used to remove all rows (complete data) from a table. It is similar to the DELETE
statement with no WHERE clause.

Syntax of TRUNCATE statement in SQL

TRUNCATE TABLE table name;

SQL COPY TABLE

If you want to copy the data of one SQL table into another SQL table in the same SQL server, then it is possible
by using the SELECT INTO statement in SQL.

The SELECT INTO statement in Structured Query Language copies the content from one existing table into the
new table. SQL creates the new table by using the structure of the existing table.

Syntax of SELECT INTO statement in SQL

1. SELECT * INTO New_table_name FROM old_table_name;


SQL ALTER TABLE

The ALTER TABLE statement in Structured Query Language allows you to add, modify, and delete columns of an
existing table. This statement also allows database users to add and remove various SQL constraints on the
existing tables.

Syntax of ALTER TABLE statement in SQL

1. ALTER TABLE name ADD column name column-definition;

SQL PRIMARY KEY


A column or columns is called primary key (PK) that uniquely identifies each row in the table.

If you want to create a primary key, you should define a PRIMARY KEY constraint when you create or modify a
table.

When multiple columns are used as a primary key, it is known as composite primary key.

In designing the composite primary key, you should use as few columns as possible. It is good for storage and
performance both, the more columns you use for primary key the more storage space you require.

EXAMPLE:

CREATE TABLE Employee (

empid INT NOT NULL PRIMARY KEY,

name VARCHAR (20) NOT NULL

dob DATE,

mobile VARCHAR (10) NOT NULL UNIQUE,

address VARCHAR (20)

);

SQL FOREIGN KEY

In the relational databases, a foreign key is a field or a column that is used to establish a link between two tables.

In simple words you can say that, a foreign key in one table used to point primary key in another table.
EXAMPLE:

CREATE TABLE Employee (

empid INT NOT NULL PRIMARY KEY,

name VARCHAR (20) NOT NULL

dob DATE,

mobile VARCHAR (10) NOT NULL UNIQUE,

address VARCHAR (20)

depicted INTFOREIGN KEY REFERENCE Department(depicted)

);

Unique Key in SQL


A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a
database table.

You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate
values.

The unique key and primary key both provide a guarantee for uniqueness for a column or a set of columns.

There is an automatically defined unique key constraint within a primary key constraint.

EXAMPLE

CREATE TABLE Employee (

empid INT NOT NULL name VARCHAR (20) NOT NULL

dob DATE,

mobile VARCHAR (10) NOT NULL UNIQUE,

address VARCHAR (20)


DAY 5:

SQL WHERE CLAUSE AND or NOT


A WHERE clause in SQL is a data manipulation language statement.

WHERE clauses are not mandatory clauses of SQL DML statements. But it can be used to limit the number of
rows affected by a SQL DML statement or returned by a query.

Actually. it filters the records. It returns only those queries which fulfill the specific conditions.

WHERE clause is used in SELECT, UPDATE, DELETE statement etc.

SYNTAX

1. SELECT column1, column 2, ... column n


2. FROM table name
3. WHERE [conditions]

= equal

> greater than

< less than

>= greater than or equal

<= less than or equal

<> not equal to

SQL AND

o The SQL AND condition are used in SQL query to create two or more conditions to be met.
o It is used in SQL SELECT, INSERT, UPDATE and DELETE
o Let's see the syntax for SQL AND:
o SELECT columns FROM tables WHERE condition 1 AND condition 2;
o The SQL AND condition require that both conditions should be met.
o The SQL AND condition also can be used to join multiple tables in a SQL statement.
o To understand this concept practically, let us see some examples.
Query:

mysql> SELECT *FROM emp WHERE Department = "IT" AND Location = "Chennai";

SQL Commands

o SQL commands are instructions. It is used to communicate with the database. It is also used to perform
specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table,
set permission for users.

Types of SQL Commands

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL)


o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
o All the command of DDL is auto-committed that means it permanently save all the changes in the
database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the database.

1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,.]);

Example:

CREATE TABLE EMPLOYEE (Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE table name;

Example

DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be either to modify the
characteristics of an existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

ALTER TABLE name ADD column name COLUMN-definition;

To modify existing column in the table:

ALTER TABLE name MODIFY (column definitions....);

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD (ADDRESS VARCHAR2(20));


2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.

Syntax:

TRUNCATE TABLE table name;


Example:

TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language

o DML commands are used to modify the database. It is responsible for all form of changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all the changes in the
database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

Syntax:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3, col N)
3. VALUES (value1, value2, value3, .... value N);

Or

1. INSERT INTO TABLE_NAME


2. VALUES (value1, value2, value3, .... value N);

For example:

INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table name SET [column_name1= value1, column_nameN = value] [WHERE CONDITION]

For example:

1. UPDATE students
2. SET Username = 'Sonoo'
3. WHERE Student_Id = '3'
c. DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];

For example:

1. DELETE FROM javatpoint


2. WHERE Author="Sonoo";

3. Data Control Language


DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language


TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used while creating
tables or dropping them.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.

Syntax:

1. ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;

SQL Data Types


Data types are used to represent the nature of the data that can be stored in the database table. For example,
in a particular column of a table, if we want to store a string type of data then we will have to declare a string
data type of this column.

Data types mainly classified into three categories for every database.

1. String Data types


2. Numeric Data types
3. Date and time Data types

1.STRING DATA TYPES


CHAR(Size) It is used to specify a fixed length string that can contain numbers, letters,
and special characters. Its size can be 0 to 255 characters. Default is 1.

VARCHAR(Size) It is used to specify a variable length string that can contain numbers, letters,
and special characters. Its size can be from 0 to 65535 characters.

BINARY(Size) It is equal to CHAR () but stores binary byte strings. Its size parameter
specifies the column length in the bytes. Default is 1.

VARBINARY(Size) It is equal to VARCHAR () but stores binary byte strings. Its size parameter
specifies the maximum column length in bytes.

TEXT(Size) It holds a string that can contain a maximum length of 255 characters.

TINYTEXT It holds a string with a maximum length of 255 characters.

MEDIUMTEXT It holds a string with a maximum length of 16,777,215.

LONGTEXT It holds a string with a maximum length of 4,294,967,295 characters.

ENUM (val1, val2, It is used when a string object having only one value, chosen from a list of
val3,) possible values. It contains 65535 values in an ENUM list. If you insert a value
that is not in the list, a blank value will be inserted.

SET (val1, val2, It is used to specify a string that can have 0 or more values, chosen from a
val3,....) list of possible values. You can list up to 64 values at one time in a SET list.

BLOB (size) It is used for BLOBs (Binary Large Objects). It can hold up to 65,535 bytes.

2.MySQL Numeric Data Types

BIT(Size) It is used for a bit-value type. The number of bits per value is specified in size. Its
size can be 1 to 64. The default value is 1.

INT (size) It is used for the integer value. Its signed range varies from -2147483648 to
2147483647 and unsigned range varies from 0 to 4294967295. The size parameter
specifies the max display width that is 255.

INTEGER (size) It is equal to INT (size).

FLOAT (size, d) It is used to specify a floating-point number. Its size parameter specifies the total
number of digits. The number of digits after the decimal point is specified
by d parameter.

FLOAT(p) It is used to specify a floating-point number. MySQL used p parameter to


determine whether to use FLOAT or DOUBLE. If p is between 0 to24, the data type
becomes FLOAT (). If p is from 25 to 53, the data type becomes DOUBLE ().
DOUBLE (size, It is a normal size floating point number. Its size parameter specifies the total
d) number of digits. The number of digits after the decimal is specified by d
parameter.

DECIMAL (size, It is used to specify a fixed-point number. Its size parameter specifies the total
d) number of digits. The number of digits after the decimal parameter is specified
by d parameter. The maximum value for the size is 65, and the default value is 10.
The maximum value for is 30, and the default value is 0.

DEC (size, d) It is equal to DECIMAL (size, d).

BOOL It is used to specify Boolean values true and false. Zero is considered as false, and
nonzero values are considered as true.

MySQL Date and Time Data Types

DATE It is used to specify date format YYYY-MM-DD. Its supported range is from '1000-
01-01' to '9999-12-31'.

DATETIME (fsp) It is used to specify date and time combination. Its format is YYYY-MM-DD
hh:mm: ss. Its supported range is from '1000-01-01 00:00:00' to 9999-12-31
23:59:59'.

TIMESTAMP It is used to specify the timestamp. Its value is stored as the number of seconds
(fsp) since the Unix epoch ('1970-01-01 00:00:00' UTC). Its format is YYYY-MM-DD
hh:mm:ss. Its supported range is from '1970-01-01 00:00:01' UTC to '2038-01-
09 03:14:07' UTC.

TIME (fsp) It is used to specify the time format. Its format is hh:mm:ss. Its supported range
is from '-838:59:59' to '838:59:59'

YEAR It is used to specify a year in four-digit format. Values allowed in four-digit format
from 1901 to 2155, and 0000.

SQL Operators
Every database administrator and user use SQL queries for manipulating and accessing the data of database
tables and views.

The manipulation and retrieving of the data are performed with the help of reserved words and characters,
which are used to perform arithmetic operations, logical operations, comparison operations, compound
operations, etc.

The SQL reserved words and characters are called operators, which are used with a WHERE clause in a SQL
query. In SQL, an operator can either be a unary or binary operator. The unary operator uses only one operand
for performing the unary operation, whereas the binary operator uses two operands for performing the binary
operation.
Syntax of Unary SQL Operator

1. Operator SQL Operand

SQL Operator Symbols Operators

** Exponentiation operator

+, - Identity operator, Negation operator

*, / Multiplication operator, Division operator

+, -, || Addition (plus) operator, subtraction (minus) operator, String Concatenation


operator

=, =, <, >, <=, >=, IS NULL, LIKE, Comparison Operators


BETWEEN, IN

NOT Logical negation operator

&& or AND Conjunction operator

OR Inclusion operator

Types of Operators

SQL operators are categorized in the following categories:

1. SQL Arithmetic Operators


2. SQL Comparison Operators
3. SQL Logical Operators
4. SQL Set Operators
5. SQL Bit-wise Operators
6. SQL Unary Operators

SQL Arithmetic Operators

The Arithmetic Operators perform the mathematical operation on the numerical data of the SQL tables. These
operators perform addition, subtraction, multiplication, and division operations on the numerical operands.

Following are the various arithmetic operators performed on the SQL data:

1. SQL Addition Operator (+)


2. SQL Subtraction Operator (-)
3. SQL Multiplication Operator (+)
4. SQL Division Operator (-)
5. SQL Modulus Operator (+)

SQL Comparison Operators

The Comparison Operators in SQL compare two different data of SQL table and check whether they are the
same, greater, and lesser. The SQL comparison operators are used with the WHERE clause in the SQL queries

Following are the various comparison operators which are performed on the data stored in the SQL database
tables:

1. SQL Equal Operator (=)


2. SQL Not Equal Operator (! =)
3. SQL Greater Than Operator (>)
4. SQL Greater Than Equals to Operator (>=)
5. SQL Less Than Operator (<) \
6. SQL Less Than Equals to Operator (<=)

SQL Logical Operators

The Logical Operators in SQL perform the Boolean operations, which give two results True and False. These
operators provide True value if both operands match the logical condition.

Following are the various logical operators which are performed on the data stored in the SQL database
tables:

1. SQL ALL operator


2. SQL AND operator
3. SQL OR operator
4. SQL BETWEEN operator
5. SQL IN operator
6. SQL NOT operator
7. SQL ANY operator
8. SQL LIKE operator

SQL Set Operators

The Set Operators in SQL combine a similar type of data from two or more SQL database tables. It mixes the
result, which is extracted from two or more SQL queries, into a single result.
Set operators combine more than one selects statement in a single query and return a specific result set.

Following are the various set operators which are performed on the similar data stored in the two SQL
database tables:

1. SQL Union Operator


2. SQL Union ALL Operator
3. SQL Intersect Operator
4. SQL Minus Operator

SQL Bitwise Operators

The Bitwise Operators in SQL perform the bit operations on the Integer values. To understand the performance
of Bitwise operators, you just knew the basics of Boolean algebra.

Following are the two important logical operators which are performed on the data stored in the SQL
database tables:

1. Bitwise AND (&)


2. Bitwise OR (|)

Bitwise AND (&)

The Bitwise AND operator performs the logical AND operation on the given Integer values. This operator checks
each bit of a value with the corresponding bit of another value.

Syntax of Bitwise AND Operator

1. SELECT column1 & column2 & .... & columnN FROM table_Name [WHERE conditions];

SQL Unary Operators

The Unary Operators in SQL perform the unary operations on the single data of the SQL table, i.e., these
operators operate only on one operand.

These types of operators can be easily operated on the numeric data value of the SQL table.

Following are the various unary operators which are performed on the numeric data stored in the SQL table:

1. SQL Unary Positive Operator


2. SQL Unary Negative Operator
3. SQL Unary Bitwise NOT Operator

DAY 6:
MY SQL BUILT IN FUNCTIONS (STRINGS, DATE, NUMERIC)
Built in functions are functions that are shipped with MySQL. They can be categorized according to the data
types that they operate on i.e., strings, date and numeric built-in functions. Stored functions are created by
the user within MySQL server and can be used in SQL statements

MySQL String Functions:

Function Description
SUBSTRING Extracts a substring from a string (starting at any
position)
SUBSTRING_INDEX Returns a substring of a string before a specified
number of delimiters occurs
TRIM Removes leading and trailing spaces from a string
UCASE Converts a string to upper-case
MY SQL DATE FUNCTIONS:

MySQL date/time functions are used to manipulate temporal values. The following table indicates each of the
functions with a brief description:

Functions Description

date () The date () function is used to get the date from given date/datetime.

adddata () The add data () function is used to get the date in which some time/date
intervals are added.

curdate() The curdate() function is used to get the current date.

current_date() The current_date() function is used to get the current date.

date_add() The date_add() function is used to get the date in which some
date/datetime intervals are added.

date_format() The date_format() function is used to get the date in specified format.
datediff() The datediff() function is used to get the difference between the two
specified date values.

day () The day () function is used to get the day from the given date.

dayname() The dayname() function is used to get the name of the day from the
given date.

dayofmonth() The dayofmonth() function is used to get the day for the specified date.

dayofweek() The dayofweek() function is used to get the day of the week in numeric.

dayofyear() The dayofyear() function is used to get the number of day in the year.

from_days() The from_days() function is used to get the date of the given number of
days.

hour () The hour () function is used to get the hour from the given datetime.

addtime() The addtime() function is used to get the time/datetime value in which
some time intervals are added.

current_time() The current_time() function is used to get the current time.

current_timestamp() The current_timestamp() function is used to get the current date and
time.

curtime() The curtime() function is used to get the current time.

last_day() The last_day() function is used to get the last date of the given month
on the date.
localtime() The localtime() function is used to get the current date and time.

localtimestamp() The localtimestamp() function is used to get the current date and time.

makedate() The makedate() function is used to make the date from the given year
and number of days.

maketime() The maketime() function is used to make the time from given hour,
minute and second.

microsecond () The microsecond () function is used to get the value of the microsecond
from the given datetime or time.

minute () The minute () function is used to get the value of month for the specified
datetime or time.

month () The month () function is used to get the value of month from given
datetime or time.

monthname() The monthname() function is used to get the full month name.

now () The now () function is used to get the current date and time.

period_add() The period_add() function adds the given number of month in the given
period in the format YYMM or YYYYMM.

period_diff() The period_diff() function is used to get the difference between the
given two periods.

quater() The quarter () function is used to get the quarter portion of the specified
date/datetime.

sec_to_time() The sec_to_time() function is used to convert the specified second into
time.
second () The second () function is used to get the second portion from the
specified date/datetime.

str_to_date() The str_to_date() function is used to convert the string into the given
format_mask.

subdate() The subdate() function is used to get the date which is subtracted by
given intervals.

subtime() The subtime() function is used to get the time/datetime which is


subtracted by certain intervals.

sysdate() The sysdate() function is used to get the system date.

time () The time () function is used to get the time for the given time/datetime.

time_format() The time_format() function is used to format the time in specified


format_mask.

time_to_sec() The time_to_sec() function is used to convert the time into seconds.

timediff() The timediff() function is used to get the difference for the given two
time/datetime.

timestamp () The timestamp () function is used to convert the expression into


datetime/time.

to_day() The to_day() function is used to convert the date into numeric number
of days.

weekday () The weekday () function is used to get the index for a date

week () The week () function is used to get the week portion for the specified
date.
weekofyear() The weekofyear () function is used to get the week of the given date.

Numeric Functions and Operators

Name Description

%, MOD Modulo operator

* Multiplication operator

+ Addition operator

- Minus operator

- Change the sign of the argument

/ Division operator

ABS () Return the absolute value

ACOS () Return the arc cosine

ASIN () Return the arc sine

ATAN () Return the arc tangent

ATAN2(), ATAN () Return the arc tangent of the two arguments

CEIL () Return the smallest integer value not less than the argument

CEILING () Return the smallest integer value not less than the argument

CONV () Convert numbers between different number bases

COS () Return the cosine


Name Description

COT () Return the cotangent

CRC32() Compute a cyclic redundancy check value

DEGREES () Convert radians to degrees

DIV Integer division

EXP () Raise to the power of

FLOOR () Return the largest integer value not greater than the argument

LN () Return the natural logarithm of the argument

LOG () Return the natural logarithm of the first argument

LOG10 () Return the base-10 logarithm of the argument

LOG2() Return the base-2 logarithm of the argument

MOD () Return the remainder

PI () Return the value of pi

POW () Return the argument raised to the specified power

POWER () Return the argument raised to the specified power

RADIANS () Return argument converted to radians

RAND () Return a random floating-point value

ROUND () Round the argument

SIGN () Return the sign of the argument

SIN () Return the sine of the argument

SQRT () Return the square root of the argument


Name Description

TAN () Return the tangent of the argument

TRUNCATE () Truncate to specified number of decimal places

SQL Compare String


In this SQL section, we will discuss how to compare two or more strings in the Structured Query Language

We can compare two or more strings using the STRCMP string function, LIKE operator, and Equal operator.

STRCMP String function

STRCMP is a function of string that compares the specified two strings and gives 0 if the length of the first string
is equal to the length of the second string. If the length of the first string is more than the length of the second
string, then the function returns 1 otherwise -1.

Syntax of STRCMP Function:


SELECT STRCMP (String_1, String_2);

SQL BETWEEN Operator

The BETWEEN operator in SQL shows the record within the range mentioned in the SQL query. This operator
operates on the numbers, characters, and date/time operands.

If there is no value in the given range, then this operator shows NULL value.

Syntax of BETWEEN operator:

1. SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name WHERE column_nameBE

SQL LIKE Operator

The LIKE operator in SQL shows those records from the table which match with the given pattern specified in
the sub-query.
The percentage (%) sign is a wildcard which is used in conjunction with this logical operator.

This operator is used in the WHERE clause with the following three statements:

1. SELECT statement
2. UPDATE statement
3. DELETE statement

Syntax of LIKE operator:

SELECT column_Name
SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name WHERE column_name LIKE

SQL String Functions

SQL String functions are the predefined functions that allow the database users for string manipulation. These
functions only accept, process, and give results of the string data type.

Following are the most important string functions in Structured Query Language:

1. ASCII ()
2. CHAR_LENGTH ()
3. CHARACTER_LENGTH ()
4. CONCAT ()
5. CONCAT_WS ()
6. FIND_IN_SET ()
7. FORMAT ()
8. INSERT ()
9. INSTR ()
10. LCASE ()
11. LEFT ()
12. LOCATE ()
13. LOWER ()
14. LPAD ()
15. LTRIM ()
16. MID ()
17. POSITION ()
18. REPEAT ()
19. REPLACE ()
20. REVERSE ()
21. RIGHT ()
22. RPAD ()
23. RTRIM ()
24. SPACE ()
25. STRCMP ()
26. SUBSTR ()
27. SUBSTRING ()
28. SUBSTRING_INDEX ()
29. UCASE ()
30. UPPER ()

Let's discuss ONE string function in brief with the SQL table.

1.
1. CREATE TABLE table_name
2. (
3. 1st_Column Data Type (character_size of 1st Column),
4. 2nd_Column Data Type (character_size of the 2nd column),
5. 3rd_Column Data Type (character_size of the 3rd column),
6. ...

2. Nth_Column Data Type (character_size of the Nth column)


3. );

Stored Procedure in SQL Server


A stored procedure is a group of one or more pre-compiled SQL statements into a logical unit. It is stored as an
object inside the database server. It is a subroutine or a subprogram in the common computing language that
has been created and stored in the database. Each procedure in SQL Server always contains a name, parameter
lists, and Transact-SQL statements. The SQL Database Server stores the stored procedures as named objects.
We can invoke the procedures by using triggers, other procedures, and applications such as Java, Python, PHP,
etc. It can support almost all relational database systems.
SQL Server builds an execution plan when the stored procedure is called the first time and stores them in the
cache memory. The plan is reused by SQL Server in subsequent executions of the stored procedure, allowing it
to run quickly and efficiently.

Features of Stored Procedures in SQL Server

The following are the features of stored procedure in SQL Server:

o Reduced Traffic: A stored procedure reduces network traffic between the application and the database
server, resulting in increased performance. It is because instead of sending several SQL statements, the
application only needs to send the name of the stored procedure and its parameters.
o Stronger Security: The procedure is always secure because it manages which processes and activities we
can perform. It removes the need for permissions to be granted at the database object level and
simplifies the security layers.
o Reusable: Stored procedures are reusable. It reduces code inconsistency, prevents unnecessary rewrites
of the same code, and makes the code transparent to all applications or users.
o Easy Maintenance: The procedures are easier to maintain without restarting or deploying the
application.
o Improved Performance: Stored Procedure increases the application performance. Once we create the
stored procedures and compile them the first time, it creates an execution plan reused for subsequent
executions. The procedure is usually processed quicker because the query processor does not have to
create a new plan.

Types of Stored Procedures

SQL Server categorizes the stored procedures mainly in two types:

1.User-defined Stored Procedures

2.System Stored Procedures

User-defined Stored Procedures

Database developers or database administrators build user-defined stored procedures. These procedures
provide one or more SQL statements for selecting, updating, or removing data from database tables. A stored
procedure specified by the user accepts input parameters and returns output parameters. DDL and DML
commands are used together in a user-defined procedure.

We can further divide this procedure into two types:

o T-SQL Stored Procedures: Transact-SQL procedures are one of the most popular types of SQL Server
procedures. It takes parameters and returns them. These procedures handle INSERT, UPDATE, and
DELETE statements with or without parameters and output row data.
o CLR Stored Procedures: The SQL Server procedures are a group of SQL commands, and the CLR indicates
the common language runtime. CLR stored procedures are made up of the CLR and a stored procedure,
which is written in a CLR-based language like VB.NET or C#. CLR procedures are .Net objects that run in
the SQL Server database's memory.

System Stored Procedures

The server's administrative tasks depend primarily on system stored procedures. When SQL Server is installed,
it creates system procedures. The system stored procedures prevent the administrator from querying or
modifying the system and database catalog tables directly. Developers often ignore system stored procedures.

SQL Server Stored Procedures Syntax

The following are the basic syntax to create stored procedures in SQL Server:

1. CREATE PROCEDURE [schema_name].procedure_name


@Parameter_name data_type,
a. ....
b. parameter_name data_type
2. AS
3. BEGIN
i. SQL statements
ii. SELECT, INSERT, UPDATE, or DELETE statement
4. END

Parameter Explanations

The stored procedure syntax has the following parameters:

Schema name: It is the name of your database or schema. By default, a procedure is associated with the current
database, but we can also create it into another database by specifying the DB name.

Procedure Name: It represents the name of your stored procedure that should be meaningful names so that
you can identify them quickly. It cannot be the system reserved keywords.

Parameter Name: It represents the number of parameters. It may be zero or more based upon the user
requirements. We must ensure that we used the appropriate data type. For example, @Name VARCHAR (50).

DAY 6:
SQL Group by:
In SQL, The Group By statement is used for organizing similar data into groups. The data is further organized
with the help of equivalent function. It means, if different rows in a precise column have the same values, it will
arrange those rows in a group.

o The SELECT statement is used with the GROUP BY clause in the SQL query.
o WHERE clause is placed before the GROUP BY clause in SQL.
o ORDER BY clause is placed after the GROUP BY clause in SQL.

Syntax:
1. SELECT column1, function_name(column2)
2. FROM table_name
3. WHERE condition
4. GROUP BY column1, column2
5. ORDER BY column1, column2;
6. function_name: Table name.
7. Condition: which we used.

Example:

Group By single column: Group By single column is used to place all the rows with the same value. These values
are of that specified column in one group. It signifies that all rows will put an equal amount through a single
column, which is of one appropriate column in one group.

Consider the below query;

1. SELECT NAME, SUM (SALARY) FROM Employee


2. GROUP BY NAME;

NAME SALARY

John 50000

Nick 44000

Amara 15000

SQL ORDER BY Clause

o Whenever we want to sort the records based on the columns stored in the tables of the SQL database,
then we consider using the ORDER BY clause in SQL.
o The ORDER BY clause in SQL will help us to sort the records based on the specific column of a table. This
means that all the values stored in the column on which we are applying ORDER BY clause will be sorted,
and the corresponding column values will be displayed in the sequence in which we have obtained the
values in the earlier step.
o Using the ORDER BY clause, we can sort the records in ascending or descending order as per our
requirement. The records will be sorted in ascending order whenever the ASC keyword is used with
ORDER by clause. DESC keyword will sort the records in descending order.
o If no keyword is specified after the column based on which we have to sort the records, in that case, the
sorting will be done by default in the ascending order.

Before writing the queries for sorting the records, let us understand the syntax.

Syntax to sort the records in ascending order:


SELECT ColumnName1, Column Name N FROM Table Name ORDER BY Column Name ASC;

Syntax to sort the records in descending order:


1. SELECT ColumnName1, Column Name N FROM Table Name ORDER BY Column Name DESC;

Syntax to sort the records in ascending order without using ASC keyword:
1. SELECT ColumnName1, Column Name N FROM Table Name ORDER BY Column Name;

SQL HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.

HAVING Syntax

SELECT column name(s)


FROM table name
WHERE condition
GROUP BY column name(s)
HAVING condition
ORDER BY column name(s);

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

The SQL JOIN clause takes records from two or more tables in a database and combines it together.

ANSI standard SQL defines five types of JOINS:

1. inner join,
2. left outer join,
3. right outer join,
4. full outer join, and
5. cross join.

In the process of joining, rows of both tables are combined in a single table.

Why SQL JOIN is used?


If you want to access more than one table through a select statement.

If you want to combine two or more table then SQL JOIN statement is used .it combines rows of that tables in
one table and one can retrieve the information by a SELECT statement.

The joining of two or more tables is based on common field between them.

SQL INNER JOIN also known as simple join is the most common type of join.

SQL OUTER JOIN


In the SQL outer JOIN all the content of the both tables are integrated together either they are matched or not.

If you take an example of employee table

Outer join of two types:

1.Left outer join (also known as left join): this join returns all the rows from left table combine with the matching
rows of the right table. If you get no matching in the right table it returns NULL values.

2.Right outer join (also known as right join): this join returns all the rows from right table are combined with
the matching rows of left table. If you get no column matching in the left table .it returns null value.

SQL LEFT JOIN


The SQL left join returns all the values from the left table and it also includes matching values from right table,
if there are no matching join value it returns NULL.

BASIC SYNTAX FOR LEFT JOIN:

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


2. FROM table1
3. LEFTJOIN table2
4. ON table1.column_field = table2.column_field;

let us take two tables in this example to elaborate all the things:

CUSTOMER TABLE:

46.1M
888
How to find Nth Highest Salary in SQL

ID NAME AGE SALARY

1 ARYAN 51 56000

2 AROHI 21 25000

3 VINEET 24 31000

4 AJEET 23 32000

5 RAVI 23 42000

This is second table

ORDER TABLE:

O_ID DATE CUSTOMER_ID AMOUNT

001 20-01-2012 2 3000

002 12-02-2012 2 2000

003 22-03-2012 3 4000

004 11-04-2012 4 5000

join these two tables with LEFT JOIN:

1. SQL SELECT ID, NAME, AMOUNT, DATE


2. FROM CUSTOMER
3. LEFT JOIN ORDER
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;

This will produce the following result:

ID NAME AMOUNT DATE

1 ARYAN NULL NULL

2 AROHI 3000 20-01-2012

2 AROHI 2000 12-02-2012

3 VINEET 4000 22-03-2012

4 AJEET 5000 11-04-2012

5 RAVI NULL NULL

SQL RIGHT JOIN


The SQL right join returns all the values from the rows of right table. It also includes the matched values from
left table but if there is no matching in both tables, it returns NULL.

Basic syntax for right join:

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


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

let us take an example with 2 tables table1 is CUSTOMERS table and table2 is ORDERS table.

CUSTOMER TABLE:

ID NAME AGE SALARY

1 ARYAN 51 56000

2 AROHI 21 25000

3 VINEET 24 31000

4 AJEET 23 32000
5 RAVI 23 42000

and this is the second table:

ORDER TABLE:

DATE O_ID CUSTOMER_ID AMOUNT

20-01-2012 001 2 3000

12-02-2012 002 2 2000

22-03-2012 003 3 4000

11-04-2012 004 4 5000

Here we will join these two tables with SQL RIGHT JOIN:

1. SQL> SELECT ID, NAME, AMOUNT, DATE


2. FROM CUSTOMER
3. RIGHT JOIN ORDER
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;

ID NAME AMOUNT DATE

2 AROHI 3000 20-01-2012

2 AROHI 2000 12-02-2012

3 VINEET 4000 22-03-2012

4 AJEET 5000 11-04-2012

SQL FULL JOIN


The SQL full join is the result of combination of both left and right outer join and the join tables have all the
records from both tables. It puts NULL on the place of matches not found.
SQL full outer join and SQL join are same. generally, it is known as SQL FULL JOIN.

SQL full outer join:


What is SQL full outer join?

SQL full outer join is used to combine the result of both left and right outer join and returns all rows (don't care
its matched or unmatched) from the both participating tables.

Syntax for full outer join:

1. SELECT *
2. FROM table1
3. FULL OUTER JOIN table2
4. ON table1.column_name = table2.column_name;

SQL Cross Join


o Join operation in SQL is used to combine multiple tables together into a single table.
o If we use the cross join to combine two different tables, then we will get the Cartesian product of the
sets of rows from the joined table. When each row of the first table is combined with each row from the
second table, it is known as Cartesian join or cross join.
o After performing the cross-join operation, the total number of rows present in the final table will be
equal to the product of the number of rows present in table 1 and the number of rows present in table
2.
o Forexample:
If there are two records in table 1 and three records in table 2, then after performing cross join operation,
we will get six records in the final table.
o Let us take a look at the syntax of writing a query to perform the cross-join operation in SQL.

SELECT TableName1.columnName1, TableName2.columnName2 FROM TableName1 CROSS JOIN TableName2


ON Table
DAY 7:

View in SQL
A view is a database object that has no values. It is a virtual table, which is created according to the result set
of an SQL query. However, it looks similar to an actual table containing rows and columns. Therefore, we can
say that its contents are based on the base table. It is operated similarly to the base table but does not contain
any data of its own. Its name is always unique, like tables. The views differ from tables as they are definitions
that are created on top of other tables (or views). If any changes occur in the underlying table, the same changes
reflected in the views also.

This diagram illustrates the concept of a view that included columns from more than one table. Here we have
two tables named 'Table A' and 'Table B,' and by using a SQL statement, a view is created containing data from
both tables. Views are a database object; that's why it does not store physically. This feature makes views
excellent for abstracting or hiding complex queries.
Uses of views
The primary use of view in SQL Server is to implement the security mechanism. It prevents users from seeing
specific columns and rows from tables. It only shows the data returned by the query that was declared when
the view was created. The rest of the information is completely hidden from the end-user.

Types of views
The SQL Server categories the views into two types:

1. User-Defined Views

Users define these views to meet their specific requirements. It can also divide into two types one is the simple
view, and another is the complex view. The simple view is based on the single base table without using any
complex queries. The complex view is based on more than one table along with group by clause, order by
clause, and join conditions.

2. System-Defined Views

System-defined views are predefined and existing views stored in SQL Server, such as Temped, Master, and
temp. Each system views have its own properties and functions. They can automatically attach to the user-
defined databases. We can divide the System-defined views in SQL Server into three types: Information Schema,
Catalog View, and Dynamic Management View.

SQL Server allows us to create a view in mainly two ways:

o Using T-SQL Query


o Using SQL Server Management Studio

Let us explain both ways in detail.

Using T-SQL Query


We can create a new view by using the CREATE VIEW and SELECT statement. SELECT statements are used to
take data from the source table to make a VIEW.

Syntax

The following syntax is used to create a view in SQL Server:

1. CREATE VIEW name AS

2. SELECT column1, column2, ...


3. FROM table name
4. WHERE condition;

In this syntax, the view name indicates the name of a view. It should be unique. The SELECT statement chooses
columns from the source table. The WHERE is an optional clause specifying the conditions that must be met for
the records to be included in the VIEW.

Rename views in SQL Server

We can also change the name of a view in SQL Server. We can do this by using the built-in stored procedure
named sp_rename or the SQL Server management studio. Here we will see both ways:

Using sp_rename

The following syntax is used to rename a view:

SP_RENAME View_Old_Name, View_New_Name

Suppose we want to change the name of the above-created view course enrolled to course. The following query
explains this concept:

sp_rename course enrolled, course

Update views in SQL Server

We can also update a view in SQL Server. We can do this by using the ALTER VIEW command or the
management studio. Here we will see both ways:

ALTER VIEW Statement

Suppose we want to add one more column named 'city' in the above-created view course enrolled.
To do this, we need to use the statements as follows:

1. ALTER VIEW course enrolled

2. AS
3. SELECT first name, last name, course, city, amount paid
4. FROM Student AS S
5. INNER JOIN Fee AS F
6. ON S. admission_no = F. admission_no;
List views in SQL Server

We can use the sys. views or sys. objects catalog view to list or display all views available in a SQL
Server Database. Here is an example:

SELECT OBJECT_SCHEMA_NAME (v. object_id) schema name, v.name

1. FROM sys. views as v;

Drop Views in SQL Server

We can also remove the existing view from the SQL Server. We can do this by using the SQL query or the
management studio. Here we will see both ways:

Using SQL Query

SQL Server provides a DROP VIEW command to remove the view from a database. If the view does not exist,
we will get an error. We can use the below syntax to remove a view:

DROP VIEW [IF EXISTS] schema name. view name;

Suppose you want to delete a view course enrolled; we can do this as follows:

DROP VIEW course enrolled

Joining Three or More Tables in SQL


Joining multiple tables in SQL is some tricky tasks. It can be more difficult if you need to join more than two
tables in single SQL query, we will analyse how to retrieve data from multiple tables using INNER JOINs. In this
section, we have used two approaches to join three or more tables in SQL.

There are two approaches to join three or more tables in SQL:

1. Using JOINS in SQL:


The same logic is applied here which is used to join two tables i.e., the minimum number of join statements to
join n tables are (n-1).

1. select s_name, score, status, address city, email_id,


2. accomplishments from student s inner join mark m on
3. s.s_id = m.s_id inner join details d on
4. d.school_id = m.school_id;
Output:

2. Using the Parent-child Relationship:

In the parent-child relationship, we use where clause to join two or more tables. Create column X as a primary
key in one table and a foreign key in another table

Look at the tables which are created:


s_id is the primary key in the student table and foreign key in the marks table. (student (parent) -
marks(child)).
school_id is the primary key in the marks table and foreign key in the student table. (marks(parent) -
details(child)).

Query:

1. select s_name, score, status, address_city,


2. email_id, accomplishments from student s,
3. marks m, details d where s.s_id = m.s_id and
4. m.school_id = d.school_id;

Output:

SQL UNION
UNION is an SQL operator which combines the result of two or more SELECT queries and provides the
single set in the output.
Syntax of UNION in SQL:

1. SELECT Column_Name_1, Column_Name_2 ...., Column_NameN FROM Table_Name_1

2. UNION
3. SELECT Column_Name1, Column_Name_2 ...., Column_Name_N FROM Table_Name_2
4. UNION ....... UNION
5. SELECT Column_Name1, Column_Name_2 ...., Column_Name_N FROM Table_Name_N;

Union ALL Operator in SQL

The SQL Union ALL Operator is same as the UNION operator, but the only difference is that UNION ALL operator
also shows the common rows in the result.

Syntax of UNION ALL Set operator:

1. SELECT Column_Name_1, Column_Name_2 ...., Column_Name_N FROM Table_Name_1 [WHERE condi


tion]

2. UNION ALL
3. SELECT Column_Name_1, Column_Name_2 ...., Column_Name_N FROM Table_Name_2 [WHERE condi
tion];

SQL INTERSECT Operator


In SQL Server, the INTERSECT operator is used to fetch the records that are in common between two SELECT
statements or data sets. If a record exists in one query and not in the other, it will be omitted from the INTERSECT
results.

Syntax:

1. SELECT expression1, expression2, ... expression_n


2. FROM tables
3. [WHERE conditions]
4. INTERSECT
5. SELECT expression1, expression2, ... expression_n
6. FROM tables
7. [WHERE conditions];

Parameter explanation
expression1, expression2, ... expression_n: expressions specify the columns or calculations that you want to
compare between the two SELECT statements. There is not necessary to have the same fields in each of the
SELECT statements, but the corresponding columns must be similar data types in both tables.

tables: It specifies the tables that you want to retrieve records from. There must be at least one table listed in
the FROM clause.

WHERE conditions: It is optional condition. It specifies the conditions that must be met for the records
to be selected.

Image representation:

Mandatory conditions for INTERSECT operation


o The number of expressions in both SELECT statements must be same.
o The corresponding columns in each of the SELECT statements must have similar data types.
o The INTERSECT operator fetch only common records the SELECT statements.

DAY 8:

SQL Sub Query


A Subquery is a query within another SQL query and embedded within the WHERE clause.

Important Rule:

o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators like
=, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner
query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to perform
the same function as ORDER BY command.

1. Subqueries with the Select Statement

SQL subqueries are most frequently used with the Select statement.

Syntax

1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. (SELECT column_name from table_name WHERE ...);

2. Subqueries with the INSERT Statement


o SQL subquery can also be used with the Insert statement. In the insert statement, data returned from
the subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date functions.

Syntax:

1. INSERT INTO table_name (column1, column2, column3....)


2. SELECT *
3. FROM table_name
4. WHERE VALUE OPERATOR

3. Subqueries with the UPDATE Statement


The subquery of SQL can be used in conjunction with the Update statement. When a subquery is used with the
Update statement, then either single or multiple columns in a table can be updated.

Syntax
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);

4. Subqueries with the DELETE Statement


The subquery of SQL can be used in conjunction with the Delete statement just like any other statements
mentioned above.

Syntax

1. DELETE FROM TABLE_NAME


2. WHERE VALUE OPERATOR
3. (SELECT COLUMN_NAME
4. FROM TABLE_NAME
5. WHERE condition);

SQL TEMP TABLE


The concept of temporary table is introduced by SQL server. It helps developers in many ways:

Temporary tables can be created at run-time and can do all kinds of operations that a normal table can do.
These temporary tables are created inside tempdb database.

There are two types of temp tables based on the behavior and scope.

1. Local Temp Variable


2. Global Temp Variable

Local Temp Variable

Local temp tables are only available at current connection time. It is automatically deleted when user
disconnects from instances. It is started with hash (#) sign

1. CREATE TABLE #local temp table (


2. User id int,
3. Username varchar (50),
4. User address varchar (150)
5. )

Global Temp Variable


Global temp tables name starts with double hash (##). Once this table is created, it is like a permanent table. It
is always ready for all users and not deleted until the total connection is withdrawn.

1. CREATE TABLE ##new global temp table (


2. User id int,
3. User name varchar (50),
4. User address varchar (150)
5. )

DAY 9:

Triggers in SQL Server


A trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized category
of stored procedure that is called automatically when a database server event occurs. Each trigger is always
associated with a table.

A trigger is called a special procedure because it cannot be called directly like a stored procedure. The key
distinction between the trigger and procedure is that a trigger is called automatically when a data modification
event occurs against a table. A stored procedure, on the other hand, must be invoked directly.

The following are the main characteristics that distinguish triggers from stored procedures:

o We cannot manually execute/invoked triggers.


o Triggers have no chance of receiving parameters.
o A transaction cannot be committed or rolled back inside a trigger.

Syntax of Trigger
We can create a trigger in SQL Server

by using the CREATE TRIGGER statement as follows:

1. CREATE TRIGGER schema.trigger_name

2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}

The parameter descriptions of this syntax illustrate below:

schema: It is an optional parameter that defines which schema the new trigger belongs to.

trigger_name: It is a required parameter that defines the name for the new trigger.

table_name: It is a required parameter that defines the table name to which the trigger applies. Next to the
table name, we need to write the AFTER clause where any events like INSERT, UPDATE, or DELETE could be
listed.

NOT FOR REPLICATION: This option tells that SQL

Server does not execute the trigger when data is modified as part of a replication process.

SQL Statements: It contains one or more SQL statements that are used to perform actions in response to an
event that occurs.

When we use triggers?

Triggers will be helpful when we need to execute some events automatically on certain desirable scenarios. For
example, we have a constantly changing table and need to know the occurrences of changes and when these
changes happen. If the primary table made any changes in such scenarios, we could create a trigger to insert
the desired data into a separate table.

Types of SQL Server Triggers

We can categorize the triggers in SQL Server in mainly three types:

1. Data Definition Language (DDL) Triggers


2. Data Manipulation Language (DML) Triggers
3. Logon Triggers

DDL Triggers

DDL triggers are fired in response to the DDL events, such as CREATE, ALTER, and DROP statements. We can
create these triggers at the database level or server level, depending on the type of DDL events. It can also be
executed in response to certain system-defined stored procedures that do DDL-like operations.

The DDL triggers are useful in the following scenario:

o When we need to prevent the database schema from changing


o When we need to audit changes made in the database schema
o When we need to respond to a change made in the database schema

DML Triggers

DML triggers are fired in response to DML events like INSERT, UPDATE, and DELETE statements in the user's
table or view. It can also be executed in response to DML-like operations performed by system-defined stored
procedures.

The DML triggers can be classified into two types:

o After Triggers
o Instead Of Triggers

After Triggers

After trigger fires, when SQL Server completes the triggering action successfully, that fired it. Generally, this
trigger is executed when a table completes an insert, update or delete operations. It is not supported in views.
Sometimes it is known as FOR triggers.

We can classify this trigger further into three types:

1. AFTER INSERT Trigger


2. AFTER UPDATE Trigger
3. AFTER DELETE Trigger

Example: When we insert data into a table, the trigger associated with the insert operation on that table will
not fire until the row has passed all constraints, such as the primary key constraint. SQL Server cannot fire the
AFTER trigger when the data insertion failed.

The following is illustration of the After Triggers syntax in SQL Server:

1. CREATE TRIGGER schema_name.trigger_name


2. ON table_name
3. AFTER {INSERT | UPDATE | DELETE}
4. AS
5. BEGIN
6. -- Trigger Statements
7. -- Insert, Update, Or Delete Statements
8. END
Instead of Triggers

Instead of Trigger fires before SQL Server begins to execute the triggering operation that triggered it. It means
that no condition constraint check is needed before the trigger runs. As a result, even if the constraint check
fails, this trigger will fire. It is the opposite of the AFTER trigger. We can create the INSTEAD OF triggers on a
table that executes successfully but doesn't contain the table's actual insert, update, or delete operations.

We can classify this trigger further into three types:

1. INSTEAD OF INSERT Trigger


2. INSTEAD OF UPDATE Trigger
3. INSTEAD OF DELETE Trigger

Example: When we insert data into a table, the trigger associated with the insert operation on that table will
fire before the data has passed all constraints, such as the primary key constraint. SQL Server also fires the
Instead of Trigger if the data insertion fails.

The following is an illustration of the Instead of Triggers syntax in SQL Server:

1. CREATE TRIGGER schema_name.trigger_name


2. ON table_name

3. INSTEAD OF {INSERT | UPDATE | DELETE}


4. AS
5. BEGIN
6. -- trigger statements
7. -- Insert, Update, or Delete commands
8. END

Logon Triggers

Logon triggers are fires in response to a LOGON event. The LOGON event occurs when a user session is
generated with an SQL Server instance, which is made after the authentication process of logging is completed
but before establishing a user session. As a result, the SQL Server error log will display all messages created by
the trigger, including error messages and the PRINT statement messages. If authentication fails, logon triggers
do not execute. These triggers may be used to audit and control server sessions, such as tracking login activity
or limiting the number of sessions for a particular login.

How to SHOW Triggers in SQL Server?

When we have many databases with multiple tables, the show or list trigger comes in handy. When the table
names in multiple databases are the same, this query is extremely helpful. Using the following command, we
can see a list of all the triggers available in SQL Server:
1. SELECT name, is_instead_of_trigger

2. FROM sys.triggers
3. WHERE type = 'TR';

Advantages of Triggers

The following are the advantages of using triggers in SQL Server:

o Triggers set database object rules and roll back if any change does not satisfy those rules. The trigger will
inspect the data and make changes if necessary.
o Triggers help us to enforce data integrity.
o Triggers help us to validate data before inserted or updated.
o Triggers help us to keep a log of records.
o Triggers increase SQL queries' performance because they do not need to compile each time they are
executed.
o Triggers reduce the client-side code that saves time and effort.
o Triggers are easy to maintain.

Disadvantages of Triggers

The following are the disadvantages of using triggers in SQL Server:

o Triggers only allow using extended validations.


o Triggers are invoked automatically, and their execution is invisible to the user. Therefore, it isn't easy to
troubleshoot what happens in the database layer.
o Triggers may increase the overhead of the database server.
o We can define the same trigger action for multiple user actions such as INSERT and UPDATE in the same
CREATE TRIGGER statement.
o We can create a trigger in the current database only, but it can reference objects outside the current
database.

CTE (Common Table Expression) SQL


The Common Table Expressions (CTE) are imported into the SQL to simplify many classes of the Structured
Query Language (SQL) for a derived table, which is unsuitable. It was introduced in 2005 SQL SERVER version.

The common table expressions (CTE) are a result set, which we reference with the SELECT, INSERT, UPDATE,
or DELETE statement. In SQL 2008, we add a CTE for the unique MERGE statement.
How to use CTEs in T-SQL?

The use of Common Text Expression is to add the clause "WITH" before the SELECT, INSERT, UPDATE, DELETE
or MERGE statement. The WITH clause contain one or more CTEs, which are separated by commas.

1. [WITH [, ....]]
2. ::::=
3. cte_name [(column_name[, ...])]__Write the name of column here
4. AS (cte_query)

Day 10:
ALL OPERATOR IN SQL

How to Use ALL in SQL

In this SQL section, we will discuss how to use the 'ALL' keyword with the tables in Structured Query Language.
To understand the examples of the 'ALL' keyword, we first have to know what it is.

What is Any in SQL?

The ALL is an operator in SQL. This operator compares the single record to every record of the list returned by
the sub-query. This operator is always used with the SQL comparison operator, which is followed by the inner
query.

The syntax for using ALL operator in Structured Query Language:

1. SELECT Column_Name_1, Column_Name_2, Column_Name_3, ……, Column_Name_N FROM Table_Na


me WHERE Column_Name Comparison_Operator ALL (SELECT Column_Name FROM Table_Name WHE
RE [condition]);

In the ALL syntax, the ALL operator is followed by the SQL comparison operator, which helps compare the
column value with the sub-query.

We can use the following comparison operators with the ALL operator in the statements of SQL:

1. Equal operator (=)

This comparison operator with ALL operator evaluates to TRUE when the value of specified column is equal to
any value in the returned list.
Syntax:

Column Name = ALL (subquery);

2. Not Equal operator (! =)

This comparison operator with the ALL operator evaluates to TRUE when the value of the specified column is
not equal to any value of the returned list.

Syntax:

Column Name! = ALL (subquery);

3. Greater Than operator (>)

This comparison operator with the ALL operator evaluates to TRUE when the value of the specified column is
greater than the biggest value of the returned list.

Syntax:

Column Name > ALL (subquery);

4. Less Than operator (<)

This comparison operator with the ALL operator evaluates to TRUE when the value of the specified column is
less than the smallest value of the returned list.

Syntax:

Column Name < ALL (subquery);

5. Greater Than Equal To operator (>=)

This comparison operator with the ALL operator evaluates to TRUE when the value of the specified column is
greater than or equals the biggest value of the returned list.

Syntax:

Column Name >= ALL (subquery);

6. Less Than Equals To operator (<=)

This comparison operator with the ALL operator evaluates to TRUE when the value of the specified column is
less than or equals the smallest value of the returned list.
Syntax:

column Name <= ALL (subquery);

If you want to perform the 'ALL' operator in the tables of SQL, then you have to follow the below points one by
one in the given manner:

1. Create a database in the system.


2. Create two new tables.
3. Insert the data in both tables
4. View the Inserted data of both tables
5. Use the ALL operator to view the data in different ways.

You might also like