SQLPDF
SQLPDF
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.
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.
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.
When a transaction rolled back the data associated with table variable is not rolled back.
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
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
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
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.
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.
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:
In this SQL syntax, we have to specify the name of that database which we want to delete permanently
from the database system.
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.
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.
This syntax is used when we want to change the name of the database in MySQL.
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.
stored in a database. In other words, ER diagrams help to explain the logical structure of databases. ER diagrams are created
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.
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.
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:
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.
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.
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, Students as a group are associated with multiple faculty members, and faculty members can be
associated with multiple students.
Steps to Create an
ER Diagram
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
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.
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 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
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 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.
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.
Employee
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.
If you want to create a table, you should name the table and define its column and each column's data type.
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.
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.
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.
But if you do not specify the WHERE condition it will remove all the rows from the 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.
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.
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.
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.
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:
dob DATE,
);
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:
dob DATE,
);
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
dob DATE,
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.
SYNTAX
= equal
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.
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
o CREATE
o ALTER
o DROP
o TRUNCATE
Example:
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
Example
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:
EXAMPLE
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
Syntax:
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.
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:
Or
For example:
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:
For example:
o Grant
o Revoke
Example
Example
These operations are automatically committed in the database that's why they cannot be used while creating
tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.
Syntax:
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Data types mainly classified into three categories for every database.
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.
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.
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.
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.
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.
BOOL It is used to specify Boolean values true and false. Zero is considered as false, and
nonzero values are considered as true.
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
** Exponentiation operator
OR Inclusion operator
Types of 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:
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:
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:
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:
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:
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.
1. SELECT column1 & column2 & .... & columnN FROM table_Name [WHERE conditions];
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:
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
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.
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_timestamp() The current_timestamp() function is used to get the current date and
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.
time () The time () function is used to get the time for the given time/datetime.
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.
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.
Name Description
* Multiplication operator
+ Addition operator
- Minus operator
/ Division operator
CEIL () Return the smallest integer value not less than the argument
CEILING () Return the smallest integer value not less than the argument
FLOOR () Return the largest integer value not greater than the argument
We can compare two or more strings using the STRCMP string function, LIKE operator, and Equal operator.
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.
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.
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
SELECT column_Name
SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name WHERE column_name LIKE
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. ...
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.
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.
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.
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.
The following are the basic syntax to create stored procedures in SQL Server:
Parameter Explanations
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.
NAME SALARY
John 50000
Nick 44000
Amara 15000
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 without using ASC keyword:
1. SELECT ColumnName1, Column Name N FROM Table Name ORDER BY Column Name;
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.
HAVING Syntax
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.
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.
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.
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.
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
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
ORDER TABLE:
let us take an example with 2 tables table1 is CUSTOMERS table and table2 is ORDERS table.
CUSTOMER TABLE:
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
ORDER TABLE:
Here we will join these two tables with SQL RIGHT 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.
1. SELECT *
2. FROM table1
3. FULL OUTER JOIN table2
4. ON table1.column_name = table2.column_name;
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.
Syntax
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.
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
Suppose we want to change the name of the above-created view course enrolled to course. The following query
explains this concept:
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:
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:
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:
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:
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:
Suppose you want to delete a view course enrolled; we can do this as follows:
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
Query:
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:
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;
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.
2. UNION ALL
3. SELECT Column_Name_1, Column_Name_2 ...., Column_Name_N FROM Table_Name_2 [WHERE condi
tion];
Syntax:
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:
DAY 8:
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.
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 ...);
Syntax:
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);
Syntax
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.
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
DAY 9:
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:
Syntax of Trigger
We can create a trigger in SQL Server
2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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 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
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.
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.
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:
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:
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:
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:
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:
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:
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:
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: