100% found this document useful (1 vote)
55 views61 pages

Introduction To SQL Database

Databases in sql

Uploaded by

Mashaka Yohana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
55 views61 pages

Introduction To SQL Database

Databases in sql

Uploaded by

Mashaka Yohana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 61

What is SQL?

SQL Meaning: it is a domain-specific language. It is used in application development language


to enable a programmer to work with the data. The data is stored in a relational database. To
manage this data, we have relational database management systems like SQL Server,
MySQL,Oracle, etc. that use SQL as a standard database language.
This introduction to SQL session will give you a quick overview on:
•What does SQL stand for?
•What Is Data?
•What Is a Database?
•What Is a Database Management System?
•Types of Database Architecture
•Types of Databases
•Features of SQL
•History of SQL
•Why SQL
•SQL Process
•Types of SQL Commands
•What is SQL used for?
•How to Use SQL
•Types of SQL Statements
•SQL Standards
•SQL Language elements
•Why does it make sense to learn SQL after NoSQL?
•SQL Skills in Demand
•Whats the Future of SQL Databases?
•SQL Basics

What does SQL stand for?


A common question is what is the full form of SQL. SQL stands for Structured Query Language.
The original name of the language was SEQUEL, created for the IBM System R research
database in 1970, but due to copyright issues, they changed the name to SQL.
What Is Data?
Data is distinct pieces of information, which can be facts, figures, or details that are stored in or
used by a computer. In this digital era where data powers everything that we do, mastering what
is SQL and how does it work might take a long time. To learn and become a SQL professional
join this complete SQL Training Course!

What Is a Database?
A database is a well-organized collection of data that is stored in an electronic format. To be
more specific, a SQL database is an electronic system that allows users to easily access,
manipulate, and update the data.
What Is a Database Management System?
Consider a School SQL Database which has a record of the present students and the previously
studied students in the Student Details table. Similarly, it may contain Faculty Details,
Management Details, Staff Details, and many more depending on the schools requirement. As
the data is in huge amounts, to manage it we need a database management system.

Almost all modern databases are managed by a Database Management System (DBMS).
Basically, it is a system software used for creating data in a systematic way and managing
databases.
Want to get certified in SQL? Learn all about SQL Server Certification!
How Does SQL Database Manage Data?
DBMS provides, for both users and programmers, a fundamental way to create, retrieve, update,
and manage data.
Consider a scenario where a student XYZ wants to change his address. The DBMS searches the
details of XYZ in the table Student Detailsfrom the database School Databaseand displays it for
the user, and then the user edits it.
Watch this SQL Full Course Tutorial
Now, we have a clear picture of a database and its managing system. Lets move on.
Types of Database Architecture
We have two types of database architecture:

 File Server
 Client-Server

Still have queries? Come to Intellipaats SQL Community, clarify all your doubts, and excel in
your career!
File Server Architecture
In the file server architecture, files are located on the local system. It is useful for sharing
information across a network. The client sends a request for a file over the network, and the file
server forwards the file to the client. This is considered to be the most primitive type of data
service used for exchanging information over a network. The file server provides access to
remote server processors too.
Here is an example to understand the implementation of the file server.

Suppose, you have an Excel file, and one of your friends requests you to send that file for some
information. So, you send a copy to your friend. Now when you make any changes in your
original Excel file, those changes would not be reflected in the file which is with your friend.
In this example, you are a file server and your friend is the device requesting the information.
We can conclude on the file server architecture by quoting that the server acts as a sorting device
and only one person at a time can have access to it.
Client-Server Architecture
In the client-server architecture, the database is the server and any application that uses the data
is a client.
Here is an example to explain the working of this server. Consider three OLE DB components or
client systems accessing the database at the same time. The systems have logged into the IRCTC
website to know the number of trains running from X destination to Y destination.

The client system sends the request to the network server. The network server sends the same
request to the database and the final result is sent to the client system. This process is conducted
when one system sends the request. But in real-time, there will be n number of systems and there
can be multiple requests that are sent at a time for the same data. The database server will have to
process all the requests simultaneously and send back the requested data to the client systems.
Types of Databases
The databases are classified into various databases depending upon the usage requirements.

 Centralized database.
 Distributed database.
 Personal database.
 End-user database.
 Commercial database.
 NoSQL database.
 Operational database.
 Relational database.
 Cloud database.
 Object-oriented database.
 Graph database.

Features of SQL
Now we are good to go with SQL! As discussed before SQL full form is a structured query
language, it helps you to communicate with the database by commands. Here are some of the
features of SQL Database:

 It allows users to extract data from the relational database.


 It allows users to create databases and tables.
 It allows updating, inserting, deleting, and altering databases and tables.
 It provides security and allows to set permission.
 Allows people to handle data in new ways.

History of SQL
IBM Corporation, Inc. created the language Structured English Query Language (SEQUEL) to
implement Codds model. Later, SEQUEL was renamed SQL (still pronounced sequel). The first
commercially available implementation of SQL was released in 1979 by Relational Software,
Inc. (now Oracle). SQL is now widely recognised as the standard RDBMS language.
Why SQL
Since SQL can work with any database, it is the most widely used language for database access.
The databases in which you interact are programs that allow clients to logically store and manage
information. With SQL, we can have the following advantages.

 SQL offers data access to users in relational databases.


 Users may use this feature to define the data.
 Identifying and modifying the data in a database is easy with SQL
 We can create, delete, alter the data in the database anytime.
 It Allows SQL modules, libraries, and pre-compilers to be embedded within other
languages.
 Database views, stored procedures, and functions can be built with SQL.

SQL Process
When you want to run SQL Queries on any DBMS system, you must first decide the best method
for carrying out your request, and the SQL engine will determine how to interpret that task.
The following are some important components of the SQL process:

 Query Dispatcher: The dispatchers task is to send the query request to either CQE or SQE,
depending on the querys attributes. The dispatcher is in charge of handling all inquiries. It
cant be avoided.
 Optimization Engines: After considering several factors related to the objects referenced
and the conditions defined in the query, including the Optimizer Goal, the Query optimizer
determines the most efficient way to execute a SQL expression.
 Classic Query Engine: For any fields that are empty, CQE will use default values to map
data into the record buffer. For fields that arent empty, SQE just maps data to the record
buffer.
 SQL Query Engine: To access data in relational structures, a SQL query engine interprets
SQL commands and language. Many people use SQL query engines to perform CRUD
(create, read, update, and delete) operations and implement data policies that are required by
relational data models and database management systems.

Types of SQL Commands


SQL commands are traditionally divided into four categories:

 Data Query Language (DQL Commands in SQL)


 Data Definition Language (DDL Commands in SQL)
 Data Manipulation Language (DML Commands in SQL)
 Data Control Language (DCL Commands in SQL)

Data Query Language (DQL Commands in SQL)


Data Query Language comprises only one command select.This command can be accompanied
by many other clauses to compose queries.
Data Definition Language (DDL Commands in SQL)
Data Definition Language is power for SQL, which allows a user to create and restructure
database objects. The basic DDL commands in SQL are Create Tables, Alter Tables, and Drop
Tables.
CREATE TABLE It creates a new table
DROP TABLE It deletes the ENTIRE table.
ALTER TABLE Modifies the existing table

Data Manipulation Language (DML Commands in SQL)


Data Manipulation Language is used to manipulate data within the tables. The basic DML
commands in SQL are Insert, Update and Delete.
SELECT Retrieve information from the database
INSERT Add new information to a database
UPDATE Modifies the information currently stored in a database
DELETE Delete information from the database

Data Control Access Language (DCL Commands in SQL)


And finally, we have Data Control Access which allows the user to control access to data within
the database. These DCA commands are generally used to control the distribution of privileges
among users and create objects related to user access. The basic DCL commands in SQL are
Grant and Revoke.
This brings us to the end of the Introduction to SQL. Here we have learned what is SQL, SQL
full form, SQL Database, all basic SQL commands, and their types – DDL, DCL, DML, and
DQL with examples.
Read more – SQL Commands cheat sheet
What is SQL used for?
In the technology world, databases and SQL are used in almost any environment where large
volumes of data are involved. The finance industry, music applications, social media platforms
are some of the sectors that use SQL the most.
For example, Banking software and payment processors, such as Stripe, store and operate data
about financial transactions and users in the finance industry. A complex database is at the heart
of these procedures. Furthermore, bank database systems have additional security specifications
that necessitate the strictest risk enforcement in the SQL code.
How to Use SQL
With SQL, we can create databases, tables, functions, etc. the following are the SQL commands
you need to learn to work in a database.

 CREATE DATABASE – for creating a database


 CREATE TABLE – for creating tables
 SELECT – for finding/extracting some data from a database
 UPDATE – for making adjustments and edit data
 DELETE – for deleting some data
For example, if you want to create a new record in the database.
1
CREATEDATABASEname_of_a_database;
2 CREATETABLEname_of_a_table (
3 column1 data_type,
4 column2 data_type,)

Enroll now in SQL course in Bangalore to learn more about SQL concepts.
Types of SQL Statements
SQL statements are mainly classified into the following.

 Data Definition Language (DDL) Statements


 Data Manipulation Language (DML) Statements
 Transaction Control Statements
 Session Control Statements
 System Control Statement
 Embedded SQL Statements

SQL Standards
SQL is a database management language. It entails database formation, deletion, row retrieval,
and modification, among other things. SQL is accepted as the standard language for relational
databases by both ANSI and the ISO/IEC. There are many sections of the SQL specifications.
The formal names of this standard are:
1
2
3
4
5 ANSI/ISO/IEC 9075:2003, "Database Language SQL",
Parts
6 1 ("SQL/Framework"),
7 2 ("SQL/Foundation"),
8 3 ("SQL/CLI"),
9 4 ("SQL/Persistent Stored Modules"),
1 9 ("SQL/Management of External Data"),
10 ("SQL/Object Language Binding"),
0 11 ("SQL/Schemata"),
1 13 ("SQL/Java Routines and Types"),
1 14 ("SQL/XML") and(SQL/MDA)

SQL Language elements


Mostly used SQL language elements are:
Keywords: single or multiple keywords are present in every SQL statement
Expressions: from elements, like constants, SQL operators, expressions are formed.
Variables: there are many variables like global variables, Sybase IQ supports local variables
and connection-level variables.
Comments: to attach explanatory text to SQL statements or blocks of statements, the comment
is used. A comment is not executed in the SQL server.
Strings: Strings may be literal strings or VARCHAR/CHAR data types expressions.
Identifiers: names of objects in the database, like user IDs, tables, and columns can be said as
Identifiers.
NULL Value: to specify a value that is unknown, missing, or not applicable, a NULL value is
used.
Special values: When creating tables, special values should be used in expressions and as
column defaults.
Search conditions: Conditions may be used to pick a subset of a tables rows or to manipulate
statements such as an IF statement to evaluate flow control.
Why does it make sense to learn SQL after NoSQL?
Since NoSQL databases are highly specialized systems with unique use and limitations, we
should learn SQL after NoSQL. NoSQL is more suited to those who work with large amounts of
data. Relational databases and related technologies are used by the vast majority of people.
Comparing the security and storage support, SQL has more advantages than NoSQL.
SQL Skills in Demand
Most organizations are looking for professionals in SQL skills. Some in-demand SQL skills are:

 Database structures
 Creating a database with SQL
 SQL statements and clauses
 SQL database management
 MySQL and PostgreSQL
 Master PHP

With these in-demand SQL skills you can land in positions as follows:

 Database administrators(DBA)
 Database Migration engineer
 Data scientist
 Big data architect

Whats the Future of SQL Databases?


For years, SQL has had a stronghold on databases. SQL databases could be phased out in favor
of more distributed models in the future, with NoSQL and Hadoop competing for first place.
And according to Stack Overflow Developers survey, SQL is the second-most common
programming language, used by 50% of all developers (Web, Desktop, Sysadmin/DevOps, Data
Scientist/Engineer) and beaten only by JavaScript – a language half the age of SQL. Hence, SQL
databases have a lot of scope in the future.
SQL Basics
Now, lets take a quick ride on what are the SQL Basics we have learned in this what is SQL
blog.
 SQL- SQL is a structured query language.
 History of SQL- first implemented in 1979
 Why SQL?- we can create, alter, and delete data records in a database anytime.
 SQL process- Query dispatcher, optimization engines, classic query engine, the SQL query
engine
 Types of SQL commands- DQL, DDL, DML, and DCL
 SQL language elements- keywords, expressions, variables, comment strings, etc
 SQL skills- database structure, database creation, statements, clauses, MySQL and master
PHP, etc

Features of SQL
SQL is one of the most demanding skills in the current world. Every day a huge amount of data
is collected and one has to deal with these databases to create insightful information. Hence, it is
important for us to learn SQL as it is a special-purpose database programming language that
helps in generating useful strategies from a database and can easily interact with large and
massive databases, no matter what the size is. These features of SQL make SQL the most
powerful tool. Hence, here are some of the major SQL features which makes it a successful
database programming language:

 Data Definition Language (DDL) – DDL contains commands that define data
 create – Creates a table
For example:
create table
tablex(attribute1 datatype…..attribute datatype);
 drop – Deletes the table along with all the attributes
For example:
drop table tablex;
 alter – Modifies the tables structures
For example:
alter table
tablex add(new row1 datatype……new rown datatype);
 rename – Changes the name of a table.
For example:
rename tablex to tabley;

Also check out our guide on SQL Query interview questions.

 Data Manipulation Language (DML): DML contains commands that manipulate data
 insert – Used after the create command to insert values in the table
For example:
insert into tabley values(attribute1 datatype);
:
:
:
insert into tabley values(attributen datatype);
 delete – Deletes particular rows, tuples, or cardinality from the table
For example:
delete from tabley where condition;
 update – Updates the tuples in the table
For example:
update tabley set tuplename=attributename;
 Triggers – Performed when particular conditions are met on data. It has three parts.
 Event – The change that activates the trigger
 Condition – The test or query that is executed after the trigger is activated
 Action – The procedure that is executed after the condition is met true

 Client-server execution and remote database access – SQL commands can control how a
client application is allowed to access the database remotely.
 Security and authentication – SQL can make sure that only specific details of the database
are visible to the user while the entire database is secured by DBMS.
 Embedded SQL – SQL can embed languages like COBOL, C, Java, etc. to query at
runtime
 Transaction Control Language – TCL is used to control the transactions with commands
like:
 commit – Saves the database when its inconsistent
commit;
 rollback – Rolls back to the previous transaction
rollback;
 savepoint – Goes back to the previous transaction without going through the entire
transaction
savepoint;

Characteristics of SQL
 High Performance
SQL provides high-performance programming capability for highly transactional, heavy
workload, and high usage database systems. SQL programming gives various ways to
describe the data more analytically.
 High Availability
SQL is compatible with databases like MS Access, Microsoft SQL Server, MySQL, Oracle
Database, SAP HANA, SAP Adaptive Server, etc. All of these relational database
management systems support SQL and it is easy to create an application extension for
procedural programming and various other SQL functions which are additional features thus
converting SQL into a powerful tool.

 Scalability and Flexibility


SQL provides Scalability and Flexibility. It is very easy to create new tables and
previously created or not used tables can be dropped or deleted in a database.
 Robust Transactional Support
SQL programming can handle large records and manage numerous transactions.
 High Security
It is very easy to provide permissions on tables, procedures, and views, hence, SQL gives
security to your data.
 Comprehensive Application Development
SQL is used by many programmers to program apps to access a database. No matter what
the size of an organization, SQL works for every small or large organization.
 Management Ease
SQL is used in almost every Relational Database Management System. Select, Create,
Insert, Drop, Update, and Deleteare the standard and common SQL commands that help
us to manage large amounts of data from a database very quickly and efficiently.
 Open Source
SQL is an open-source programming language for building relational database
management system

All these features of SQL make it a robust and primary language for many organizations to
manage their large databases.
INSTALLING MS SQL SERVER – LAB 1

How to Create, Use, and Drop a SQL Database?


A database contains records, and to create, modify, or delete these records SQL queries are used.
An SQL query can either be an action query like delete or create or a select query like select or
use. These queries are used to find specific data, perform actions on it, or just display data by
filtering based on specific criteria.
How to Create a Database in SQL?
To Create a Database in SQL
Syntax:
1 CREATEDATABASEdatabasename;

where CREATE DATABASE is the keyword and databasename is the name of the database,
followed by a semicolon.
Here are the steps how to Create a Database in SQL
 Open the SQL software and create a new query by clicking on New Query
 Type the syntax and give a name for your database (Here, we are creating a database happy)

1 CREATEDATABASEhappy;

 Then hit You will see that your commands are executed successfully, and your table is
created.
 Click on Refresh [ ] and you will find a database happy created in Object Explorer
Wish to get certified in SQL! Learn from our SQL expert and do excel in your career with
Intellipaats SQL certification.
How do we Use a SQL Database?
To Select and use a Database in SQL
Syntax:
1 USE databasename;

where USE is the keyword, and databasename is the name that we want to use (select it from
the existing database names), followed by a semicolon.
Once the database is selected, it remains default until another USE statement with a different
database is used. To check which database youre using, place your mouse pointer over the file
where youre executing the query.
Enroll now in SQL course in Bangalore to learn SQL concepts from experts.
How to Select a Database?
 Here in the above image, the default database is the previously selected as SPARATA
 To select the happydatabase, give the command

1 USE happy;

 Hit Execute and the database is selected

How do we Delete or Drop a SQL Database?


To delete a database
Syntax:
1 DROPDATABASEdatabasename;

where DROP DATABASE is the keyword and databasename is the name of the database we
want to delete, followed by semicolon.
Delete a SQL Database
 Here, we are deleting the igneous database; hence give the following command:

1 DROPDATABASEigneous;

 Then hit Execute and Click on Refresh [ ], and the igneous database would not be
displayed on Object Explorer

This bring us to the end of this SQL Database tutorial part. Now youre ready to get started with
creating and modifying your database! Now you know how to create a database in SQL.
Meanwhile, there is a lot more you can do using SQL Database which we will see in the next
tutorial sections.
Overview of Tables in SQL
Tables are the fundamental way to store data in a relational database management system. It
contains a header row at the top of the table, which gives the list of column names, followed by
rows that contain data. We will discuss the basic operations performed on a database by using
important SQL operators.
What Is a Table in SQL?
A table is a database object which is composed of rows and columns in SQL. In simple terms, its
a collection of related data held in a table format.
Numerous tables may be present in a database. The table will list the number of columns but not
the number of rows because the latter is arbitrary.
Lets select the Student Details table from the school database used as the previous example. Any
number of student information can be placed into the Student Details table, however, the
columns should all be confined to and related to one another, such as Student_Name,
Student_ID, Age, BOD, Address, and Percentage of Marks.
The snapshot displays a table from an Employee Database, which contains employee details.
Records and Fields in SQL
In a table, there are rows and columns, with rows referred to as records and columns referred to
as fields. A column consists of data values of a specific type, such as numbers or alphabets, with
each row in the database having one value for that column.
Examples of columns include Age, Student_ID, or Student_Name. On the other hand, a row
represents a singular data item within a table, and all rows in the table have the same structure.
For instance, Shaze in the Student_Name column or 007 in the Student_ID column.
Let us understand fields and records in detail.
Records and Fields in SQL
In a table, there are rows and columns, with rows referred to as records and columns referred to
as fields. A column consists of data values of a specific type, such as numbers or alphabets, with
each row in the database having one value for that column.
Examples of columns include Age, Student_ID, or Student_Name. On the other hand, a row
represents a singular data item within a table, and all rows in the table have the same structure.
For instance, Shaze in the Student_Name column or 007 in the Student_ID column.
Let us understand fields and records in detail.
Curious about how data is stored and manipulated? Want to learn about it? Here is
the Database Course provided by Intellipaat.
Fields in SQL
Fields are basically columns in a table with specific information about the data.
Consider the snapshot below. There is an e_salary field in the table that provides information
about the salaries of different employees. Similarly, the e_age field provides information about
the age of different employees.
Read on: SQL constraints to enhance your knowledge!
Records in SQL
A record is basically an individual entry that exists in a table. Records give complete information
about a single entry or entity. Consider the snapshot below. One row is selected, i.e., Anne. This
row gives complete information about the particular employee, Anne.
So, now we know that a collection of records and fields makes a table, and a collection of tables
makes a database.
Data Types in SQL
SQL Data types inform a compiler or interpreter about the characteristics of the data used in a
program. In simple words, a data type is a particular kind of data item which helps define the
operations that can be performed on the data. There are different data types available like
character data type for the letters in the alphabet or Boolean data type for true or false values.
What Are SQL Data Types?
Data type in SQL basically defines the kind of data that will go into a particular column. All
entries of one particular column will be of the same data type.
Consider the salary table from an employee database. Lets take the e_salary column, for
example. The first value in this column is of an integer type; the second is also of the integer type
and, similarly, all the other entries of the e_salary column are of integer type. Now, consider
another column e_dept from the same table, all values entered in this column are of a character
type.

These data types contain constraints and integrity. Constraints are the limitations on data. They
can either be implemented to a column or to the table. When there is a violation between the data
action and the constraint, then the action is aborted. There are different types of constraints like
primary key, unique key, etc.
Different Data Types in SQL
SQL Data types are divided into three major categories, namely, numeric, character, and date and
time.
Go for this in-depth job-oriented SQL certification training now!
Numeric Data Types in SQL
Numeric data types store all numerical values or integer values.

 Bigint data type helps store really bigvalues.


 Int data type is used to store reasonably big values.
 Smallint data type is used to store values that range from −32,768 to 32,767.
 Tinyint data type stores values from 0 to 255. Its for relatively small numbers.
 Decimal data type is used to store fractional values in two arguments. First part is the size of
the value that is the total number of digits, and the second part specifies the number of digits
(d) after the decimal point. Lets say, we want to store the decimal value 12.50. Here, the size
would be 4 because the total number of digits is 4, and the value of dwould be 2 because
there are 2 digits after the decimal point.

Character Data Types in SQL


Character data types store all alphabetic values and special characters.
 Char data type takes in one argument and has fixed length. For example, consider the size of
the value to be 20. This would mean that you cannot give any value having more than 20
characters. Keeping in mind the fact that char has fixed length, i.e., if the value size is to be
30 characters, but information assigned to it is of 3 characters, then the memory consumed
is of 30 characters.
 Varchar data type also takes in size as the argument. But here, it is a variable length data
type, unlike char. So here if the value size is to be 30 characters, and you give only 3
characters, the memory consumed would be only of 3 characters.
 The text data type can take in a string with a maximum length of 65,535 characters.

Date and Time Data Types in SQL


Date and Time data types store a date or a date/time value.

 Date data type in SQL helps us specify the date in a format. Lets say, if we want to store the
date, 2 January 2019, then first we will give the year which would be 2 0 1 9, then the
month which would be 0 1, and finally, the day which would be 0 2.
 Time data type helps us specify the time represented in a format. Lets say, we want to store
the time 8:30:23 a.m. So, first well specify the hour which would be 0 8, then the minutes
which would be 3 0, and finally the seconds which would be 2 3.
 Year data type holds year values such as 1995 or 2011

How to Create and Drop Table in SQL


A database contains data, and to store data we need a table. Tables are the fundamental level of
a database to store data. It comprises columns, which contain a set of data values of a particular
type, and rows, which contains a single data item. In this tutorial section, we will discuss on:

 How to Create Table in SQL?


 How to Drop Table in SQL?

How to Create Table in SQL?


Lets learn how to create table in SQL with the following example.
Table name will be employee, and this table comprises employee ID, employee name, employee
salary, age, gender and the department in which the employee works

Step 1: Creating a table which involves naming the table


Step 2: Defining its columns which are part of the table
Step 3: Assigning a data type to each column

Syntax of create table in SQL with an example


1 CREATETABLE tablename(
2 column1 datatype,
3 column2 datatype,

4 columnN datatype,
5 PRIMARYKEY(one ormore
6 columns));

where CREATE TABLE is the keyword, tablename is the name of the table name, columns1 to
columnN are the set of columns, and PRIMARY KEY is a constraint followed by a semicolon
Lets create an employee table
1
Createthe table,
2 employee(
3 e_id intnotnull,
4 e_name varchar(20),
5 e_salary int,
6 e_age int,
e_gender varchar(20),
7 e_dept varchar(20),
8 primarykey(e_id)
9 );

 Not null is the constraint used to signify that all cells of this column must have a value
 Varchar stands for variable length character, and the value passed is the maximum length of
the character
 Primary key constraints help uniquely identify all records from the table, and a table cannot
have more than one primary key

 After writing the query, click on the execute button to check for errors
 Once the query is executed, a message appears like Commands completed successfully

How to Drop Table in SQL?


It is used to delete a table from the database.
Syntax of Drop Table in SQL with an example
1 DROPTABLETableName;

where DROP TABLE is the keyword and tablename is the name of the table followed by a
semicolon

 Now, let us see an example of dropping a table

1 DROPTABLEtest;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, a message appears like Commands completed successfully.
 SQL INSERT INTO Query
 The INSERT statement is used to insert records in a table. The table selected to insert
data must have the same number of columns and values. In this tutorial section, we will
discuss on the Insert statement syntax with an example.

A Brief on the INSERT Query in SQL


Once the table is created, the next step is to insert values into it according to its constraints. The
insert statement consists of two ways.

 Only values:
Value of the data to be inserted is specified with the column names.

 Column names and values:


Column name is mentioned, and then the values are inserted.

We are using the only values method in this tutorial section. In only values, the values entered
must be in an order according to the column.
Syntax
1 INSERTINTOtablename VALUES(value1, value2,….valueN);

where INSERT INTO and VALUES are the keywords and tablename is the name of the table;
value1 to valueN are the set of values, followed by a semicolon.
Values are given for each of the columns, respectively. Whenever a variable length character
appears, then the values are entered in a single quote. And when an integer appears, it is written
just like that.
Interested in learning SQL? Enroll in our SQL training now!

 As our employee table is created, lets insert values into it


Insert into employee values(1,sam,30000,26,male,operation);

 After writing the query, click on the execute button to check for errors
 Once the query is executed, a message appears like Commands completed successfully
 Repeat the procedure and create 5 more sets of entries. Once you enter the records, the
employee table will be displayed as follows:

e_id e_name e_salary e_age e_gender e_dept


1 sam 30000 26 male operation
2 julia 940000 27 female operation
3 anne 125000 21 female analytics
4 bob 50000 24 male support
5 jeff 20000 43 male sales
6 matt 940000 29 male operation

Finally, our table is ready with the values. We have inserted six records and, this is the way
Insert query in SQL works. In the next tutorial section, we will learn how to select individual
records from a table.
SELECT Statement in SQL
The Select statement in SQL is the most commonly query-used statement in SQL. It is used to
either fetch data according to some specified rule or display an entire table in SQL. The data
displayed after the query execution is stored in a result table.
In this tutorial section, we will discuss on:

 Select Statement in SQL


 Select Distinct in SQL

Wish to get certified in SQL! Learn SQL from top SQL experts and excel in your career with
intellipaats SQL certification.
A Brief on the SELECT Query in SQL
The Select query in SQL is one of the most important commands in SQL, and it is used to get
data from a table.
Syntax
1 SELECTcolumn1, column2, columnN
2 FROMtablename;

where SELECT and FROM are the keywords; column1 to columnN are a set of columns, and
tablename is the name of the table followed by a semicolon.
How to Select Data from a Table?
 Lets display the name and age of an employee from the employee table

1 Selecte_name Fromemployee; (single column)


2 Selecte_name, e_age Fromemployee;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, the table appears

Become a SQL professional with this complete SQL Training Course!


The Select option contains the table name and the From option contains the table name from
where we want to fetch the data.
 To select everything from a table, use * (asterisk operator)

1 Select* fromemployee;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, the table appears

Select Distinct in SQL


A column often contains many duplicate values, and sometimes the information needed from a
single column has to be distinct. Using the SELECT DISTINCT statement in SQL, we can filter
out distinct values from a column.
Get familiar with the top SQL Interview Questions to get a head start in your career!
Syntax
1 SELECTDISTINCTcolumn1, column2, columnN
2 FROMtablename;

where SELECT DISTINCT and FROM are the keywords, column1 to columnN are a set of
columns, and tablename is the name of the table, followed by a semicolon.
How to Select Distinct Data from a Table?
 Lets select some distinct values from our employee table. If we have a glance at the gender
column, we can see that two values are being repeated, male and female.

selectdistincte_gender
1 fromemployee;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, the table appears

Lets remove the distinct keyword and run the query.


1 selecte_gender fromemployee;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, the table appears

When the distinct keyword was removed, all values got displayed., which gives us a clear picture
of the Select Distinct statement; it gets only the values which are different.
If you have any doubts or queries related to SQL, get them clarified from the SQL experts on
our SQL Community!
This bring us to the end of this Select Query in SQL. Here, we learned to use Select Command in
SQL and Select Distinct command in SQL .
What Is Where Clause in SQL?
The WHERE clause is a very powerful tool that can be used to filter data from a database. It can
be used to select specific rows, columns, and values from a table. The WHERE clause is used in
conjunction with the SELECT statement to specify the conditions that the rows in the result set
must meet.
The syntax for the WHERE clause is as follows:
WHERE <condition>

The <condition> is a Boolean expression that evaluates to either TRUE or FALSE. If


the <condition> evaluates to TRUE, then the row is included in the result set. If
the <condition> evaluates to FALSE, then the row is excluded from the result set.
The <condition> can be any valid Boolean expression. This includes comparisons, logical
operators, and functions. For example, the following are all valid WHERE clauses:
 WHERE name = 'John'
 WHERE age >21
 WHERE country IN ('USA', 'Canada', 'UK')
 WHERE date_of_birth BETWEEN '1990-01-01' AND '2000-01-01'

The WHERE clause can be used to perform complex filtering operations. For example, you
could use the WHERE clause to select all rows where the name column is equal to John and the
age column is greater than 21. You could also use the WHERE clause to select all rows where
the country column is in the list of countries USA, Canada, and UK, and the date_of_birth
column is between 1990-01-01 and 2000-01-01.
The WHERE clause is a powerful tool that can be used to filter data from a database. By
understanding how to use the WHERE clause, you can query your database more effectively and
efficiently.
Here are some additional tips for using the WHERE clause:

 Use the LIKE operator to match patterns in strings. For example, you could use
the LIKE operator to select all rows where the name column contains the letter J.
 Use the IN operator to match a value against a list of values. For example, you could use
the IN operator to select all rows where the country column is equal to USA, Canada, or UK.
 Use the BETWEEN operator to match a value between two other values. For example, you
could use the BETWEEN operator to select all rows where the date_of_birth column is
between 1990-01-01 and 2000-01-01.

By following these tips, you can use the WHERE clause to filter data from your database more
effectively and efficiently.
Here is an example of how to use the WHERE clause to select all rows where the name column is
equal to John:
SELECT * FROM customers
WHERE name = 'John';
This query will return all rows from the customers the table where the value in the name the
column is equal to John.
Here is another example of how to use the WHERE clause to select all rows where the age column
is greater than 21:
SELECT * FROM customers
WHERE age >21;

This query will return all rows from the customers table where the value in the age column is
greater than 21.
Operators in SQL
These SQL operators are considered as a set of reserved words used in SQL Where clause. They
specify the condition and also serve as a conjunction for multiple conditions in a statement. In
this tutorial, we will discuss on:

 How to Impose Conditions using SQL Operators?


 AND Operator in SQL and its syntax
 SQL OR Operator in SQL and its syntax
 NOT Operator in SQL and its syntax

How to Impose Conditions using SQL Operators?


As in the earlier Where clause section, we saw how one condition is passed. But when there are
multiple conditions applied to a table to filter the data, the operators are used. There are two
conditions: first, the age should be greater than 60 and, second, the occupation must be doctor.
Only when these conditions are met, the AND operator displays values.
There are three types of operators:

 AND Operator in SQL


 OR Operator in SQL
 NOT Operator in SQL

AND operator in SQL and its syntax:


The AND operator displays only those records where all conditions are evaluated to true. For
example, if you want to find out all the doctors aged greater than 60, the syntax would be as
follows.
Syntax
SELECT column1, column2, …, columnN
FROM tablename
WHERE [condition1], … AND [conditionN];

where SELECT, FROM, WHERE, and AND are the keywords; column1 to columnN are a set of
columns; tablename is the name of the table, and condition1 to conditionN are a set of conditions
followed by a semicolon.
 Lets display all employees whose age is below 30 and who belong to the operations
department from the employee table

Select e_name, e_age, e_salary From employee where e_age<30 and e_dept=operation;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, the table appears

The AND operator imposes a condition or multiple conditions in which the conditions must be
true, i.e., it must satisfy all the conditions.
Want to learn more about SQL check out our course on SQL Certification in Dublin.
OR operator in SQL and its syntax
The OR operator displays records for any condition separated by OR which is evaluated to true.
For example, if we have to filter out a software engineer or a doctor, then we use the OR
operator.
Syntax
SELECT column1, column2, … columnN
FROM tablename
WHERE [condition1], …, OR [conditionN];

where SELECT, FROM, WHERE, and OR are the keywords; column1 to columnN are a set of
columns; tablename is the name of the table, and condition1 to conditionN are a set of conditions
followed by a semicolon.

 Lets display all employees who are from either the sales department or the operations
department from the employee table

Select * From employee where_dept=salesor e_dept=operation;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, the table appears

The OR operator imposes a condition or multiple conditions in which either of the conditions
must be true.
NOT operator in SQL and its syntax
The NOT operator displays a record if the condition is not true. For example, if we have to
extract all records where the occupation of a person is not a software engineer, then the Not
operator is used.
Syntax
SELECT column1, column2, … columnN
FROM tablename
WHERE NOT [condition1];

where SELECT, FROM, WHERE, and NOT are the keywords; column1 to columnN are a set of
columns; tablename is the name of the table, and there is a condition followed by a semicolon.
Check out the SQL Interview Questions For Experienced list to prepare for your upcoming
interviews.

 Lets display all employees whose gender is not equal to female from the employee table

Select * From employee where not e_gender=female;

 After writing the query, click on the execute button to check for errors
 Once the query is executed, the table appears

Well, this brings us to the end of this SQL Operates tutorial section. Now, youre ready to get
started with creating a table and conducting basic operations of filtering and imposing
conditions! While there is a lot more you can do with the data using SQL queries which we will
see in the following tutorial sections.
The BETWEEN operator in SQL serves as a tool for refining result sets by focusing on values
within a predefined range in a particular column. It facilitates the extraction of rows whose
column values lie within a specified range, encompassing both the lower and upper limits. SQL
queries frequently employ the BETWEEN operator to streamline the retrieval of data that
adheres to specific conditions.
SQL BETWEEN Syntax:
SELECTcolumn1,
column2, ...
1 FROMtable_name
2 WHEREcolumn_name
3 BETWEENvalue1 ANDvalue2;

 column1, column2, ...: The columns you want to retrieve in the result set.
 table_name: The name of the table you are querying.
 column_name: The name of the column you want to apply the BETWEEN operator to.
 value1 and value2: The lower and upper bounds of the range you want to filter on.

Usage Example: Suppose you have a table named employees with a column called, and you want
to retrieve all employees with salaries between $40,000 and $60,000:
SELECTfirst_name, last_name,
1 salary
2 FROMemployees
3 WHEREsalary BETWEEN40000 AND60000;

This SQL query will return all rows from the employees table where the salary falls within the
specified range.
Read on:- SQL Tutorial to enhance your knowledge!
Things to Note while using SQL BETWEEN Operator
1. Inclusive Range: The BETWEEN operator is inclusive, meaning it includes rows where the
column value is equal to the lower and upper bounds. In the example above, employees with
salaries of $40,000 and $60,000 would be included in the result.
2. Data Types: The values used with the BETWEEN operator must be of compatible data types
with the column being compared. For example, if youre comparing dates, the values should
be in a date format that the database can recognize.
3. Negation with NOT: You can also use NOT BETWEEN to retrieve rows that do not fall
within the specified range.
4. Complex Conditions: You can combine BETWEEN with other SQL operators and conditions
(e.g., AND, OR) to create more complex filtering criteria.

The SQL BETWEEN operator simplifies the process of selecting rows within a specific range of
values, making it a valuable tool for querying databases and retrieving relevant data for analysis
or reporting purposes.
Check the UPDATE Query in SQL blog!
Heres a step-by-step guide with SQL code for creating a database, or table, inserting data, and
using the BETWEEN operator:
Step 1: Create a Simple New Database in SQL
To create a new database in SQL, you can use the following code:
1 CREATEDATABASEMyDatabase;

This SQL command will create a new database named MyDatabase.


Step 2: Create a New Table in SQL
Next, lets create a new table within the MyDatabasedatabase. Suppose we want to create a table
to store employee information:
USE MyDatabase;

CREATETABLEEmplo
yees (
1 EmployeeID
2 INTPRIMARYKEY,
3 FirstName
4 VARCHAR(50),
5 LastName
VARCHAR(50),
6 Salary
7 DECIMAL(10, 2)
8 );

This code creates a table named Employeeswith columns for EmployeeID, FirstName,
LastName, and Salary.
Step 3: Insert Data into the Table in SQL
Now, lets insert some sample data into the Employeestable:
1 INSERTINTOEmployees (EmployeeID, FirstName, LastName, Salary)
2 VALUES
3
(1, 'John', 'Doe', 50000.00),
4 (2, 'Jane', 'Smith', 60000.00),
5 (3, 'Alice', 'Johnson', 45000.00),
6 (4, 'Bob', 'Brown', 55000.00);

This SQL code inserts four records into the Employeestable.


Step 4: View the Inserted Data in SQL
To view the data youve inserted, you can use a SELECT statement:
1 SELECT* FROMEmployees;

This SQL query will display all the records in the Employeestable.
Step 5: Use the BETWEEN Operator in SQL
Now, lets use the BETWEEN operator to retrieve employees with salaries between $45,000 and
$55,000:
SELECT* FROMEmployees
WHERESalary
1 BETWEEN45000.00
2 AND55000.00;

This SQL query will return the employees whose salaries fall within the specified range.
These steps demonstrate how to create a database, create a table, insert data, and use the
BETWEEN operator in SQL.
Here are the topics we are about to discuss in this blog:

 SQL UPDATE Query


 How to Use UPDATE Query in SQL?
 Update Table in SQL
 SQL update multiple columns
 SQL update multiple rows

SQL UPDATE Query


The SQL UPDATE query is used to modify existing records in a database table. It allows
changing the values stored in one or more fields of selected records without replacing the entire
record. The basic structure includes specifying the table name, field(s) to update, new value(s) to
replace old ones, and a condition in the WHERE clause to identify which record(s) to update.
SQL UPDATE query provides a convenient way to keep data up-to-date by correcting mistakes,
adding or removing information, and modifying values directly in the database table.
How to Use UPDATE Query in SQL?
The UPDATE command in SQL is used to modify or change the existing records in a table. If
we want to update a particular value, we use the WHERE clause along with the UPDATE clause.
If you do not use the WHERE clause, all the rows will be affected. Moreover, we can use the
UPDATE statement to update single or several columns depending on our needs.
Syntax
1 UPDATEtable_name
2 SETcol1=val1, col2=val2…
3 [Wherecondition];

where UPDATE, SET, and WHERE are the keywords, table_name is the name of the table you
want the update, col1, col2, … are the columns considered to be updated, val1, val2, … assign
new values, and the condition section is where the condition is given, followed by a semicolon.
Lets update some records of the employee table using the Update command in SQL
1 UPDATEemployee
2 SETe_age=42
3 WHEREe_name=sam;

Update Table in SQL


 After writing the query, click on the execute button to check for errors

 Once the query is executed, a message appears like Commands completed successfully
 Lets check the update

SELECT * from employee;

 Now you can check out the updated data in the table.

Also, Check our blog on Replace in SQL: Usage and Implementation of REPLACE()
Function.
SQL Update Multiple Columns
Here is an example for updating multiple columns in SQL.
1 UPDATEEMPLOYEE
2 SETLast_Name='KAPADIA',First_Name='MANISH'
3 WHEREEmployee_ID=7369

 After writing the query, click on the execute button to check for errors
 Once the query is executed, a message appears like 1 row affected .

 Lets check the update

SELECT * from employee;

 Now you can check out the updated data in the table.
Do you still have queries? Come to Intellipaats SQL Community, clarify all your doubts, and
excel in your career!
SQL Update Multiple Rows
UPDATEEmployee
1 SETMiddle_Name
2 =
3 CASEEmployee_ID
4 WHEN7369 THEN'A'
5 WHEN7499 THEN'B'
ELSEMiddle_Name
6 END
7 WHEREEmployee_ID
8 IN(7369,7499);

 After writing the query, click on the execute button to check for errors
 Once the query is executed, a message appears like 1 row affected .

 Lets check the update


 SELECT * from employee;

Know the most common methods for executing function in sql by exploring our blog on how
to run function in SQL!

Delete and Truncate commands in SQL


The Delete query in SQL only deletes records from the table, and it doesnt make any changes in
the definition, i.e., it only manipulates. Hence, it is DML (Data Manipulation Language). The
Truncate command in SQL removes all rows from a table, i.e., it reinitializes the identity by
making changes in the data definition. Thats the reason it is a DDL (Data Definition Language).
DELETE Command in SQL
A DELETE query in SQL is used to remove one or more rows from a table based on certain
conditions. Its a powerful operation that requires caution, as the deleted data is permanently
removed from the table. Heres the basic structure of a DELETE query:
1 DELETEFROMtable_name
2 WHEREcondition;

Lets break down the components:

 DELETE FROM: This part of the query indicates that you want to delete rows from a specific
table.
 table_name: Replace this with the actual name of the table from which you want to delete
data.
 WHERE condition: This is an optional part of the query that specifies the condition that must
be met for a row to be deleted. If you omit this part, all rows in the table will be deleted.
For example, consider a table named Employeeswith columns
EmployeeID,FirstName,LastName,and Salary.If you want to delete an employee with a specific
ID, the query might look like this:
1 DELETEFROMEmployees
2 WHEREEmployeeID = 101;

Its important to be cautious while using DELETE queries, especially without a specific
condition, as they can lead to unintended data loss. To avoid accidents, its recommended to
perform the following steps:

1. Backup: Before running DELETE queries, make sure you have a backup of your data. This
ensures that you can recover the data if something goes wrong.
2. Use SELECT First: If youre unsure about the records that will be deleted, you can first run
a SELECT query with the same condition to preview the data that will be affected.
3. Transaction: Wrap the DELETE query within a transaction if possible. This way, you can
roll back the transaction if something unexpected occurs.
4. Restrict Permissions: Limit DELETE permissions to authorized users only. This prevents
accidental or malicious deletion of data.
5. Test in Development: Always test DELETE queries in a development or testing
environment before applying them to production data.

Enroll now in SQL course to learn more about SQL concepts.


Examples of DELETE Query in SQL
here are a few examples of DELETE queries in SQL with different scenarios:
Example 1: Basic DELETE Query Suppose you have a table named Productswith columns
ProductID,ProductName,and StockQuantity.You want to delete a product with a low stock
quantity (less than 10):
1 DELETEFROMProducts
2 WHEREStockQuantity <10;

This query will delete all rows where the stock quantity is less than 10.
Example 2: DELETE with Specific Condition Consider a table named Orderswith columns
OrderID,CustomerID,and OrderDate.You want to delete an order with a specific ID:
1 DELETEFROMOrders
2 WHEREOrderID = 12345;

This query will delete the order with an OrderID of 12345.


Example 3: DELETE All Records Suppose you want to start fresh by deleting all records from
a table named LogEntries:
1 DELETEFROMLogEntries;

This query will delete all records from the LogEntriestable.


Example 4: DELETE with JOIN If you have a related table structure, you might use a
DELETE query with a JOIN. Suppose you have a Customerstable and an Orderstable, and you
want to delete a specific customer and all their associated orders:
1 DELETECustomers, Orders
FROMCustomers
JOINOrders
ONCustomers.CustomerID =
2 Orders.CustomerID
3 WHERECustomers.CustomerI
4 D = 789;

This query will delete the customer with CustomerID 789 and all orders associated with that
customer.
Example 5: DELETE with Subquery Suppose you have a table named Employeesand you
want to delete employees who have not placed any orders in the Orderstable:
DELETEFROMEmployees
WHEREEmployeeID
1 NOTIN(SELECTDISTINCTEm
2 ployeeID FROMOrders);

This query will delete employees who do not have a corresponding entry in the Orderstable.

Truncate Command in SQL


The TRUNCATE command in SQL is used to quickly and efficiently remove all rows from a table,
effectively resetting it to an empty state. Unlike the DELETE statement, which removes rows one by
one and generates individual transaction logs for each deletion, TRUNCATE works by deallocating
data pages and is typically faster, especially for large tables.
Heres the syntax of the TRUNCATE command:
1 TRUNCATETABLEtable_name;

 TRUNCATE TABLE: This part of the command indicates that you want to remove all rows from the
specified table.
 table_name: Replace this with the name of the table you want to truncate.

Keep in mind the following points when using the TRUNCATE command:

1. Data Deletion: TRUNCATE deletes all rows from the table, and the operation is not reversible.
Its a quicker alternative to DELETE for removing all data.
2. Auto-commit: TRUNCATE is typically an auto-commit operation, meaning its immediately
committed to the database without needing an explicit transaction.
3. Table Structure: TRUNCATE retains the table structure, constraints, and indexes. Its like
starting with an empty table that has the same schema.
4. Permissions: TRUNCATE requires appropriate permissions on the table. Users must have at
least the ALTER privilege on the table.
5. Referential Integrity: If the table is referenced by foreign keys in other tables, you might need
to temporarily disable or drop these constraints before using TRUNCATE.
6. Cannot Be Rolled Back: Unlike transactions, TRUNCATE cannot be rolled back. Once the
command is executed, the data is permanently removed.
Prepare yourself for the industry by going through this Top SQL Interview Questions and
Answers!
Examples of SQL Truncate
Example 1: Basic TRUNCATE Suppose you have a table named Orderswith columns
OrderID,CustomerID,and OrderDate.You want to quickly remove all rows from the table:
1 TRUNCATETABLEOrders;

This command will remove all rows from the Orderstable while keeping its structure intact.
Example 2: TRUNCATE with Constraints If the table youre trying to truncate is referenced by
foreign keys in other tables, you might need to temporarily drop or disable the constraints:
-- Drop foreign key
constraints
ALTERTABLEOtherTable
DROPCONSTRAINTFK_ConstraintNa
1 me;
2
-- Truncate the main table
3 TRUNCATETABLEMainTable;
4
5 -- Recreate the foreign key
6 constraints
7 ALTERTABLEOtherTable
8 ADDCONSTRAINTFK_ConstraintNam
e
9 FOREIGNKEY(ForeignKeyColumn)
1 REFERENCESMainTable
0 (PrimaryKeyColumn);

In this example, you need to drop the foreign key constraints before truncating the main table and
then recreate them afterward.
Example 3: TRUNCATE with Identity Columns If your table has an identity column (auto-
incrementing), the identity value will be reset after truncating the table:
TRUNCATETABLEMyTable;
1 DBCC CHECKIDENT
2 ('MyTable', RESEED, 0);

After truncating, the identity columns value will start from 1 again.
Example 4: TRUNCATE with Log Space Reclamation TRUNCATE can help in freeing up the log
space used by the transactions. This can be beneficial when your transaction log becomes large due to
many DELETE operations:
1 BACKUP LOG YourDatabaseName TODISK = 'C:BackupYourDatabaseLogBackup.bak';
2 TRUNCATETABLEYourTable;

In this example, you back up the transaction log and then truncate the table to release the log space.
Example 5: TRUNCATE with WHERE Condition While TRUNCATE doesnt support a WHERE
clause like DELETE does, you can use a temporary table to achieve a similar result:
1
2 SELECT*
3 INTO#TempTable
4 FROMYourTable
5 WHERESomeConditi
on;
6
7 TRUNCATETABLEYou
8 rTable;
9
1 INSERTINTOYourTa
0 ble
SELECT*
1 FROM#TempTable;
1
1 DROPTABLE#TempTa
2 ble;

n this scenario, you first select the rows you want to keep into a temporary table, then truncate the
main table, and finally re-insert the selected rows back into the main table.
Remember, the TRUNCATE command is a powerful tool for quickly removing all rows from a table.
However, due to its irreversible nature, ensure that you have a backup of your data and understand the
potential impacts before using it, especially in production environments.
SQL training in Bangalore lets you learn about SQL concepts from expert. Enroll now!
SQL Delete vs SQL Truncate
Well, this how we work with Delete query in SQL and where to use Truncate command in SQL. The
table below gives a quick difference between these two commands.

ORDER By in SQL and GROUP By Clause in SQL


In this SQL tutorial, we will learn how to use ORDER By and GROUP By in SQL. Group By in
SQL is used to arrange similar data into groups and Order By in SQL is used to sort the data in
ascending or descending order.
ORDER By in SQL
SQL Order By is used to sort the data in ascending or descending order. It sorts the data in
ascending order by default. To sort the data in descending order we use the DESC keyword.
Syntax of ORDER By in SQL:
SELECTcolumn1, column2….
1 FROMtable_name
2 ORDERBYcolumn1 ASC/DESC,
3 column2 ASC/DESC;

Example:
Sort all the students in ascending order in SQL by the markscolumn.
1 SELECTName
2 FROMStudent_details
3 ORDERBYRoll_no ASC;

GROUP By in SQL:
It is used to arrange similar data into groups. The GROUP BY clause follows the WHERE clause
comes before the ORDER BY clause.
The GROUP BY statement is utilized to group rows with similar values into summary rows,
such as finding out the total number of Apples in each store. It is commonly combined with
aggregate functions like COUNT(), MAX(), MIN(), SUM(), and AVG() to group the result set
based on one or more columns.
Syntax of GROUP By in SQL:
1
2 SELECTcolumn1, column2…
FROMtable_name
3 WHERE[condition]
4 GROUPBYcolumn1, column2
5 ORDERBYcolumn1, column2;

Example:
If we want to know the total marks of each student, then GROUP BY is used as follows:
1 SELECTName, Sum(marks)
2 FROMStudent_details
3 GROUPBYName;

Introduction to SQL DISTINCT


The DISTINCT keyword in SQL is used to return unique values from a column or set of
columns. This can be useful for getting a count of unique values, or for filtering out duplicate
rows from a result set.
For example, lets say we have a table of students, and we want to get a count of the number of
unique students in the table. We can use the following SQL query:
SELECT COUNT(DISTINCT student_id)
FROM students;

This query will return the number 10, which is the number of unique students in the students
table.
Examples in SQL DISTINCT
Here are some other examples of how to use the DISTINCT keyword in SQL:

 To get a list of all of the unique cities in a country, we could use the following query:

SELECT DISTINCT city


FROM countries;

 To filter out duplicate rows from a list of products, we could use the following query:
SELECT DISTINCT product_name, product_price
FROM products;

How to search a specified pattern in a column in SQL?


It is used to search a specified pattern in a column. The two wildcards operator used in
conjunction with the LIKE operator.

 % – The percent sign is used to represent one or more characters.


 _ – The underscore sign is used to represent only one Character.

Syntax:
SELECT column1, column2….
FROM table_name
WHERE column1 LIKE %XXX;
OR
SELECT column1, column2….
FROM table_name
WHERE column1 LIKE %XXX%;
OR

SELECT column1, column2….


FROM table_name
WHERE column1 LIKE _XXX;
OR
SELECT column1, column2….
FROM table_name
WHERE column1 LIKE XX_X;
OR
SELECT column1, column2….
FROM table_name
WHERE column1 LIKE %XX_X;
Example:
SELECT Name, Roll_no
FROM Student_details
WHERE Name LIKE %tesh;

Name Roll No.


Jitesh 6

What is the SQL ALTER Command?


The ALTER command in SQL is a powerful tool that allows you to change the structure of
existing database objects without affecting the data they contain. The command can be used to
modify table columns, constraints, indexes, and more.
Modifying Table Structure
Adding Columns
You can use the ALTER TABLE statement to add new columns to an existing table. For
example, lets say you have a Customers table and want to add a Phone_Number column.
The syntax for adding a column is as follows:
1 ALTERTABLECustomers ADDPhone_Number varchar(20);

Dropping Columns
To remove a column from a table, you can use the DROP COLUMN clause in the ALTER
TABLE statement. Suppose you decide to remove the Phone_Numbercolumn from the
Customerstable.
1 ALTERTABLECustomers
2 DROPCOLUMNPhone_Number;

Modifying Column Data Types


The ALTER command also lets you change the data type of a column. Imagine you want to
change the Phone_Numbercolumn data type to hold longer phone numbers.
ALTERTABLECustomers
1 ALTERCOLUMNPhone_Numbe
2 r VARCHAR(20);

3. Managing Constraints
Adding Constraints
Constraints ensure data integrity. You can use the ALTER TABLE statement to add constraints
like primary keys, foreign keys, and unique constraints. For example, lets add a unique constraint
to the Emailcolumn in the Customerstable.
1 ALTERTABLECustomers
2 ADDCONSTRAINTUQ_Email UNIQUE(Email);

Dropping Constraints
To remove a constraint, use the DROP CONSTRAINT clause in the ALTER TABLE statement.
If you wish to drop the unique constraint on the Emailcolumn:
1 ALTERTABLECustomers
2 DROPCONSTRAINTUQ_Email;

4. Renaming Tables
The ALTER command allows you to rename a table easily. Suppose you want to rename the
Customerstable to Clients.
1 ALTERTABLECustomers
2 RENAME TOClients;

5. Changing Table Owners


You can change the owner of a table using the ALTER command, granted you have the
necessary privileges.
1 ALTERTABLECustomers
2 OWNER TONewOwner;

6. Real-world Examples
Adding Columns for Enhanced Data Tracking
Consider a scenario where an Orderstable lacks a Timestampcolumn for order placement. You
can use ALTER to rectify this.
1 ALTERTABLEOrders
2 ADDTimestampDATETIME;

Adapting to Business Changes: Modifying Data Types


If an Inventorytables Product_Pricecolumn needs more precision, you can modify its data type.
1 ALTERTABLEInventory
2 ALTERCOLUMNProduct_Price DECIMAL(10, 2);

Strengthening Data Integrity: Adding Constraints


Suppose an Employeestable requires a foreign key relationship with a Departmentstable. You
can establish it using ALTER.
ALTERTABLEEmployees
1 ADDCONSTRAINTFK_DepartmentID
2 FOREIGNKEY(Department_ID)
3 REFERENCESDepartments(ID);

Conclusion
Mastering the SQL ALTER command empowers you to adapt your database structures to
changing requirements without compromising data integrity. Whether youre adding columns,
altering data types, or managing constraints, the ALTER command is a versatile tool in your
database administration arsenal. Armed with the knowledge and practical examples provided in
this guide, youre now ready to navigate the world of SQL alterations with confidence.
How does SQL UNION work?
SQL UNION combines the results of two or more SELECT queries into a single result set. Its
important to note that UNION only returns distinct rows in the final result, automatically
eliminating any duplicate entries. To use UNION, the SELECT statements being combined must
have the same number of columns, and the columns must have compatible data types.
The syntax for a basic SQL UNION operation is as follows:
1 SELECTcolumn_name(s)
2 FROMtable1
3 UNION
4 SELECTcolumn_name(s)
5 FROMtable2;

In this example, we are combining the results of two SELECT queries, one from table1 and one
from table2. The column_name(s) keywords specify the columns that we want to include in the
final result set.
Practical Examples of SQL UNION

 Merging Customer Data:


Suppose you have two tables: customers_usa and customers_europe, containing customer
information for different regions. You can use UNION to create a unified customer list:
SELECTcustomer_id, first_name, last_name,
email
1 FROMcustomers_usa
2 UNION
3 SELECTcustomer_id, first_name, last_name,
4 email
5 FROMcustomers_europe;

 Consolidating Inventory Data:


Lets say you manage inventory data in separate tables based on product categories. To
consolidate this data for efficient analysis, you can use UNION:
SELECTproduct_id, product_name,
stock_quantity
1 FROMelectronics_inventory
2 UNION
3 SELECTproduct_id, product_name,
4 stock_quantity
5 FROMclothing_inventory;

 Combining Sales Reports:


Imagine you have quarterly sales reports stored in various tables. To create an annual sales
overview, you can use UNION to merge the quarterly reports:
SELECTyear, quarter,
total_sales
1 FROMQ1_sales
2 UNION
3 SELECTyear, quarter,
4 total_sales
5 FROMQ2_sales
6 UNION
7 SELECTyear, quarter,
8 total_sales
9 FROMQ3_sales
1 UNION
0 SELECTyear, quarter,
1 total_sales
1 FROMQ4_sales;

Use Cases for SQL UNION


 Merging Similar Data: Imagine you have a customer database split into two tables, one
containing basic customer information and the other containing contact details. By using
UNION, you can effortlessly merge these tables to create a comprehensive customer profile.
 Consolidating Time-Series Data: If your organization stores time-series data in different
tables, you can utilize UNION to consolidate historical records into a single table. This is
particularly useful for generating trend analyses and forecasts.
 Combining Reports: Lets say youre dealing with multiple sales reports from different
regions. With SQL UNION, you can unify these reports into a single result set for
centralized reporting and analysis.
 Categorizing Data: Suppose you have separate tables for different product categories. SQL
UNION can help you create a master catalog by combining data from these tables,
simplifying inventory management.

Best Practices for Using SQL UNION


 Column Ordering and Data Types: Ensure that the columns youre combining in the
SELECT statements have the same ordering and compatible data types. Mismatched data
types can lead to errors or unexpected results.
 Use UNION ALL When Appropriate: While UNION eliminates duplicate rows, UNION
ALL preserves all rows, including duplicates. If youre confident that your data doesnt
contain duplicates, using UNION ALL can be more efficient.
 Optimize Query Performance: Just like any other SQL operation, UNION queries can
benefit from proper indexing, query optimization, and database design practices.
 Avoid Excessive UNIONs: While UNION is a powerful tool, excessive use of UNION
operations might indicate a need for better database design or normalization.

Conclusion
SQL UNION opens up a world of possibilities for combining and analyzing data from various
sources. Whether youre working with customer data, time-series records, or different types of
reports, UNION allows you to create a cohesive dataset for enhanced insights. By understanding
the syntax, use cases, and best practices of SQL UNION, youll be equipped to harness its
potential and take your data analysis skills to the next level.
LIKE and BETWEEN in SQL
LIKE and BETWEEN operators in SQL are used to compare values in a database. In this tutorial
section, we will discuss on:

 LIKE Operator in SQL


 BETWEEN Operator in SQL

LIKE Operator in SQL


The LIKE Operator in SQL is used to extract records where a particular pattern is present. In a
WHERE clause, the LIKE operator is used to look for a certain pattern in a column. In SQL, it
has two wildcard characters, such as:

 Percentage symbol (%): It is a substitution for zero, one, or more characters.


 Underscore symbol (_): It is a substitution for a single character.


Here are the examples of how we use the LIKE operator using wildcard
Like Operator Description
WHERE EmployeeName LIKE e Finds values that start with e
%
WHERE EmployeeName LIKE Finds values that end with e
%e
WHERE EmployeeName LIKE Finds values that have enat any position
%en%
WHERE EmployeeName LIKE _e Finds values that have eonly in the second position
%
WHERE EmployeeName LIKE Finds values that start with eand are at least 3 characters in
e__% length
WHERE EmployeeName LIKE e Finds values that start with eand end with 0
%0

 SQL Like Syntax


1 SELECTcolumn_list
FROMtablename
2 WHEREcolumn_N
3 LIKE_xxxxx%;

 where SELECT, FROM, WHERE, and LIKE are the keywords, column_list is the list of
columns, tablename is the name of the table, column_N is the column name, and there is
a pattern followed by a semicolon.
 Let us take an example to understand this better, imagine that we want to extract a
persons name from the employee table below.
 Demo Database
e_id e_name e_salary e_age e_gender e_dept
1 john 30000 25 male operations
2 julia 540000 27 female operations
3 anna 125000 27 female analytics
4 bob 50000 24 male support
5 max 540000 29 male operations

 Lets do some operations with the LIKE query in SQL. Extract all records where the
employee name starts with the letter J
1 Select* fromemployee wheree_name LIKE'j%';


 After writing the query, click on the execute button to check for errors. Once the SQL
query is executed, a message appears like Commands completed successfully. As we can
see in the result, we got only two rows in which the names start with the letter j.
 Now, lets take another example in which we extract all records from the database where
the employee age is in the twenties.
Select* fromemployee wheree_age
1 LIKE'2_';

BETWEEN Operator in SQL


The BETWEEN operator in SQL is used to select values within a given range. For example, to
extract only those records where the age of the person is between 20 and 25, we have to use the
BETWEEN query in SQL.
SQL Between Syntax
1 SELECTcolumn_list
2 FROMtablename
3 Wherecolumn_N BETWEENval1 ANDval2;

where SELECT, FROM, WHERE, BETWEEN, and AND are the keywords, column_list is a list
of columns, tablename is the name of the table, column_N is the column name, val1 is the
minimum value of the range, and val2 is the maximum value of the range, followed by a
semicolon. Lets, now, display employees aged between 25 and 35 from the above employee
table.
1 Select* Fromemployee wheree_age BETWEEN25 AND35;
Visit our SQL Community to get answers to all your queries!
After writing the query, click on the execute button to check for errors. Once the query is
executed, the table appears.
Lets display the salaries of employees between $60,000 and $120,000 from the employee table.
1 Select* Fromemployee wheree_salary BETWEEN60000 AND1200000;

After writing the query, click on the execute button to check for errors. Once the query is
executed, the table appears.
Well, this brings us to the end of this tutorial section. Now, youre ready to get started with using
LIKE in SQL and BETWEEN in SQL for comparing the values in your database.
What is Constraint in SQL?
Constraints are rules that are applied to the data columns of a table. They are used to ensure the
accuracy and consistency of the data in a table. If a constraint is violated, the action that is trying
to be performed is aborted.
SQL constraints can be specified when the table is created or after the table is created. They can
be column-level or table-level. Column-level constraints are applied to only one column, while
table-level constraints are applied to the whole table.
Here are some examples of SQL constraints:

 NOT NULL constraint: This constraint ensures that the column cannot have a NULL
value.
 UNIQUE constraint: This constraint ensures that each row in the table has a unique value
in the specified column.
 CHECK constraint: This constraint ensures that the value in the column meets certain
criteria. For example, you could use a CHECK constraint to ensure that the value in a
column is between 1 and 100.
 FOREIGN KEY constraint: This constraint ensures that the value in one column refers to
a valid value in another column. For example, you could use a FOREIGN KEY constraint to
ensure that the customer_id column in the orders table refers to a valid value in the
customers table.
 Constraints are an important part of data integrity. By using constraints, you can ensure that
the data in your tables is accurate and consistent. This can help to prevent errors and
improve the quality of your data.

Constraints in SQL
Some of the commonly used Constraints in SQL are:

 Not NULL Constraints in SQL


 UNIQUE Constraints in SQL
 PRIMARY KEY Constraints in SQL
 FOREIGN KEY Constraints in SQL
 CHECK Constraints in SQL
 DEFAULT Constraints in SQL
 Not NULL:
It indicates that the column cannot have null value.

 UNIQUE:
It ensures that all the values in the column are unique.
 PRIMARY KEY:
It is a key which helps you to find the data from the table. It must be unique and not null.
 FOREGIN KEY
A foreign key is a field in a relational table that matches the primary key column of another
table.
 CHECK
It checks whether all values meets the specific condition or not.
 DEFAULT
Itprovides the default value when the value is not specified.
Syntax:
CREATE TABLE table_name
(
Column1 datatype (size) constraint_name,
Column2 datatype (size) constraint_name,
Column3 datatype (size) constraint_name,
……….
);

DATE FORMAT in SQL – SQL FORMAT ()


This FORMAT () function in the SQL is utilized for formatting a field in order to be brought into
its displayable standard format.
The Syntax for the format function is mentioned below:
1 SELECTFORMAT (column_name, format) FROMtablename;

Here, the column_name – Tells about the ground where formatting is required. And the format –
Defines the layout
For Example Table: Shopping
MerchandiseName Cost Date

SELECTMerchandiseName, Cost, FORMAT (Now (),'YYYY-MM-DD')


1 ASPerDate FROMMerchandise;
DATE FORMAT in SQL
The DATE_FORMAT () returns a value formatted with the specified format. It is used for the
locale-aware formatting of date/time and number values as strings. Let us understand more about
it below:
The DATE_FORMAT ()
It is a function from the SQL server. The date format in SQL is used for displaying the time and
date in several layouts and representations.
Syntax
1 DATE_FORMAT (date, format)

–Where date is a suitable date and Format tells about the layout to be represented.
SQL Date Format Functions
In SQL, when working with a database, the format of the date in the table must be similar to the
input date. There are some default date formatfunctions present in SQL. Following are some of
the:

 NOW () – Returns the current date and time


 CURTIME() – Returns the current time
 EXTRACT() – Returns a single part of a date/time
 DATE_SUB() – Subtracts a specified time interval from a date
 DATE_FORMAT() – Displays date/time data in different formats
 DATEDIFF () – Returns the number of days between two dates
 DATE_ADD() – Adds a specified time interval to a date
 DATE() – Extracts the date part of a date or date/time expression
 CURDATE() – Returns the current date

SQL Date Functions


There are several SQL Date functions but not all are used mostly. There are certain SQL Date
Functions that are used frequently. Some of those default SQL Date functions are:

 GETDATE () – Returns the time between two dates


 DATEADD () – Adds or subtracts a specified time interval from a date
 CONVERT () – Displays date/time data in different formats. It converts date format into
SQL
 DATEPART () – Returns a single part of a date/time
 DATEDIFF () – Returns the current date and time

SQL Date Data Types


For storing date and time, the different data types are:

 DATE – in YYYY-MM-DD format in SQL


 YEAR – in YYYY or YY format in SQL
 TIMESTAMP – in YYYY-MM-DD HH: MI:SS format in SQL
 DATETIME – in YYYY-MM-DD HH: MI: SS format in SQL
Datetime Format In SQL
SQL Date and Time Data Types
The Date format types are in the table below:
Data type Accuracy Storage size User-defined fractional Time zone
(bytes) second precision offset
time 100 nanoseconds 3 to 5 yes no
date 1 day 3 no

smalldatetimen 1 minute 4 no no
date time 0.00333 second 8 no no
datetime2 100 nanoseconds 6 to 8 yes no
datetimeoffset 100 nanoseconds 8 to 10 yes yes

SQL Date and Time Functions


Function Syntax Return data type Deterministic
SYSDATETIME SYSDATETIME () datetime2(7) No
SYSDATETIMEOFFSET SYSDATETIMEOFFSET ( ) datetimeoffset(7) No
SYSUTCDATETIME SYSUTCDATETIME ( ) datetime2(7) No

Lower-Precision System Date and Time Functions


Function Syntax Return data type Deterministic
SYSDATETIME SYSDATETIME () datetime2(7) No
SYSDATETIMEOFFSET SYSDATETIMEOFFSET ( ) datetimeoffset(7) No
SYSUTCDATETIME SYSUTCDATETIME ( ) datetime2(7) No

Functions to Get Date and Time Parts in SQL


Function Syntax Return data type Deterministic
DATENAME DATENAME ( datepart ,date ) nvarchar No
DATEPART DATEPART ( datepart ,date ) int No
DAY DAY ( date ) int Yes
MONTH MONTH ( date ) int Yes
YEAR YEAR ( date ) int Yes

Functions to Get Date and Time Values from Their Parts


Function Syntax Return data Deterministi
type c
DATEFROMPARTS DATEFROMPARTS date Deterministi
( year, month, day ) c
DATETIME2FROMPARTS DATETIME2FROMPARTS datetime2 Deterministi
( year, month, day,hour, minute, second ( precision ) c
s, fractions, precision )
DATETIMEFROMPARTS DATETIMEFROMPARTS datetime Deterministi
( year, month, day, hour,minute, second c
s, milliseconds )
DATETIMEOFFSETFROMP DATETIMEOFFSETFROMPARTS datetime Deterministi
ARTS ( year, month,day, hour, minute, second ( precision ) c
s,
fractions, hour_offset,minute_offset, pr
ecision )
SMALLDATETIMEFROMP SMALLDATETIMEFROMPARTS smalldatetim Deterministi
ARTS ( year, month,day, hour, minute ) e c
TIMEFROMPARTS TIMEFROMPARTS time Deterministi
( hour, minute, seconds,fractions, preci ( precision ) c
sion )

Functions That Get Date and Time Difference


Function Syntax Return data Deterministic
type
DATEDIFF DATEDIFF ( datepart ,startdate , enddate ) int Deterministic
DATEDIFF_BIG DATEDIFF_BIG bigint Deterministic
( datepart ,startdate , enddate )

Functions That Modify Date and Time Values


Function Syntax Return data type Determinist
ic
DATEADD DATEADD (datepart , number, date )The data type of Deterministi
the date argument c
EOMONTH EOMONTH (start_date [,month_to_add ] ) Return type is the Deterministi
type c
ofstart_date or date.
SWITCHOFFSET SWITCHOFFSET(DATETIMEOFFSET, ti datetimeoffset with Deterministi
me_zone) the fractional c
precision of
theDATETIMEOFF
SET
TODATETIMEOF TODATETIMEOFFSET datetimeoffset with Deterministi
FSET (expression ,time_zone) the fractional c
precision of
thedatetime argume
nt

Functions That Set or Get Session Format


Function Syntax Deterministic
@@DATEFIRST @@DATEFIRST Nondeterministic
SET DATEFIRST SET DATEFIRST {number |@number_var } Not applicable
SET DATEFORMAT SET DATEFORMAT {format |@format_var } Not applicable
@@LANGUAGE @@LANGUAGE Not applicable
SET LANGUAGE SET LANGUAGE { [ N ] language | Not applicable
@language_var }
sp_helplanguage sp_helplanguage [ [ @language = ]language ] Not applicable

Functions That Proves the Date and Time Values


Function Syntax Return data type Deterministic
ISDATE ISDATE (expression ) int Yes

Introduction to SQL Functions


Structured Query Language (SQL) functions are the bedrock of database manipulation, providing
a systematic approach to retrieving, transforming, and analyzing data. Think of SQL functions as
pre-packaged tools designed to streamline data operations, making it easier for developers to
perform calculations, data manipulations, and transformations without having to write extensive
code from scratch. By leveraging these functions, developers can optimize efficiency and
promote code reusability.
Built-in vs. User-defined Functions
SQL functions are categorized into two main types: built-in functions, which come as part of the
database system, and user-defined functions (UDFs), which developers create to cater to specific
needs.
Common SQL Function Categories
Mathematical Functions: These functions form the foundation of numeric operations. They
encompass fundamental arithmetic operations like addition ( +), subtraction (-), multiplication (*),
division (/), and modulo (%). More advanced functions include exponentiation (POWER or ^)
and square root (SQRT).
String Functions: String manipulation is crucial in handling textual data. SQL string functions
offer a plethora of capabilities, including concatenation ( CONCAT), case conversions
(UPPER and LOWER), trimming (TRIM), and pattern matching (LIKE). Functions
like SUBSTRING and CHARINDEX enable extraction and searching within strings.
Date and Time Functions: Dealing with temporal data is a common task in databases. SQL date
and time functions facilitate formatting ( FORMAT), extraction of date parts
(YEAR, MONTH, DAY), arithmetic operations (DATEADD, DATEDIFF), and conversions
(CAST, CONVERT) between different date and time formats.
Aggregate Functions: Aggregate functions compute values across multiple rows, making them
essential for summarizing data. Functions such as SUM, AVG, COUNT, MAX, and MIN are used in
conjunction with the GROUP BY clause for efficient data aggregation.
Conversion Functions: Converting data types is a common requirement in data processing.
SQL provides functions like CAST and CONVERT to convert between different data types,
ensuring consistency and compatibility in calculations and comparisons.
Conditional Functions: Conditional functions facilitate decision-making within queries.
The CASE statement, for instance, enables conditional expressions, allowing developers to define
different outcomes based on specified conditions. The COALESCE function returns the first non-
null value from a list of expressions.
Using SQL Functions: To harness the power of SQL functions, developers include them within
their queries. The syntax typically involves specifying the function name, providing necessary
parameters, and utilizing the returned value in the desired context. Functions can be used on
columns, constants, or expressions to produce calculated results.
Optimizing Performance with Functions: While SQL functions enhance code readability, they
can also impact performance. Some functions prevent the query optimizer from efficiently
utilizing indexes, leading to slower query execution times. Striking a balance between code
clarity and query optimization is crucial.
User-Defined Functions (UDFs): For more specific or complex requirements, developers can
create their own functions, known as user-defined functions (UDFs). These functions
encapsulate custom logic, offering a higher level of abstraction and reusability. UDFs can be
scalar functions that return a single value, or table-valued functions that return result sets.
Best Practices for Using SQL Functions
 Select the appropriate function for the task to ensure accuracy and maintainability.
 Limit the usage of functions within queries, especially in large datasets, to prevent
performance bottlenecks.
 Minimize unnecessary type conversions to avoid performance degradation.

Challenges and Limitations in SQL Functions


 Function support varies across different database systems, requiring careful consideration
when designing cross-platform solutions.
 Overuse of functions can lead to queries that are harder to optimize and maintain.
 Complex functions might hinder debugging efforts and increase the likelihood of errors.

Future Trends in SQL Function Development


As the technological landscape evolves, SQL functions are likely to incorporate advanced
features. This could include integration with machine learning libraries, support for graph
processing, and enhanced optimization techniques to accommodate the ever-increasing volumes
of data.
Conclusion
SQL functions are the unsung heroes that empower developers to work efficiently with data.
Whether through the utilization of built-in functions for everyday tasks or the creation of custom
user-defined functions for unique challenges, understanding the diverse world of SQL functions
is a prerequisite for mastering database management. Balancing the convenience of functions
with optimization considerations will ultimately result in well-structured and high-performing
database queries. As the data landscape continues to evolve, a solid understanding of SQL
functions will remain an invaluable skill for any data professional.
The following topics will be covered in this tutorial:

 What are JOINs in SQL?


 SQL JOIN Syntax
 SQL JOIN Example
 SQL JOIN Types
 Inner JOINs in SQL
 Left JOINs in SQL
 Right JOINs in SQL
 FULL JOINs in SQL

What is JOIN in SQL?


As the term suggests, SQL JOINs refers to a clause in SQL that is used to combine rows of two
or more tables by using common values. It takes into consideration the records from two or more
tables in a database and combines them. SQL JOIN is typically used in situations where you
want to access one or more tables through a select statement.
SQL JOIN Syntax
SQL JOIN ( also referred to as INNER JOIN ) is the most commonly used method of JOINing
data from multiple tables. The syntax for SQL JOIN is given below:
Consider the example below, the syntax used to JOIN data from these tables will be:
SELECTName, City, Marks, Phone_no
FROMStudent_detail,
1 Personal_detail
2 WHEREStudent_details.Name=Persona
3 l_detail.Name;

 SQL JOIN Example:


 Now let us understand SQL JOIN with the help of a detailed example:
 Consider this table showing student details:
Name Roll No. Marks
Akshay 1 57
Charu 2 68
Disha 3 52
Eva 4 68
Himanshu 5 75
Jitesh 6 88

 Below given is another table showing the personal details:


Name City Phone No Email Id
Akshay Jaipur 9543846521 Akshay21@gmail.com
Disha Bombay 8532465892 Disha@gmail.com
Jitesh Banglore 9684365125 Jitesh1990@gmail.com

Now, by giving the following syntax, the two tables are JOINed together to form a new table that
shows the name of the student, his/her city, marks obtained, and phone number.
SELECTName, City, Marks, Phone_no
FROMStudent_detail,
1 Personal_detail
2 WHEREStudent_details.Name=Persona
3 l_detail.Name;

The result of the above SQL JOIN syntax is given below:


Name City Marks Phone No
Akshay Jaipur 57 9543846521
Disha Bombay 52 8532465892
Jitesh Banglore 88 9684365125

SQL JOIN Types


There are different types of JOINs available in SQL:

 Inner JOIN in SQL


 Left JOIN in SQL
 Right JOIN in SQL
 Full JOIN in SQL

Inner JOIN in SQL:


Inner SQL JOIN Query returns a value when there is a match in both tables. Inner JOIN is the
most commonly used method when it comes to JOINing tables. The terms Inner JOINand SQL
JOINare sometimes used interchangeably. Below given is the syntax for Inner JOIN. It is also
the same syntax used in the case of SQL JOIN.

Syntax:
1 SELECTColumn_list
2 FROMTABLE1
INNERJOINTABLE2
3 ONTable1.ColName = Table2.ColName
4

Example:
SELECTstudents_data.RollNo, students_data.Name, students_data.Address,
1 students_mark.Marks, students_mark.Grade
2 FROMstudents_data
3 INNERJOINstudents_mark ONstudents_data.RollNo = students_mark.RollNo;

Left JOIN in SQL:


Left SQL JOIN Query returns all the values of the left table and matches the rows from the right
table. Now, if there is no matching value on the right side, Left JOIN will return the value from
the right side as NULL. In most of the cases, the result from Left JOIN is mostly the same as one
from Right JOIN except that all the rows from the left table are also included.

Syntax:
1
SELECTcolumn_name
2 FROMtable1
3 LEFTJOINtable2
4 ONtable1.column_name=table2.column_name;

Example:
SELECTStudent_details.Name, Address,
1 Roll_no, Email_id
FROMStudent_details
2 LEFTJOINPersonal_details
3 ONStudent_details.Name=
4 Personal_details.Name;
Roll No. Address Email Id
Name
Akshay 1 Jaipur Akshay21@gmail.com
Charu 2 NULL NULL
Disha 3 Bombay Disha@gmail.com
Eva 4 NULL NULL
Himanshu 5 NULL NULL
Jitesh 6 Banglore Jitesh1990@gmail.com

Right JOIN in SQL:


Right SQL JOIN Query returns all the rows of the right table even if there are no matches in the
left table. Basically, the Right JOIN will return all the values from the right table along with the
matched values of the left table. Also, if there is no matched value found, the result will be
NULL.
Syntax:
1
SELECTcolumn_name
2 FROMtable1
3 RIGHTJOINtable2
4 ONtable1.column_name=table2.column_name;

Example:
SELECTPersonal_details.Name, Address, Roll_no,
1 Email_id
2 FROMStudent_details
3 RIGHTJOINPersonal_details

Come to Intellipaats SQL Community if you have more queries on SQL!


ONStudent_details.Name=
1 Personal_details.Name;
Name Address Roll Email ID
No.

Akshay Jaipur 1 Akshay21@gmail.com

Disha Bombay 3 Disha@gmail.com

Jitesh Banglore 6 Jitesh1990@gmail.com

FULL JOIN in SQL:


Full SQL JOIN Query returns all the rows from the left table and the right table. The result set is
created by combining all the rows of both tables. The results of LEFT JOIN and RIGHT JOIN
are combined to arrive at the result of FULL JOIN.
Syntax:
SELECTcolumn_name
1 FROMtable1
FULLOUTERJOINtable2
2 ONtable1.column_nam
3 e=table2.column_nam
4 e;
Example:
1 SELECTStudent_details.Name, Roll_no, Address
FROMStudent_details
2 FULLOUTERJOINPersonal_details
3 ONStudent_details.Name=
4 Personal_details.Name;
Name Roll No. Address

Akshay 1 Jaipur

Charu 2 NULL

Disha 3 Bombay

Eva 4 NULL

Himanshu 5 NULL

Jitesh 6 Banglore

What is LEFT JOIN in SQL?


LEFT JOIN is a keyword used to select all rows from the left table and the matched values
between the two tables.
LEFT JOIN in SQL
The LEFT JOIN in SQL basically returns all records from the left table and the matched records
from the right tables. For example, lets say, we have two tables, Table A and Table B. When
LEFT JOIN is applied on these two tables, all records from Table A and only the matched
records from Table B will be displayed.

SQL LEFT JOIN Syntax


1 SELECTcolumns
2 FROMtable1
name
3 LEFTJOINtable2
4 name
ONtable1.coumn
_x =
table2.column_
y;

where SELECT, LEFT JOIN, and ON are the keywords, columns are the list of columns, table1
is the first table and table2 is the second table, and column_x and column_y are the columns for
performing the LEFT JOIN, followed by a semicolon.
SQL LEFT JOIN Example
Lets apply LEFT JOIN to two tables, the employee table, and the department table
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 LEFTJOINdepartment
3 ONemployee.e_dept = department.d_name;

After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully
What is RIGHT JOIN in SQL?
RIGHT JOIN is a keyword, which is used to select all rows from the right table and also the
matched values between the two tables.
RIGHT JOIN in SQL
The RIGHT JOIN basically returns all records from the right table and the matched records from
the left table. For example, lets say, we have two tables, Table A and Table B, when the left join
is applied to these two tables, it would give all records from Table B and only the matched
records from Table A.

SQL RIGHT JOIN Syntax


1 SELECTcolumns
FROMtable1 name
2 RIGHTJOINtable2 name
3 ONtable1.coumn_x =
4 table2.column_y;

where SELECT, RIGHT JOIN, and ON are the keywords, columns is the list of
columns, table1 is the first table and table2 is the second table, and column_x and column_y are
the columns for performing the RIGHT JOIN, followed by a semicolon.
SQL RIGHT JOIN Example
Lets apply SQL RIGHT JOIN to two tables, the employee table, and the department table:
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 RIGHTJOINdepartment
3 ONemployee.e_dept = department.d_name;
After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully.

What is INNER JOIN in SQL?


INNER JOIN is a keyword, which is used to select all rows from the participating tables in
SQL as long as there is a match between columns.
INNER JOIN in SQL
SQL INNER JOIN gives records that have matching values in the participating tables. For
example, lets say, we have two tables, Table A and Table B. When INNER JOIN in SQL is
applied to these two tables, it will get only those records that are common to both Table A and
Table B

Interested in learning SQL? Enroll in our SQL Training now!

SQL INNER JOIN Syntax


SELECTcolumns
FROMtable1
name
INNERJOINtable
1 2 name
ONtable1.coumn
2 _x =
3 table2.column_
4 y;

where SELECT, INNER JOIN, and ON are the keywords, columns are the list of columns,
table1 is the first table, table2 is the second table, and column_x and column_y are the columns
for performing the INNER JOIN, followed by a semicolon.
SQL INNER JOIN Example
Lets apply SQL INNER JOIN to two tables, the employee table, and the department table
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 INNERJOINdepartment
3 ONemployee.e_dept = department.d_name;

After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully.
This brings us to the end of this INNER JOIN in SQL tutorial section. Go ahead and link the
tables from your database to get a better insight into your data.
What is FULL JOIN in SQL?
Under SQL joins, FULL JOIN is a keyword, which is used to select all records from the right
table and also from the left table
FULL JOIN in SQL
The FULL JOIN basically returns all records from the left table and also from the right table. For
example, lets say, we have two tables, Table A and Table B. When FULL JOIN is applied on
these two tables, it returns us all records from both Table A and Table B. If the condition is not
met, then the null value is displayed instead.

SQL FULL JOIN Syntax


1 SELECTcolumns
FROMtable1 name
2 FULLJOINtable2 name
3 ONtable1.coumn_x =
4 table2.column_y;

where SELECT, FULL JOIN, and ON are the keywords, columns are the list of columns, table1
is the first table, table2 is the second table, and column_x and column_y are the columns for
performing Left Join, followed by a semicolon.
SQL FULL JOIN Example
Lets apply FULL JOIN to two tables, the employee table, and the department table
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 FULLJOINdepartment
3 ONemployee.e_dept = department.d_name;

After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully.
This brings us to the end of this tutorial section on JOIN operators.

What is RDBMS?
RDBMS stands for Relational Database Management System. It is an information management
system that is oriented on a data model. Here all the information is properly stored as tables.
RDBMS Example systems are SQL Server, Oracle, MySQL, MariaDB, and SQLite.
Basic Features of RDBMS:
 Offers information to be saved in the tables
 Numerous users can access it together which is managed by a single user
 Virtual tables are available for storing the insightful data
 In order to exclusively find out the rows, the primary key is used
 The data are always saved in rows and columns
 To retrieve the information the indexes are used
 Columns are being shared between tables using the keys
