EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PARTITION BY in SQL

By Roja MetlaRoja Metla

Home » Data Science » Data Science Tutorials » SQL Tutorial » PARTITION BY in SQL

PARTITION BY in SQL

Introduction to PARTITION BY in SQL

The following article provides an outline on PARTITION BY in SQL. The PARTITION BY is used to divide the result set into partitions. After that, perform computation on each data subset of partitioned data. We use ‘partition by’ clause to define the partition to the table. The ‘partition by ‘clause is used along with the sub clause ‘over’. We use window functions to operate the partition separately and recalculate the data subset. Window functions are defined as RANK (), LEAD (), MIN (), ROUND(), MAX () and COUNT () etc. The ‘partition by ‘clause is a scalar subquery. Which always return single value.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

window_function ( expression ) OVER (
PARTITION BY expression_1, expression_2...
order_clause
)

Here expression, we can use two or more columns to partition the data result set. The expression_1, expression_2 only refer to the columns by ‘FROM’ clause. We can’t refer to the alias in the select statement.

How to Implement PARTITION BY in SQL?

Let us take two tables as below and implementation

Below are “Package” and “Loan” table. Here once we apply the ‘PARTITION BY’ join we get the common rows between two tables.

Package Table

PARTITION BY in SQL 1

Below is the partition by condition applied as per the ‘amount’ partitioning by the ‘trip_no’.

Code:

SELECT
Package_no,
Trip_no,
Amount,
ROUND (AVG(Amount) OVER ( PARTITION BY Trip_no )) AS avg_trip_amount
FROM
Package;

Output:

PARTITION BY in SQL 2

Loan Table:

loan table

Below the partition by condition is applied as per the ‘loan_amount’ partitioning by the ‘loan_no’.

Code:

SELECT
loan_no,
loan_status,
state,
loan_amount,
ROUND (AVG(loan_amount) OVER ( PARTITION BY loan_status )) AS avg_loan_amount FROM
LOAN;

Popular Course in this category
JDBC Training (6 Courses, 7+ Projects)6 Online Courses | 7 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,027 ratings)
Course Price

View Course

Related Courses
PHP Training (5 Courses, 3 Project)Windows 10 Training (4 Courses, 4+ Projects)SQL Training Program (7 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)Oracle Training (14 Courses, 8+ Projects)

Output:

loan table

ROW_NUMBER with PARTITION BY Clause

We use ROW_NUMBER for the paging purpose in SQL. It is used to provide the consecutive numbers for the rows in the result set by the ‘ORDER’ clause. The sequence starts from 1.

Not necessarily, we need a ‘partition by’ clause while we use the row_number concept.

Syntax:

ROW_NUMBER() OVER( PARTITION BY exp1,exp2,.. ORDER BY col1,col2,..)

Example:

a. Without using the ‘Partition by’ clause.

Code:

SELECT *, ROW_NUMBER() OVER (ORDER BY state) AS Row_Number
FROM LOAN;

Output:

without using clause

b. By using the partition by clause.

Code:

SELECT *, ROW_NUMBER() OVER (PARTITION BY state ORDER BY state) AS Row_Number
FROM LOAN;

Output:

PARTITION BY in SQL 6

Examples of PARTITION BY in SQL

Given below are the examples of PARTITION BY in SQL:

Let’s us create the table.

Code:

create table customer_order_data(
customer_name varchar(20),
customer_city varchar(20),
customer_order_amount int,
customer_orderofcount int
);

Below commands to insert the data into the tables.

Code:

insert into customer_order_data values ('sam','agile',560,3),
('suppu','kakinada',890,12),
('Ram','kakinada',980,6),
('Raj','korea',780,11),
('Rose','korea',1780,21),
('Jack','korea',120,4),
('Goldy','Japan',320,5),
('Spongy','Japan',1320,15),
('Smarty','USA',520,10),
('Likka','USA',220,2)

Now lets select the table.

Code:

SELECT * FROM customer_order_data;

Output:

from customer order data

Now let’s get the partition by applied for the above table:

Example #1

Code:

SELECT Customer_city,
Customer_Name,
customer_order_amount,
COUNT(customer_orderofcount) OVER(PARTITION BY Customer_city) AS customer_CountOfOrders,
AVG(customer_order_amount) OVER(PARTITION BY Customer_city) AS Avgcustomer_OrderAmount from CUSTOMER_ORDER_DATA;

Output:

PARTITION BY in SQL 8JPG

Example #2

Code:

SELECT Customer_city,
Customer_Name,
customer_order_amount,
COUNT(customer_orderofcount) OVER(PARTITION BY Customer_city) AS customer_CountOfOrders,
AVG(customer_order_amount) OVER(PARTITION BY Customer_city) AS Avgcustomer_OrderAmount,
MIN(customer_order_amount) OVER(PARTITION BY Customer_city) AS Mincustomer_OrderAmount,
SUM(customer_order_amount) OVER(PARTITION BY Customer_city) AS Totalcustomer_OrderAmount
from
CUSTOMER_ORDER_DATA;

Output:

PARTITION BY in SQL 9JPG

Conclusion

Things that need to be considered in the topic ‘partition by’ in sql are the ‘partition by ‘clause is used along with the sub clause ‘over’. We use window functions to operate the partition separately and recalculate the data subset. Window functions are defined as RANK (), LEAD (), MIN (), ROUND(), MAX () and COUNT () etc The ‘partition by ‘clause is a scalar subquery. Which always return single value. We use ROW_NUMBER for the paging purpose in SQL. It is used to provide the consecutive numbers for the rows in the result set by the ‘ORDER’ clause. The sequence starts from 1. Not necessarily, we need a ‘partition by’ clause while we use the row_number concept.

Recommended Articles

This is a guide to PARTITION BY in SQL. Here we discuss the introduction to PARTITION BY in SQL along with examples to implement ROW_NUMBER with PARTITION BY Clause. You may also have a look at the following articles to learn more –

  1. What is SQL Developer?
  2. SQL RANK()
  3. ROLLUP in SQL
  4. SQL SELECT RANDOM

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
SQL Tutorial
  • Advanced
    • SQL Formatter
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL INSTR()
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • Alternate Key in SQL
    • SQL Super Key
  • Functions
    • SQL Date Function
    • SQL String Functions
    • SQL Compare String
    • SQL Window Functions
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • ANY in SQL
    • LIKE Query in SQL
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL MOD()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Server Permission
    • T-SQL INSERT
    • SQL Ranking Function
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - JDBC Training Course Learn More