SQL INSERT INTO Statement
Last Updated :
02 Dec, 2024
The INSERT INTO statement is a fundamental SQL command used to add new rows of data into a table in a database. It is one of the most commonly used SQL statements for manipulating data and plays a key role in database management.
This article will explore the SQL INSERT INTO statement in detail, showing how to use it effectively with multiple examples. We’ll cover both basic and advanced usage, including inserting individual rows, multiple rows, and even copying data between tables.
SQL INSERT INTO Statement
- The
INSERT INTO statement in SQL is used to add new rows of data to a table in a database.
- There are two main ways to use the
INSERT INTO statement by specifying the columns and values explicitly or by inserting values for all columns without specifying them.
There are two primary syntaxes of INSERT INTO statements depending on the requirements. The two syntaxes are:
Syntax 1. Only Values
The first method is to specify only the value of data to be inserted without the column names.
INSERT INTO table_name
VALUES (value1, value2, value);
Parameters:
- table_name: name of the table.
- value1, value2: value of first column, second column,… for the new record
Syntax 2. Column Names And Values Both
In the second method we will specify both the columns which we want to fill and their corresponding values as shown below:
INSERT INTO table_name (column1, column2, column3)
VALUES ( value1, value2, value);
Parameters:
- table_name: name of the table.
- column1, column2..: name of first column, second column.
- value1, value2, value..: the values for each specified column of the new record.
Examples of SQL INSERT INTO
For better understanding, let’s look at the SQL Server INSERT statement with examples.
Let us first create a table named ‘Student‘.
CREATE DATABASE StudentDB;
USE StudentDB;
CREATE TABLE Student (
ROLL_NO INT PRIMARY KEY,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(15),
AGE INT
);
INSERT INTO Student (ROLL_NO, NAME, ADDRESS, PHONE, AGE) VALUES
(1, 'Ram', 'Delhi', 'XXXXXXXXXX', 18),
(2, 'Ramesh', 'Gurgaon', 'XXXXXXXXXX', 18),
(3, 'Sujit', 'Rohtak', 'XXXXXXXXXX', 20),
(4, 'Suresh', 'Rohtak', 'XXXXXXXXXX', 18);
Created Table:
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
AGE |
| 1 |
Ram |
Delhi |
xxxxxxxxxxxxxx |
18 |
| 2 |
RAMESH |
GURGAON |
xxxxxxxxxxxxxx |
18 |
| 3 |
SUJIT |
ROHTAK |
xxxxxxxxxxxxxx |
20 |
| 4 |
SURESH |
ROHTAK |
xxxxxxxxxxxxxx |
18 |
| 3 |
SUJIT |
ROHTAK |
xxxxxxxxxxxxxx |
20 |
| 2 |
RAMESH |
GURGAON |
xxxxxxxxxxxxxx |
18 |
Now, Suppose we want to add values.
Example 1: Inserting Only New Values Using INSERT INTO Example
If we want to insert only values then we use the following query.
Query:
INSERT INTO Student
VALUES ('5','HARSH','WEST BENGAL', 'XXXXXXXXXX','19');
Output:
The table Student will now look like this:
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
Age |
| 1 |
Ram |
Delhi |
XXXXXXXXXX |
18 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 4 |
SURESH |
Delhi |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 5 |
HARSH |
WEST BENGAL |
XXXXXXXXXX |
19 |
Example 2: Insert Values to Specified Columns Using INSERT INTO Example
If we want to insert values in the specified columns then we use the following query.
Query:
INSERT INTO Student (ROLL_NO, NAME, Age)
VALUES ('5','PRATIK','19');
Output:
The table Student will now look like this:
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
Age |
| 1 |
Ram |
Delhi |
XXXXXXXXXX |
18 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 4 |
SURESH |
Delhi |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 5 |
PRATIK |
null |
null |
19 |
Note: Columns not included in the INSERT statement are filled with default values (typically NULL).
INSERT Multiple Rows in MS SQL Server
We can insert multiple rows into a table using a single INSERT INTO statement. This method saves time and reduces the potential for errors.
Syntax
INSERT INTO table_name(Column1,Column2,Column3,.......)
VALUES
(Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
(Value1, Value2,Value3,.....),
............................. ;
Parameters:
- table_name: name of the table.
- Column 1: name of the first column, second column.
- Values: Value1, Value2, Value3: the value of the first column, second column.
Example of Insert Multiple Rows in a table using Single SQL Statement
The following SQL statement inserts multiple rows in Student Table.
Query:
INSERT INTO Student (ROLL_NO, NAME, AGE, ADDRESS, PHONE)
VALUES
(6, 'Amit Kumar', 15, 'Delhi', 'XXXXXXXXXX'),
(7, 'Gauri Rao', 18, 'Bangalore', 'XXXXXXXXXX'),
(8, 'Manav Bhatt', 17, 'New Delhi', 'XXXXXXXXXX'),
(9, 'Riya Kapoor', 10, 'Udaipur', 'XXXXXXXXXX');
Output:
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
AGE |
| 1 |
Ram |
Delhi |
XXXXXXXXXX |
18 |
| 2 |
Ramesh |
Gurgaon |
XXXXXXXXXX |
18 |
| 3 |
Sujit |
Rohtak |
XXXXXXXXXX |
20 |
| 4 |
Suresh |
Rohtak |
XXXXXXXXXX |
18 |
| 5 |
Pratik |
NULL |
NULL |
19 |
| 6 |
Amit Kumar |
Delhi |
XXXXXXXXXX |
15 |
| 7 |
Gauri Rao |
Bangalore |
XXXXXXXXXX |
18 |
| 8 |
Manav Bhatt |
New Delhi |
XXXXXXXXXX |
17 |
| 9 |
Riya Kapoor |
Udaipur |
XXXXXXXXXX |
10 |
If a user wants to insert more than 1000 rows, multiple insert statements, bulk insert or derived table must be used.
Using SQL INSERT INTO SELECT
The SQL INSERT INTO SELECT statement is used to copy data from one table and insert it into another table. The use of this statement is similar to that of the INSERT INTO statement.
The difference is that the SELECT statement is used here to select data from a different table. The different ways of using INSERT INTO SELECT statement are shown below:
Syntax of INSERT INTO SELECT
There are two syntaxes for using INSERT INTO SELECT statement, depending on it’s use.
1. Copy All Columns and Insert
The syntax for using INSERT INTO SELECT query to insert all data from a table to another table:
INSERT INTO first_table
SELECT *
FROM second_table;
Parameters:
- first_table: name of first table.
- second_table: name of second table.
We have used the SELECT statement to copy the data from one table and the INSERT INTO statement to insert from a different table.
2. Copy Specific Columns and Insert
The syntax for using INSERT INTO SELECT query to insert specific data from a table to another table:
INSERT INTO first_table(names_of_columns1)
SELECT names_of_columns2
FROM second_table;
Parameters:
- first_table: name of first table. second_table: name of second table.
- names of columns1: name of columns separated by comma(,) for table 1.
- names of columns2: name of columns separated by comma(,) for table 2.
We have used the SELECT statement to copy the data of the selected columns only from the second table and the INSERT INTO statement to insert in the first table.
3. Copy Specific Rows and Insert
We can copy specific rows from a table to insert into another table by using the WHERE clause with the SELECT statement. We have to provide appropriate conditions in the WHERE clause to select specific rows.
The syntax for using INSERT INTO SELECT query to insert specific rows from table
INSERT INTO table1
SELECT * FROM table2
WHERE condition;
Parameters:
- first_table: name of first table.
- second_table: name of second table.
- condition: condition to select specific rows.
Examples of SQL INSERT INTO SELECT
Let’s look at some examples of INSERT INTO SELECT statement to understand it better.
Suppose there is a LateralStudent database.
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
Age |
| 7 |
SOUVIK |
HYDERABAD |
XXXXXXXXXX |
18 |
| 8 |
NIRAJ |
NOIDA |
XXXXXXXXXX |
19 |
| 9 |
SOMESH |
ROHTAK |
XXXXXXXXXX |
20 |
Example 1: Inserting all rows and columns using INSERT INTO SELECT example
If we want to insert only values then we use the following query:
Query:
INSERT INTO Student
SELECT * FROM LateralStudent;
Output:
This query will insert all the data of the table LateralStudent in the table Student. The table Student will now look like this,
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
Age |
| 1 |
Ram |
Delhi |
XXXXXXXXXX |
18 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 4 |
SURESH |
Delhi |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 7 |
SOUVIK |
DUMDUM |
XXXXXXXXXX |
18 |
| 8 |
NIRAJ |
NOIDA |
XXXXXXXXXX |
19 |
| 9 |
SOMESH |
ROHTAK |
XXXXXXXXXX |
20 |
Example 2: Inserting specific columns using INSERT INTO SELECT
If we want to insert values in the specified columns then we use the following query:
Query:
INSERT INTO Student(ROLL_NO,NAME,Age)
SELECT ROLL_NO, NAME, Age FROM LateralStudent;
Output:
This query will insert the data in the columns ROLL_NO, NAME, and Age of the table LateralStudent in the table Student and the remaining columns in the Student table will be filled by null which is the default value of the remaining columns. The table Student will now look like this,
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
Age |
| 1 |
Ram |
Delhi |
XXXXXXXXXX |
18 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 4 |
SURESH |
Delhi |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 7 |
SOUVIK |
null |
null |
18 |
| 8 |
NIRAJ |
null |
null |
19 |
| 9 |
SOMESH |
null |
null |
20 |
Example 3: Insert specific rows using INSERT INTO SELECT
INSERT INTO Student
SELECT * FROM LateralStudent WHERE Age = 18;
Output:
This query will select only the first row from table LateralStudent to insert into the table Student. The table Student will now look like this,
| ROLL_NO |
NAME |
ADDRESS |
PHONE |
Age |
| 1 |
Ram |
Delhi |
XXXXXXXXXX |
18 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 4 |
SURESH |
Delhi |
XXXXXXXXXX |
18 |
| 3 |
SUJIT |
ROHTAK |
XXXXXXXXXX |
20 |
| 2 |
RAMESH |
GURGAON |
XXXXXXXXXX |
18 |
| 7 |
SOUVIK |
DUMDUM |
XXXXXXXXXX |
18 |
Important Points About SQL INSERT INTO Statement
- The ‘INSERT INTO‘ statement is used to add new records to a table in a database
- It allows inserting multiple records in a single statement by providing multiple sets of values.
- If you don’t specify column names, the statement assumes all columns and the values must be in the same order as the table definition.
- Columns not included in the INSERT statement will be filled with default values, which are typically NULL.
- Using a single
INSERT INTO statement for multiple rows improves efficiency and reduces potential errors.
Conclusion
Overall, INSERT INTO statement is an essential feature in SQL for adding new data to tables. Whether you’re adding a single row or multiple rows, specifying column names or copying data from another table, INSERT INTO provides the necessary flexibility. Understanding its syntax and usage is crucial for efficient database management and data manipulation.
FAQs
What is the INSERT INTO statement in SQL?
The INSERT INTO statement in SQL is used to add new rows of data to a table. It can either specify the columns to insert data into or insert data into all columns if they are provided in order. This statement is fundamental for data insertion operations in a database.
Which SQL statement is used to insert?
The INSERT INTO statement is the SQL command used to insert new rows into a table. It allows for the addition of new records by specifying the table name, column names (optional), and the corresponding values to be inserted.
What is the difference between `SELECT INTO` and `INSERT INTO` in SQL?
The SELECT INTO statement is used to create a new table and populate it with data from an existing table based on a SELECT query. In contrast, the INSERT INTO statement adds new rows to an existing table without creating a new table. INSERT INTO can insert specific values or copy data from another table, whereas SELECT INTO focuses on creating and populating a new table in one step.
Similar Reads
SQL Tutorial
In this SQL tutorial, you’ll learn all the basic to advanced SQL concepts like SQL queries, SQL join, SQL injection, SQL insert, and creating tables in SQL. SQL is easy to learn, there are no prerequisites to learn SQL. So, SQL is a standard database language used to access and manipulate data in da
11 min read
SQL Basics
What is Database?
A database is an organized collection of data stored in a computer system and usually managed by a database management system (DBMS). The most commonly used types of databases are Relational and NoSQL.The data in relational databases is modeled in tables, making querying and processing efficient. St
7 min read
Types of Databases
Every company relies on data, making its management essential. Data can be both Structured and Unstructured. Efficient data handling ensures that data is securely stored, accessed, and modified as needed, supporting smooth business operations. Proper data management not only aids in decision-making
9 min read
Introduction of DBMS (Database Management System)
A database is a collection of interrelated data that helps in the efficient retrieval, insertion, and deletion of data from the database and organizes the data in the form of tables, views, schemas, reports, etc. For Example, a university database organizes the data about students, faculty, admin st
8 min read
Non-Relational Databases and Their Types
In the area of database management, the data is arranged in two ways which are Relational Databases (SQL) and Non-Relational Databases (NoSQL). While relational databases organize data into structured tables, non-relational databases use various flexible data models like key-value pairs, documents,
7 min read
What is SQL?
SQL stands for Structured Query Language. It is a standardized programming language used to manage and manipulate relational databases. It enables users to perform a variety of tasks such as querying data, creating and modifying database structures, and managing access permissions. SQL is widely use
10 min read
SQL Data Types
SQL Data Types are the pillar of relational database schema design. It ensures that data is stored efficiently and accurately. Data types define the type of value a column can hold, such as numbers, text, or dates. Understanding SQL Data Types is critical for database administrators, developers, and
5 min read
SQL Operators
SQL operators are important in database management systems (DBMS) as they allow us to manipulate and retrieve data efficiently. Operators in SQL perform arithmetic, logical, comparison, bitwise, and other operations to work with database values. Understanding SQL operators is crucial for performing
5 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are essential for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will
7 min read
Create Database in SQL
SQL CREATE DATABASE
The CREATE DATABASE statement is a foundational SQL command used to create new databases in SQL-based Database Management Systems (DBMS), including MySQL, PostgreSQL, SQL Server, and others. Understanding how to use this command effectively is crucial for developers, database administrators, and any
4 min read
SQL DROP DATABASE
The SQL DROP DATABASE statement is an important command used to permanently delete a database from the Database Management System (DBMS). When executed, this command removes the database and all its associated objects, including tables, views, stored procedures, and other entities. In this article,
4 min read
SQL Query to Rename Database
Renaming a database in SQL is an essential task that database administrators and developers frequently perform. Whether you’re reorganizing your data, correcting naming conventions, or simply updating your project structure, knowing how to rename a database properly is critical. In this article, we'
3 min read
SQL Select Database
The USE DATABASE statement is a command in certain SQL-based database management systems that allows users to select and set a specific database as the default for the current session. By selecting a database, subsequent queries are executed within the context of that database, making it easier to i
3 min read
Tables in SQL
SQL CREATE TABLE
The SQL CREATE TABLE statement is a foundational command used to define and structure a new table in a database. By specifying the columns, data types, and constraints such as PRIMARY KEY, NOT NULL, and CHECK, helps you design the database schema. In this article, we'll learn the syntax, best practi
4 min read
SQL DROP TABLE
The DROP TABLE command in SQL is a powerful and essential tool used to permanently delete a table from a database, along with all of its data, structure, and associated constraints such as indexes, triggers, and permissions. When executed, this command removes the table and all its contents, making
4 min read
SQL DELETE Statement
The SQL DELETE statement is one of the most commonly used commands in SQL (Structured Query Language). It allows you to remove one or more rows from the table depending on the situation. Unlike the DROP statement, which removes the entire table, the DELETE statement removes data (rows) from the tabl
4 min read
ALTER (RENAME) in SQL
In SQL, making structural changes to a database is often necessary. Whether it's renaming a table or a column, adding new columns, or modifying data types, the SQL ALTER TABLE command plays a critical role. This command provides flexibility to manage and adjust database schemas without affecting the
4 min read
DROP and TRUNCATE in SQL
The DROP and TRUNCATE commands in SQL are used to remove data from a table, but they work differently. Understanding the difference between these two commands is important for proper database management, especially when dealing with large amounts of data. This article provides an in-depth explanatio
4 min read
SQL Query to Create a Backup Table
Relational databases play an important role in managing data, especially during complex operations like updates and deletions. To maintain data integrity, it is essential to back up tables before making changes. SQL backup tables ensure the safety of the original dataset, allow for data recovery, an
5 min read
What is Temporary Table in SQL?
A temporary table in SQL is an important tool for maintaining intermediate results during query execution. They help store temporary data without affecting the underlying permanent tables. In this article, we’ll explore temporary tables in SQL, their types (local vs. global), and how to use them eff
3 min read
SQL ALTER TABLE
The SQL ALTER TABLE statement is a powerful tool that allows you to modify the structure of an existing table in a database. Whether you're adding new columns, modifying existing ones, deleting columns, or renaming them, the ALTER TABLE statement enables you to make changes without losing the data s
4 min read
SQL Queries
SQL SELECT Query
The select query in SQL is one of the most commonly used SQL commands to retrieve data from a database. With the select command in SQL, users can access data and retrieve specific records based on various conditions, making it an essential tool for managing and analyzing data. In this article, we’ll
4 min read
SQL TOP, LIMIT, FETCH FIRST Clause
SQL TOP, LIMIT, and FETCH FIRST clauses are used to retrieve a specific number of records from a table. These clauses are especially useful in large datasets with thousands of records. Each of these SQL clauses performs a similar operation of limiting the results returned by a query, but different d
8 min read
SQL SELECT FIRST
The SELECT FIRST clause is used in some SQL databases (primarily MS Access) to retrieve the first record from a table based on the order in which data is stored or queried. It is commonly used when you need to access just one entry, such as the first row based on the natural order or after sorting b
3 min read
SQL - SELECT LAST
SELECT LAST is a concept or function often used to describe retrieving the last record or last row from a table in SQL. Although MS Access supports a LAST() function to directly fetch the last value from a column, this function is not universally supported across all SQL-based databases. Instead, in
5 min read
SQL - SELECT RANDOM
In SQL, the RANDOM() function is used to fetch random rows from a table. It is an extremely useful function in various applications, such as selecting random users, retrieving random questions from a pool, or even for random sampling in data analysis. In this article, we will explore how to use RAND
4 min read
SQL SELECT IN Statement
The IN operator in SQL is used to compare a column's value against a set of values. It returns TRUE if the column's value matches any of the values in the specified list, and FALSE if there is no match. In this article, we will learn how IN operator works and provide practical examples to help you b
4 min read
SQL - SELECT DATE
SQL (Structured Query Language) can work with datetime data types. SELECT DATE is an important concept when retrieving records that filter data based on date. Whether you work with employee records, transaction records, or product sales, modifying and retrieving date data is often important for your
3 min read
SQL Query to Insert Multiple Rows
In SQL, the INSERT statement is used to add new records to a database table. When you need to insert multiple rows in a single query, the INSERT statement becomes efficient. In this article, We will learn different methods such as using basic INSERT statements, utilizing INSERT INTO ... SELECT for b
4 min read
SQL INSERT INTO Statement
The INSERT INTO statement is a fundamental SQL command used to add new rows of data into a table in a database. It is one of the most commonly used SQL statements for manipulating data and plays a key role in database management. This article will explore the SQL INSERT INTO statement in detail, sho
8 min read
SQL UPDATE Statement
In SQL, the UPDATE statement is used to modify existing records in a table. Whether you need to update a single record or multiple rows at once, SQL provides the necessary functionality to make these changes. The UPDATE statement is essential for maintaining the integrity of your data by allowing yo
4 min read
SQL DELETE Statement
The SQL DELETE statement is one of the most commonly used commands in SQL (Structured Query Language). It allows you to remove one or more rows from the table depending on the situation. Unlike the DROP statement, which removes the entire table, the DELETE statement removes data (rows) from the tabl
4 min read
SQL Query to Delete Duplicate Rows
Duplicate rows in a database can cause inaccurate results, waste storage space, and slow down queries. Cleaning duplicate records from our database is an essential maintenance task for ensuring data accuracy and performance. Duplicate rows in a SQL table can lead to data inconsistencies and performa
5 min read
SQL Clauses
SQL | WHERE Clause
The SQL WHERE clause allows to filtering of records in queries. Whether you're retrieving data, updating records, or deleting entries from a database, the WHERE clause plays an important role in defining which rows will be affected by the query. Without it, SQL queries would return all rows in a tab
4 min read
SQL | WITH Clause
The SQL WITH clause, also known as Common Table Expressions (CTEs), is a powerful tool that simplifies complex SQL queries, improves readability, and enhances performance by defining temporary result sets that can be reused multiple times. Whether we're working on aggregating data, analyzing large d
5 min read
SQL HAVING Clause with Examples
The HAVING clause was introduced in SQL to allow the filtering of query results based on aggregate functions and groupings. Unlike the WHERE clause, which filters individual rows before any grouping occurs, the HAVING clause works on groups of data that have been aggregated using functions like SUM(
4 min read
SQL ORDER BY
The ORDER BY clause in SQL is a powerful feature used to sort query results in either ascending or descending order based on one or more columns. Whether you're presenting data to users or analyzing large datasets, sorting the results in a structured way is essential. In this article, we’ll explain
5 min read
SQL | GROUP BY
The GROUP BY statement in SQL is used for organizing and summarizing data based on identical values in specified columns. By leveraging the GROUP BY clause, users can apply aggregate functions like SUM, COUNT, AVG, MIN, and MAX to each group, making it easier to perform detailed data analysis. In th
5 min read
SQL LIMIT Clause
The LIMIT clause in SQL is used to restrict the number of rows returned in a query result. This clause is particularly useful when working with large datasets, as it allows you to limit the output to only the rows you need for analysis or display. Whether you're looking to paginate results, find top
4 min read
SQL Operators
SQL AND and OR Operators
The SQL AND and OR operators are used to filter data based on multiple conditions. These logical operators allow users to retrieve precise results from a database by combining various conditions in SELECT, INSERT, UPDATE, and DELETE statements. In this article, we'll learn the AND and OR operators,
3 min read
SQL AND and OR Operators
The SQL AND and OR operators are used to filter data based on multiple conditions. These logical operators allow users to retrieve precise results from a database by combining various conditions in SELECT, INSERT, UPDATE, and DELETE statements. In this article, we'll learn the AND and OR operators,
3 min read
SQL LIKE Operator
The SQL LIKE operator is used for performing pattern-based searches in a database. It is used in combination with the WHERE clause to filter records based on specified patterns, making it essential for any database-driven application that requires flexible search functionality. In this article, we w
5 min read
SQL IN Operator
The SQL IN operator filters data based on a list of specific values. In general, we can only use one condition in the Where clause, but the IN operator allows us to specify multiple values. In this article, we will learn about the IN operator in SQL by understanding its syntax and examples. IN Opera
4 min read
SQL NOT Operator
The SQL NOT Operator is a logical operator used to negate or reverse the result of a condition in SQL queries. It is commonly used with the WHERE clause to filter records that do not meet a specified condition, helping you exclude certain values from your results. In this article, we will learn ever
3 min read
SQL NOT EQUAL Operator
The SQL NOT EQUAL operator is a comparison operator used to check if two expressions are not equal to each other. It helps filter out records that match certain conditions, making it a valuable tool in SQL queries. In this article, We will explore the SQL NOT EQUAL operator, including its syntax, us
4 min read
SQL IS NULL
The SQL IS NULL operator is a logical operator used to identify and filter out rows with NULL values in a column. A NULL value represents missing or undefined data in a database. It is different from a zero value or blank space, and it indicates that the value is unknown. In this article, we will le
4 min read
SQL UNION Operator
The SQL UNION operator is used to combine the result sets of two or more SELECT queries into a single result set. It is a powerful tool in SQL that helps aggregate data from multiple tables, especially when the tables have similar structures. In this guide, we'll explore the SQL UNION operator, how
4 min read
SQL UNION ALL
UNION ALL Operator is used to combine the results of two or more SELECT statements into a single result set. Unlike the UNION operator, which eliminates duplicate records and UNION ALL includes all duplicates. This makes UNION ALL it faster and more efficient when we don't need to remove duplicates.
4 min read
SQL | Except Clause
The SQL EXCEPT operator is used to return the rows from the first SELECT statement that are not present in the second SELECT statement. This operator is conceptually similar to the subtract operator in relational algebra. It is particularly useful for excluding specific data from your result set. In
4 min read
SQL BETWEEN Operator
The BETWEEN operator in SQL is used to filter records within a specific range. Whether applied to numeric, text, or date columns it simplifies the process of retrieving data that falls within a particular boundary. In this article, we will explore the SQL BETWEEN operator with examples. SQL BETWEEN
3 min read
SQL | ALL and ANY
In SQL, the ALL and ANY operators are logical operators used to compare a value with a set of values returned by a subquery. These operators provide powerful ways to filter results based on a range of conditions. In this article, we will explore ALL and ANY in SQL, their differences, and how to use
4 min read
SQL | ALL and ANY
In SQL, the ALL and ANY operators are logical operators used to compare a value with a set of values returned by a subquery. These operators provide powerful ways to filter results based on a range of conditions. In this article, we will explore ALL and ANY in SQL, their differences, and how to use
4 min read
SQL | INTERSECT Clause
In SQL, the INTERSECT clause is used to retrieve the common records between two SELECT queries. It returns only the rows that are present in both result sets. This makes INTERSECT an essential clause when you need to find overlapping data between two or more queries. The INTERSECT operator is part o
4 min read
SQL | EXISTS
The SQL EXISTS condition is used to test whether a correlated subquery returns any results. If the subquery returns at least one row, the EXISTS condition evaluates to TRUE; otherwise, it evaluates to FALSE. The EXISTS operator can be used in various SQL statements like SELECT, UPDATE, INSERT, and D
3 min read
SQL CASE Statement
The CASE statement in SQL is a versatile conditional expression that enables us to incorporate conditional logic directly within our queries. It allows you to return specific results based on certain conditions, enabling dynamic query outputs. Whether you need to create new columns, modify existing
4 min read
SQL Aggregate Functions
SQL Aggregate functions
SQL Aggregate Functions are used to perform calculations on a set of rows and return a single value. They are often used with the GROUP BY clause in SQL to summarize data for each group. Commonly used aggregate functions include COUNT(), SUM(), AVG(), MIN(), and MAX(). In this article, we'll learn t
3 min read
SQL COUNT(), AVG() and SUM() Function
SQL aggregate functions, such as COUNT(), AVG(), and SUM(), are essential tools for performing mathematical analysis on data. These functions allow you to gather valuable insights from your database, such as calculating totals, and averages, and counting specific rows. In this article, we’ll explain
3 min read
SQL COUNT(), AVG() and SUM() Function
SQL aggregate functions, such as COUNT(), AVG(), and SUM(), are essential tools for performing mathematical analysis on data. These functions allow you to gather valuable insights from your database, such as calculating totals, and averages, and counting specific rows. In this article, we’ll explain
3 min read
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() functions are essential aggregate functions in SQL used for data analysis. They allow you to extract the minimum and maximum values from a specified column, respectively, making them invaluable when working with numerical, string, or date-based data. In this article, we will
4 min read
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() functions are essential aggregate functions in SQL used for data analysis. They allow you to extract the minimum and maximum values from a specified column, respectively, making them invaluable when working with numerical, string, or date-based data. In this article, we will
4 min read
SQL COUNT(), AVG() and SUM() Function
SQL aggregate functions, such as COUNT(), AVG(), and SUM(), are essential tools for performing mathematical analysis on data. These functions allow you to gather valuable insights from your database, such as calculating totals, and averages, and counting specific rows. In this article, we’ll explain
3 min read
SQL Data Constraints
SQL NOT NULL Constraint
In SQL, constraints are used to enforce rules on data, ensuring the accuracy, consistency, and integrity of the data stored in a database. One of the most commonly used constraints is the NOT NULL constraint, which ensures that a column cannot have NULL values. This is important for maintaining data
3 min read
SQL | UNIQUE Constraint
In SQL, constraints play a vital role in maintaining the integrity and accuracy of the data stored in a database. One such constraint is the UNIQUE constraint, which ensures that all values in a column (or a combination of columns) are distinct, preventing duplicate entries. This constraint is espec
4 min read
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint in SQL is one of the most important constraints used to ensure data integrity in a database table. A primary key uniquely identifies each record in a table, preventing duplicate or NULL values in the specified column(s). Understanding how to properly implement and use the
5 min read
SQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is a fundamental concept in relational databases, ensuring data integrity by enforcing relationships between tables. By linking a child table to a parent table, the foreign key establishes referential integrity. This constraint ensures that the values in the foreign key co
4 min read
Composite Key in SQL
A composite key is a primary key that is made up of more than one column to uniquely identify records in a table. Unlike a single-column primary key, a composite key combines two or more columns to ensure uniqueness. While any of the individual columns in a composite key might not be unique on their
2 min read
SQL | UNIQUE Constraint
In SQL, constraints play a vital role in maintaining the integrity and accuracy of the data stored in a database. One such constraint is the UNIQUE constraint, which ensures that all values in a column (or a combination of columns) are distinct, preventing duplicate entries. This constraint is espec
4 min read
SQL - ALTERNATE KEY
Alternate Key is any candidate key not selected as the primary key. So, while a table may have multiple candidate keys (sets of columns that could uniquely identify rows), only one of them is designated as the Primary Key. The rest of these candidate keys become Alternate Keys. In other words, we ca
4 min read
SQL | CHECK Constraint
In SQL, One such constraint is the CHECK constraint, which allows to enforcement of domain integrity by limiting the values that can be inserted or updated in a column. By using CHECK, we can define conditions on a column’s values and ensure that they adhere to specific rules. In this article, we wi
5 min read
SQL | DEFAULT Constraint
In SQL, maintaining data integrity and ensuring consistency across tables is important for effective database management. One way to achieve this is by using constraints. Among the many types of constraints, the DEFAULT constraint plays an important role in automating data insertion and ensuring tha
3 min read
SQL Joining Data
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are the foundation of database management systems, enabling the combination of data from multiple tables based on relationships between columns. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understandi
6 min read
SQL Outer Join
SQL Outer Joins allow retrieval of rows from two or more tables based on a related column. Unlike inner Joins, they also include rows that do not have a corresponding match in one or both of the tables. This capability makes Outer Joins extremely useful for comprehensive data analysis and reporting,
4 min read
SQL LEFT JOIN
In SQL, LEFT JOIN allows to retrieval of all records from the left table and only the matching records from the right table. When there is no matching record in the right table, SQL will return NULL for columns from the right table. This makes LEFT JOIN extremely useful for queries where you need to
4 min read
SQL RIGHT JOIN
In SQL, the RIGHT JOIN (also called RIGHT OUTER JOIN) is an essential command used to combine data from two tables based on a related column. It returns all records from the right table, along with the matching records from the left table. If there is no matching record in the left table, SQL will r
4 min read
SQL FULL JOIN
In SQL, the FULL JOIN (or FULL OUTER JOIN) is a powerful technique used to combine records from two or more tables. Unlike an INNER JOIN, which only returns rows where there are matches in both tables, a FULL JOIN retrieves all rows from both tables, filling in NULL values where matches do not exist
4 min read
SQL CROSS JOIN
In SQL, the CROSS JOIN is a unique join operation that returns the Cartesian product of two or more tables. This means it matches each row from the left table with every row from the right table, resulting in a combination of all possible pairs of records. In this article, we will learn the CROSS JO
3 min read
SQL Self Join
A Self Join in SQL is a powerful technique that allows one to join a table with itself. This operation is helpful when you need to compare rows within the same table based on specific conditions. A Self Join is often used in scenarios where there is hierarchical or relational data within the same ta
4 min read
SQL | UPDATE with JOIN
In SQL, the UPDATE with JOIN statement is a powerful tool that allows updating one table using data from another table based on a specific JOIN condition. This technique is particularly useful when we need to synchronize data, merge records, or update specific columns in one table by referencing rel
4 min read
SQL DELETE JOIN
The SQL DELETE JOIN statement is a powerful feature that allows us to delete rows from one table based on conditions related to another table. This is particularly useful when managing relationships between tables in a database. For example, we may want to delete rows in a "Library Books" table wher
4 min read
Recursive Join in SQL
In SQL, a recursive join is a powerful technique used to handle hierarchical data relationships, such as managing employee-manager relationships, family trees, or any data with a self-referential structure. This type of join enables us to combine data from the same table repeatedly, accumulating rec
3 min read
SQL Functions
SQL Date and Time Functions
Handling date and time data in SQL is essential for many database operations. SQL provides a variety of date and time functions that help users work with date values, perform calculations, and format them as needed. Whether you’re adding intervals to dates, extracting parts of a date, or formatting
4 min read
SQL | String functions
SQL String Functions are powerful tools that allow you to manipulate, format, and extract specific parts of text data in your database. These functions are essential for tasks like cleaning up data, comparing strings, and combining text fields. Whether you're working with names, addresses, or any fo
5 min read
SQL | Numeric Functions
SQL Numeric Functions are essential tools for performing mathematical and arithmetic operations on numeric data. These functions allow you to manipulate numbers, perform calculations, and aggregate data for reporting and analysis purposes. Understanding how to use SQL numeric functions is important
4 min read
SQL - Statistical Functions
SQL statistical functions are essential tools for extracting meaningful insights from databases. These functions, enable users to perform statistical calculations on numeric data. Whether determining averages, sums, counts, or measures of variability, these functions empower efficient data analysis
4 min read
Working With JSON in SQL
JSON stands for Javascript Object Notation. It is mainly used in storing and transporting data. Mostly all NoSQL databases like MongoDB, CouchDB, etc., use JSON format data. Whenever your data from one server has to be transferred to a web page, JSON format is the preferred format for front-end appl
7 min read
Conversion Function in SQL
In SQL data type conversion is important for effective database management and accurate query results. Data type conversion ensures that data from different sources or columns can be correctly interpreted and manipulated, especially when dealing with different formats like numbers, text, dates, and
5 min read
SQL Data Types
SQL Data Types are the pillar of relational database schema design. It ensures that data is stored efficiently and accurately. Data types define the type of value a column can hold, such as numbers, text, or dates. Understanding SQL Data Types is critical for database administrators, developers, and
5 min read
SQL LTRIM() Function
The SQL LTRIM() function is an essential tool used in data cleaning and manipulation tasks. This function helps remove unwanted leading spaces or specific characters from the left side of a string or string expression. It's commonly used to tidy up data by eliminating unnecessary spaces or character
4 min read
SQL UPPER() Function
In SQL, the UPPER() function is one of the most commonly used string functions. It is used to convert all characters in a given string to uppercase. Whether we are dealing with textual data that requires uniform formatting or need to compare strings without case sensitivity, the UPPER() function com
4 min read
SQL RTRIM() Function
SQL RTRIM function is a string function that removes spaces from the right side of a character or string. RTRIM or Right Trim function is used in data cleaning and manipulation in SQL. In this example, we will learn the basics of the RTRIM function, and learn how it works with examples of different
4 min read
SQL Miscellaneous Topics
SQL Wildcard Characters
SQL wildcard characters are special symbols used in SQL queries to search for specific patterns within string data. These characters are particularly effective in the LIKE and NOT LIKE clauses, allowing for filtering results based on partial matches. In this article, We will learn about SQL Wildcard
3 min read
SQL Comments
SQL Comments explain sections of SQL statements or prevent SQL statements from being executed. There are 3 types of comments in SQL: Single-line commentsMulti-line commentsIn-line commentsThese are the three commenting methods in SQL, each with its unique use. Let's discuss these SQL comments in det
3 min read
Pivot and Unpivot in SQL
In SQL, Pivot and Unpivot are relational operators that are used to transform one table into another in order to achieve more simpler view of table. Conventionally we can say that Pivot operator converts the rows data of the table into the column data. The Unpivot operator does the opposite that is
2 min read
SQL Injection
SQL Injection is a security flaw in web applications where attackers insert harmful SQL code through user inputs. This can allow them to access sensitive data, change database contents or even take control of the system. It's important to know about SQL Injection to keep web applications secure. In
7 min read
SQL Performance Tuning
SQL Performance tuning is the process of enhancing SQL queries to speed up the server performance. Performance tuning in SQL shortens the time it takes for a user to receive a response after sending a query and utilizes fewer resources in the process. The idea is that users can occasionally produce
10 min read
SQL Stored Procedures
A stored procedure in SQL is a group of SQL queries that can be saved and reused multiple times. It is very useful as it reduces the need for rewriting SQL queries. It enhances efficiency, reusability, and security in database management. Users can also pass parameters to stored procedures so that t
4 min read
SQL TRANSACTIONS
Transactions group a set of tasks into a single execution unit. Each transaction begins with a specific job and ends when all the tasks in the group successfully completed. If any of the tasks fail, the transaction fails. Therefore, a transaction has only two results: success or failure. Example of
4 min read
SQL | Subquery
In SQL, subqueries are one of the most powerful and flexible tools for writing efficient queries. A subquery is essentially a query nested within another query, allowing users to perform operations that depend on the results of another query. This makes it invaluable for tasks such as filtering, cal
4 min read
SQL | SEQUENCES
SQL sequences specifies the properties of a sequence object while creating it. An object bound to a user-defined schema called a sequence produces a series of numerical values in accordance with the specification used to create it. The series of numerical values can be configured to restart (cycle)
5 min read
SQL Auto Increment
In SQL databases, a primary key is important for uniquely identifying records in a table. However, sometimes it is not practical to manually assign unique values for each record, especially when handling large datasets. To simplify this process, SQL databases offer an Auto Increment feature that aut
7 min read
Window Functions in SQL
SQL window functions are an essential tool for database management and data analysis. They allow users to perform advanced calculations across a specified set of rows known as a "window" while retaining the individual data rows. Unlike traditional aggregate functions that return a single result for
5 min read
How to Get Current Date and Time in SQL?
Managing date and time efficiently is crucial for any database system. SQL provides built-in functions to retrieve the current date and time, which are especially useful for applications involving logging, reporting, and auditing. In this article, we will explain the three main SQL functions to fetc
4 min read
What is Cursor in SQL ?
Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by Database Server at the Time of Performing DML(Data Manipulation Language) operations on the Table by the User. Cursors are used to store Database Tables. There are 2 types of Cursors: Implicit Cursors, and Explicit Cursors. T
6 min read
CTE in SQL
In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
5 min read
Dynamic SQL
Prerequisite - Difference between Static and Dynamic SQL Dynamic SQL is a programming technique that could be used to write SQL queries during runtime. Dynamic SQL could be used to create general and flexible SQL queries. Syntax for dynamic SQL is to make it string as below : 'SELECT statement'; To
2 min read
SQL Interview Questions
SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM Computer Scientists in the 1970s. By executing queries, SQL can create, update, delete, and retrieve data in databases like MySQL, Oracle, Postg
15+ min read