RDBMS CONCEPTS
Relation in the RDBMS is the deposit of tuples having similar characteristics. A relation in
RDBMS means the set of the entities and data contained in them. The entities are different
instances and their relation is organized in different rows and columns in the data table. The
related information is of identical domains and constraints. By deleting old data and by inserting
new data, relations are altered in the database model.
Domain in RDBMS
The domain describes probable terms collected jointly that always have the same characteristics
and also constraints. A domain can be involved in a feature but only if the feature is a factor of a
particular set.
RDBMS Database
A relational database is a structured repository of data that arranges information in
predetermined connections. It stores data in tables consisting of columns and rows, enabling
clear visualization and comprehension of the relationships between various data elements.
The RDBMS speaks about relations between different entities present in the database.
Normal databases assist only the tables while RDBS along with the tables tells their connections
too. Normal databases give consistent methods but databases of RDBMS do not offer any
methodologies but instead give connections that connect one single object with another.
The stored database is called executable code. The database collects and saves data and that
particular procedure is called the stored procedure. During this, the codes are also stored which
are used for encapsulation, deleting, etc. The programmers are able to add extensions of the
syntaxes of SQL due to the applications of the APIs in the stored processes.
Constraints
Constraints are sort of limitations functional to the database. They make available the way to
employ the trade logic and the regulations in the database. In the database, it can be applied in
the type of confirming limits that verify the set of laws that the developer has missed. The
constraint is also restricting the facts that can be saved in the relations. They are applied to verify
the provinces performance and to keep it protected.
The Main Principles Of The RDBMS Model are:
 Entity integrity: Entity integrity says that in a database, all the data should be organized
having a single key. The uniqueness of all the data is maintained by this principle.
 Referential integrity: Referential integrity means that in the database all table values stay
true for all foreign keys.

RDBMS Operators
There are several relational operators that perform on the RDBMS. They are:

 The union operator mingles the rows of 2 relations and ignores the replacement. It also takes
out the copied ones from the output.
 The intersection operator gives a collection of rows that is identical to two relations.
 The difference operator gives the result by having 2 relations and gives the difference of
rows from the first that dont exist in the second.
 Cartesian product is done on two relations. It works as a cross-join operator.

Primary and Foreign Keys


Primary key:
The primary key finds out the similarity in the relationship. For the entire table, there is only one
primary key. Every table has got a particular primary key that cannot be shared by other tables.
Foreign key:
The foreign key is a key used for a different table of data which is referred by the primary key.
There are many foreign keys for a single table. It depends on the primary key and its decision to
refer those foreign keys to the table. Every foreign key can be shared and it speaks about the
coordination among the data of different tables.
Learn about the difference between DBMS and RDBMS in our blog on DBMS vs RDBMS!
Index in RDBMS
For faster access to the data and their structure, the indexes are used. Combining all the
characteristics makes it possible to find out the data faster and also allows similar data to be
found very comfortably.
Courses you may like
RDBMS Normalization
Normalization is a crucial process in database design that aims to eliminate redundancy and
inconsistency, ensuring data integrity and efficiency. It involves organizing data into multiple
tables and defining relationships between them. Lets delve deeper into the concept of
normalization, its need, data anomalies, various forms of normalization, and the advantages and
disadvantages associated with it.
The Need for Normalization:
Data redundancy is a common problem in databases, leading to anomalies such as update,
insertion, and deletion anomalies. These anomalies can result in inconsistencies, data integrity
issues, and inefficiencies in data retrieval and manipulation. Normalization addresses these
problems by breaking down data into smaller, logical units, reducing redundancy, and ensuring
efficient data management.
Data Anomalies:
Data anomalies are inconsistencies that occur when manipulating or accessing data. These
anomalies include:
Update Anomaly: This occurs when modifying data in one place but not updating the
corresponding values in other places, leading to inconsistent data.
Insertion Anomaly: Inserting data into a table may require providing incomplete information or
duplicating data, causing inconsistencies.
Deletion Anomaly: Removing data from a table may unintentionally remove other related data
that is still needed, resulting in data loss and inconsistencies.
There are 9 normalizations that are used inside the database. These are as follows:

 First normal form (1NF): this table represents a relation of unique groups.
 Second normal form (2NF): Is not practically charged on the division of any contender key.
 Third normal form (3NF): every non-prime feature is non-transitively charged on every
contender key
 Elementary key normal form: This key dependency modifies the practical dependency in a
table.

Advantages of Normalization
Data Integrity: Normalization reduces data redundancy, minimizing the risk of inconsistencies
and ensuring data integrity.
Flexibility: Normalized databases are more flexible and adaptable to changes in data
requirements.
Efficient Data Retrieval: Normalization improves query performance by reducing the size of
tables and eliminating unnecessary data repetition.
Simplified Updates: With normalized databases, updates are more straightforward and require
modifying data in fewer places.
Disadvantages of Normalization
Increased Complexity: The process of normalization can introduce complexity in designing and
maintaining the database structure.
Join Operations: Normalization often leads to the need for join operations to retrieve data from
multiple tables, which can impact query performance.
Overnormalization: Overnormalization, where excessive normalization is applied, can result in
unnecessary complexity and reduced performance.

 Normalization:

Normalization is a technique which is used to organize the data in the database. It is a systematic
approach to remove the data redundancy. Normalization is mainly used for two purpose,

 To remove data redundancy.


 Ensuring data dependencies is proper.

Without normalization 3 anomalies occurred and it becomes difficult to handle and update data.
To understand these anomalies lets take an Student table
ID Name Address Subject
201 Akshay Jaipur Maths
202 Charu Bombay Bio
203 Disha Banglore Physics
204 Eva Noida Maths

 Updation Anamoly – To update address of a student who occurs twice or more than twice in
a table, we will have to updateAddress column in all the rows, else data will become
inconsistent.
 Insertion Anamoly – Suppose for a new admission, we have a Student id, name and address
of a student but if student has not opted for any subject yet then we have to
insertNULL there, leading to Insertion Anamoly.
 Deletion Anamoly – If id 401 has only one subject and temporarily he drops it, when we
delete that row, entire student record will be deleted along with id.

Normalization Form:
Normalization Rules are divided into 4 normal forms.

 First Normal Form


 Second Normal Form
 Third Normal Form
 BCNF

First Normal Form:


As per First Normal Form, no two rows of data must contain repeating data i.e., whenever we
search for a particular result the multiple columns cannot be used to fetch the same row.
Each table should be organized into rows, and each row should have a primary key that
distinguishes it as unique.
For example, consider a table not in first normal form
Student Age Subject

Akshay 15 Maths, Physics

Charu 14 Biology

Disha 17 Maths

Student table in 1NF will be:


Student Age Subject

Akshay 15 Maths

Akshay 15 Physics

Charu 14 Biology

Disha 17 Maths

Using the First Normal Form, data redundancy increases, as there will be many columns with the
same data in multiple rows but each row as a whole will be unique.
Second Normal Form:
As per the Second Normal Form there must not be any partial dependency of any column on
primary key. It means that for a table that has concatenated primary key, each column in the
table that is not part of the primary key must depend upon the entire concatenated key for its
existence.
 Meet all the requirements of the first normal form.
 Remove subsets of data that apply to multiple rows of a table and place them in separate
tables.
 Create relationships between these new tables and their predecessors through the use of
foreign keys.

For example:
New student table following 2NF will be:
Student Age

Akshay 15

Charu 14

Disha 17

In Student Table the candidate key will be Student column, because all other column i.e Age is
dependent on it.
Student Subject

Akshay Maths

Akshay Physics

Charu Biology

Disha Maths

In Subject Table the candidate key will be {Student, Subject} column. Now, both the above
tables qualifies for Second Normal Form and will never suffer from Update Anomalies.
Third Normal Form:
 A relation is in third normal form (3NF) if it is in second normal form and it contains no
transitive dependencies.
 Consider relation R containing attributes A, B and C. R(A, B, C)
 If A →B and B →C then A →C
 Transitive Dependency: Three attributes with the above dependencies.

For example:
Student_details table
ID Name Subject DOB Address Mobile No. City

New Student_detail table:


ID Name Subject
Address Table:
ID Address DOB Mobile No. City

The advantage of removing transtive dependency is,

 Amount of data duplication is reduced.


 Data integrity achieved.

Boyce and Codd Normal Form (BCNF):


This is a higher version of third normal form. This form deals with certain type of anamoly that
is not handled by 3NF. A 3NF table which does not have multiple overlapping candidate keys is
said to be in BCNF. For a table to be in BCNF, following conditions must be satisfied:

 R must be in 3rd Normal Form


 and, for each functional dependency ( X ->Y ), X should be a super Key.

Data Abstraction
Data abstraction is a fundamental concept in computer science and software development that
involves representing complex data and operations in a simplified and manageable way. It is a
technique that allows us to focus on the essential aspects of data while hiding unnecessary
details.
There are 3 stages of data generalization. And they are:
Physical level:
It is the least possible stage that explains how information is stored in the database.
Logical level:
It is the next senior stage in the ladder that gives the generalization. It tells what information is
stored and also tells the connection among them.
View level:
It is the uppermost stage in the ladder that explains part of the whole database. It enables the
consumer to view the database and do an inquiry.

RDBMS Extensions and Intensions


Extension :
Extension describes the number of tuples existing in a table at any time and it is completely
dependent on time.
Intension :
Intension tells about the name, configuration, and limitations of the table and does not depend on
time.
Data Independence in RDBMS
The freedom of the information stored inside any application is termed data independence. It is
for the storage configuration and allows amending the representation of the data stored in the
database. But is not able to modify the representations done in the supreme stage.
There are two kinds of data independence:
Physical Data Independence:
It enables the alteration to be completed in the physical point and never is going to have an effect
on the logical part.
Logical Data Independence:
It enables the amendment to be completed at the logical part and also it affects the view level.
View
For watching the information, there is a virtual table of rows and columns this virtual table is
called a view. It is saved in the data directory and displays the file. Since it is a virtual table and
has no physical existence, it is related to the logical level.
E-R Model
The full form of this E-R model is the entity relationship. This is a form of representing objects
inside the database and the relationships between the different objects. The practical world also
represents various entities and the relationship between those different entities
ACID
ACID stands for Atomicity, Consistency, Isolation, and Durability and it performs an imperative
task in the database. The ACID features assist in controlling the accuracy of the information in
the data center. The ACID features make the database easy to use. It enables the protected
sharing of data among the tables. Without the ACID features, the data will be conflicting and
also it will become imprecise.
ACID Properties
ACID Property is the most important part of the database. ACID stands for Atomicity
Consistency Isolation Durability.
Atomicity:
This means that all or nothing. When an update occurs to a database either all or none of the
update will become available to anyone beyond the user. This update to the database is called a
transaction and it either commits or aborts.
Consistency:
It ensures that any changes to values in an instance are consistent with changes to other values in
the same instance.
Isolation:
Isolation is is needed when there are concurrent transactions. Concurrent transactions are
transactions that occur at the same time, such as shared multiple users accessing shared objects.
An important concept to understanding isolation through transactions is serializability.
Transactions are serializable when the effect on the database is the same whether the transactions
are executed in serial order or in an interleaved fashion.
Durability:
Maintaining updates of committed transactions is important. These updates must never be lost.
The ACID property of durability addresses this need. Durability refers to the ability of the
system to recover committed transaction updates if either the system or the storage media fails.

Cardinality
For arranging and properly organizing the information stored, we use cardinality. This
arrangement tool is utilized in the entity-relationship diagrams representing relationships
between different entities in the table. The cardinality is of different types and they are :
One to one:
This cardinality connects one single object with another single object.
One to many:
This cardinality connects one single object with many single objects.
Many to many:
This cardinality connects many single objects with many other single objects.
Many to one:
This cardinality connects many objects with one single object

RDBMS Advantages
 Data is only stored once so multiple documentation changes are not required
 Better safety measures
 The table arrangement is straightforward and simple for database users to appreciate and
use.
 RDBMSs permit numerous database users to admittance a database concurrently.
 RDBMS agree with the database manager to limit admission to certified users, and gift
rights to entity users depending on the kinds of database work they do
 RDBMSs offer admission to the database via a server daemon, a dedicated software
program that responds to requirements on a set of connections, and enables database users to
connect and make use of the database.
 RDBMSs feature safeguarding supply database managers with tools to without difficulty
preserve analysis, revamp, and back up the data centers.
 RDBMSs support SQL language.

You might also like