Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL SELECT FIRST
Next article icon

SQL TOP, LIMIT, FETCH FIRST Clause

Last Updated : 29 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 database management systems support them. In this article, we’ll explore the differences between these statements, provide syntax examples, and describe supporting databases.

SQL TOP, LIMIT, FETCH FIRST Clause

When working with large data sets in SQL, limiting the number of rows returned by a query can improve performance and make the data more manageable. The SQL SELECT TOP, LIMIT, and FETCH FIRST statements accomplish this purpose by limiting the result set to a specified number of row groups.

  • SQL TOP Clause is used in SQL Server and Sybase to limit the number of records returned.
  • SQL LIMIT Clause is utilized in MySQL, PostgreSQL, and SQLite.
  • SQL FETCH FIRST Clause is part of the SQL standard and is supported by Oracle, DB2, PostgreSQL, and SQL Server (as part of OFFSET-FETCH).

Depending on the database management system (DBMS) being used, you can utilize the respective clause to efficiently manage data retrieval. This article will provide examples and guidance on how to use the SQL TOP, LIMIT, and FETCH FIRST clauses in different SQL environments.

SQL SELECT TOP Clause

The SELECT TOP clause in SQL only returns the specified number of rows from the table. It is valuable on enormous tables with a large number of records. Returning countless records can affect execution.

Note: Not all database systems support the SELECT TOP clause.

The SQL TOP keyword is utilized with these database systems:

  • SQL Server
  • MS Access 

Syntax:

SELECT column1, column2, … TOP count
FROM table_name
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];

Here,

  • column1, column2 = names of columns
  • count = number of records to be fetched
  • WHERE conditions: Optional. Filters the data based on conditions.
  • ORDER BY expression: Optional. Sorts the result set in ascending or descending order.

SQL SELECT TOP Clause Example

Let’s understand this using an example of SQL SELECT TOP statement.

We will use the following table for this example:

demo sql table

Demo SQL Table

Write the following SQL queries to create this table

MySQL
CREATE TABLE Employee (    EmpId INTEGER PRIMARY KEY,     EmpName VARCHAR(225) NOT NULL,      Email VARCHAR(225) NOT NULL,       Address VARCHAR(225) NOT NULL,    Age INT NOT NULL,    Salary MONEY NOT NULL ); INSERT INTO Employee (EmpId, EmpName, Email, Address, Age, Salary) VALUES (1, 'Shubham', '[email protected]', 'India', 23, 50000.00),        (2, 'Aman', '[email protected]', 'Australia', 21, 45000.00),        (3, 'Naveen', '[email protected]', 'Sri Lanka', 24, 55000.00),        (4, 'Aditya', '[email protected]', 'Austria', 21, 42000.00),        (5, 'Nishant Saluja', '[email protected]', 'Spain', 22, 48000.00); 

Example 1: Using SELECT TOP Clause in SQL

In this example, we will fetch the top 4 rows from the table.

Query:

SELECT TOP 4* FROM Employee;

Output:

Output

SELECT TOP Clause Output

Example 2: SQL SELECT TOP with ORDER BY Clause

In this example, we will use the SQL SELECT TOP clause with ORDER BY clause to sort the data in the results set.

Query

SELECT TOP 4* FROM Employee ORDER BY Salary DESC;

Output:

sql select top with order by clause example Output

SQL SELECT TOP with ORDER BY Clause Example Output

Example 3: SQL SELECT TOP Clause with WHERE Clause Example

In this example, we will use the SELECT TOP clause with WHERE clause to filter data on specific conditions

Query: 

SELECT TOP 2* FROM Employee WHERE Salary>2000 ORDER BY Salary;

Output:

The above query will select all the employees according to the given condition (i.e. all Employees except the employee whose salary is less than 2000 will be selected) then the result will be sorted by Salary in ascending order (The ORDER BY keyword sorts the records in ascending order by default). Finally, the first 2 rows would be returned by the above query.

Example 4: SQL SELECT TOP PERCENT Clause Example

The PERCENT keyword is utilized to select the primary and percent of all-out rows. For example,

Query:

SELECT TOP 50 PERCENT* FROM Employee;

Output:

sql select top percent clause example output

SQL SELECT TOP PERCENT Clause Example Output

Here, the above query will select the first 50% of employee records out of the total number of records(i.e., the first 3 rows will be returned). 

Example 5: SQL TOP PERCENT with WHERE Clause Example

We can also include some situations using the TOP PERCENT with the WHERE clause in the above query.

Query:

SELECT TOP 50 PERCENT* FROM Employee WHERE Salary<50000;

Output:

sql top percent with where clause example output

SQL TOP PERCENT with WHERE Clause Example Output

The above query will select the Top 50% of the records out of the total number of records from the table according to the given condition such that it returns only the Top 50% of the records with the employee whose salary is less than 5000 (i.e, 2 rows will be returned)

SQL LIMIT  Clause

SQL LIMIT Clause limits the number of results returned in the results set. The LIMIT Clause is utilized with the accompanying database systems:

  • MySQL
  • PostgreSQL
  • SQLite

SQL LIMIT Clause Example

Since the LIMIT Clause is not supported in SQL Server we need to create a table in MySQL/PostgreSQL/SQLite. We will use the LIMIT clause in MySQL

CREATE TABLE Employee (    EmpId INTEGER PRIMARY KEY,     EmpName VARCHAR(225) NOT NULL,      Email VARCHAR(225) NOT NULL,       Address VARCHAR(225) NOT NULL,    Age INT NOT NULL,    Salary MONEY NOT NULL );  INSERT INTO Employee (EmpId, EmpName, Email, Address, Age, Salary) VALUES (1, 'Shubham', '[email protected]', 'India', 23, 50000.00),        (2, 'Aman', '[email protected]', 'Australia', 21, 45000.00),        (3, 'Naveen', '[email protected]', 'Sri Lanka', 24, 55000.00),        (4, 'Aditya', '[email protected]', 'Austria', 21, 42000.00),        (5, 'Nishant Saluja', '[email protected]', 'Spain', 22, 48000.00);      SELECT * FROM Employee ;

Output:

demo table created

Demo Table Created

Example 1: SELECT LIMIT Clause in SQL

In this example, we will use the SELECT LIMIT clause to display only 2 results.

Query:

SELECT * FROM Employee WHERE Salary = 45000 LIMIT 2;

Output:

limit clause in sql example ouptut

LIMIT Clause in SQL Example Ouptut

From the above query, the LIMIT operator limits the number of records to be returned. Here, it returns the first 2 rows from the table.

Example 2: SQL LIMIT with WHERE Clause

The accompanying query selects the initial 4 records from the Employee table with a given condition.

Query:

SELECT * FROM Employee WHERE Salary = 45000 LIMIT 2;

Output:

sql limit with where clause example output

SQL LIMIT with WHERE Clause Example Output

The above query will select all the employees according to the imposed condition (i.e. it selects the limited 2 records from the table where salary is 2000). Finally, the first 2 rows would be returned by the above query.

Example 3: SQL LIMIT With OFFSET Clause

The OFFSET keyword is utilized to indicate beginning rows from where to select rows. For instance,

Query:

SELECT * FROM Employee LIMIT 2 OFFSET 2;

Output:

sql limit with offset clause example output

SQL LIMIT With OFFSET Clause Example Output

Here, the above query selects 2 rows from the beginning of the third row (i.e., OFFSET 2 means, the initial 2 rows are excluded or avoided).

SQL FETCH FIRST Clause

SQL FETCH FIRST clause fetches the first given number of rows from the table. 

It is supported in database systems like:

  • IBM DB2
  • Oracle
  • PostgreSQL

Syntax:

The syntax to use the FETCH FIRST clause in SQL is:

SELECT columns FROM table WHERE condition FETCH FIRST n ROWS ONLY;

Here,

  • n: desired number of rows

Example 1: SQL FETCH FIRST Clause

We will use the same “Employee” table as used in previous examples.

FETCH FIRST clause in SQL Example

In this example, we will fetch the first 3 rows from the table.

Query:

SELECT * FROM Employee FETCH FIRST 3 ROWS ONLY;

Output:


Screenshot-2024-05-10-at-11-44-24-Online-SQL-Editor

FETCH FIRST Clause in SQL Example Output


Here, the above query will fetch the first 3 rows only from the table. We can also include some situations using the FETCH FIRST PERCENT and WHERE Clause in the above query.

Example 2: SQL FETCH FIRST PERCENT

In this example, we will fetch first 50% of the data from the table

Query:

SELECT * FROM Employee FETCH FIRST (SELECT CEIL(COUNT(*) / 2) FROM Employee) ROWS ONLY;

Output:

sql fetch first percent example output

SQL FETCH FIRST PERCENT Example Output


Here, the above query fetches the first 50% of the total number of rows (i.e., 2 rows) from the table.

Example 3: SQL FETCH FIRST with WHERE Clause

The “FETCH FIRST” syntax is not supported in MySQL. The correct syntax for limiting the number of rows in MySQL is by using the LIMIT clause.

Query:

SELECT * FROM Employee WHERE Salary = 45000 FETCH FIRST 1 ROW ONLY;

Output:

sql fetch first with where clause example output

SQL FETCH FIRST with WHERE CLAUSE Example Output

Here, the above query fetches the first 1 row from the table, with the condition that the salary is 45000 (i.e., it returns 1 row only).

Conclusion

SQL TOP, LIMIT and FETCH FIRST clause are used for a same purpose of limiting the data returned in results set. All three of these queries are not supported by all SQL DBMS. Each of them is supported by only some of the DBMS and depending on the DBMS you use, the query can differ.

We have explained all TOP, LIMIT and FETCH FIRST clause in SQL with examples, and also mentioned their supported DBMS to avoid confusion. Users should check if the clause is supported by their DBMS before using them.



Next Article
SQL SELECT FIRST

S

swathi23trl7
Improve
Article Tags :
  • Databases
  • SQL
  • SQL-Clauses

Similar Reads

  • SQL Tutorial
    SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases. In this
    11 min read
  • SQL Basics

    • What is Database?
      In today’s data-driven world, databases are indispensable for managing, storing, and retrieving information efficiently. From small-scale businesses to global enterprises, databases serve as the backbone of operations, powering applications, websites, and analytics systems. In this comprehensive art
      15 min read

    • Types of Databases
      Databases are essential for storing and managing data in today’s digital world. They serve as the backbone of various applications, from simple personal projects to complex enterprise systems. Understanding the different types of databases is crucial for choosing the right one based on specific requ
      11 min read

    • Introduction of DBMS (Database Management System)
      A Database Management System (DBMS) is a software solution designed to efficiently manage, organize, and retrieve data in a structured manner. It serves as a critical component in modern computing, enabling organizations to store, manipulate, and secure their data effectively. From small application
      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
      11 min read

    • SQL Data Types
      SQL Data Types are very important in relational databases. 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 data ana
      6 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
      6 min read

    • SQL Commands | DDL, DQL, DML, DCL and TCL Commands
      SQL commands are crucial 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 e
      7 min read

    Create Database in SQL

    • SQL CREATE DATABASE
      Creating a database is one of the fundamental tasks in SQL and is the first step in structuring your data for efficient management. Whether you're a developer or a database administrator, understanding the CREATE DATABASE statement is essential. Understanding how to use this command effectively is c
      6 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
      4 min read

    Tables in SQL

    • SQL CREATE TABLE
      In SQL, creating a table is one of the most essential tasks for structuring your database. The CREATE TABLE statement defines the structure of the database table, specifying column names, data types, and constraints such as PRIMARY KEY, NOT NULL, and CHECK. Mastering this statement is fundamental to
      5 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
      5 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
      5 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
      5 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 SQL INSERT INTO statement is one of the most commonly used commands for adding new data into a table in a database. Whether you're working with customer data, products, or user details, mastering this command is crucial for efficient database management. Let’s break down how this command works,
      6 min read

    • SQL UPDATE Statement
      In SQL, the UPDATE statement is used to modify existing records in a table. Whether you are updating a single record or multiple records at once, SQL provides the necessary functionality to make these changes. Whether you are working with a small dataset or handling large-scale databases, the UPDATE
      6 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
      6 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
      SQL queries can sometimes be complex, especially when you need to deal with multiple nested subqueries, aggregations, and joins. This is where the SQL WITH clause also known as Common Table Expressions (CTEs) comes in to make life easier. The WITH Clause is a powerful tool that simplifies complex SQ
      6 min read

    • SQL HAVING Clause with Examples
      The HAVING clause in SQL is used to filter query results based on aggregate functions. Unlike the WHERE clause, which filters individual rows before grouping, the HAVING clause filters groups of data after aggregation. It is commonly used with functions like SUM(), AVG(), COUNT(), MAX(), and MIN().
      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 SQL GROUP BY clause is a powerful tool used to organize data into groups based on shared values in one or more columns. It's most often used with aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform summary operations on each group helping us extract meaningful insights from large d
      5 min read

    • SQL LIMIT Clause
      The LIMIT clause in SQL is used to control the number of rows returned in a query result. It is particularly useful when working with large datasets, allowing us to retrieve only the required number of rows for analysis or display. Whether we're looking to paginate results, find top records, or just
      5 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 we need to find overlapping data between two or more queries. In this article, we will explain
      5 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. These functions are particularly useful when we need to summarize, analyze, or group large datasets in SQL databases. Whether you're working with sales data, employee records, or product inventories,
      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 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
      A 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 colu
      5 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 fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
      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 retrieves all records from the left table and only the matching records from the right table. When there is no matching record found, NULL values are returned for columns from the right table. This makes LEFT JOIN extremely useful for queries where you need to retain all records fr
      5 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 involving 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 where
      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

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences