SQL Query Generator for X-bar and R Control Limits
If your measurements are already in a database, you can compute X-bar and R limits without exporting to a spreadsheet. This generator builds a query that forms subgroups, calculates averages and ranges, applies the control chart constants and flags every subgroup outside its limits.
Fill in
Your own table name; this tool uses generic names
Column that identifies each subgroup, for example lot or hour
n=2: 1.880, 3: 1.023, 4: 0.729, 5: 0.577, 6: 0.483
0 for n up to 6, 0.076 for n = 7
n=2: 3.267, 3: 2.574, 4: 2.282, 5: 2.114, 6: 2.004
X-bar and R limits query
WITH subgroup_stats AS (
SELECT
subgroup_id AS subgroup_id,
COUNT(*) AS n,
AVG(measured_value) AS xbar,
MAX(measured_value) - MIN(measured_value) AS r
FROM inspection_results
WHERE characteristic_code = 'BORE_DIA' AND inspected_on >= '2026-09-01'
GROUP BY subgroup_id
HAVING COUNT(*) = 5
),
center_lines AS (
SELECT
AVG(xbar) AS xbarbar,
AVG(r) AS rbar,
COUNT(*) AS subgroup_count
FROM subgroup_stats
)
SELECT
s.subgroup_id,
s.xbar,
s.r,
c.xbarbar + 0.577 * c.rbar AS ucl_xbar,
c.xbarbar AS cl_xbar,
c.xbarbar - 0.577 * c.rbar AS lcl_xbar,
2.114 * c.rbar AS ucl_r,
c.rbar AS cl_r,
0 * c.rbar AS lcl_r,
CASE
WHEN s.xbar > c.xbarbar + 0.577 * c.rbar THEN 'XBAR ABOVE UCL'
WHEN s.xbar < c.xbarbar - 0.577 * c.rbar THEN 'XBAR BELOW LCL'
WHEN s.r > 2.114 * c.rbar THEN 'RANGE ABOVE UCL'
ELSE 'IN CONTROL'
END AS status
FROM subgroup_stats s
CROSS JOIN center_lines c
ORDER BY s.subgroup_id;Optional: sigma within for capability
-- Add to center_lines when you also need Cpk: sigma within = rbar / d2 -- d2 for n: 2 = 1.128, 3 = 1.693, 4 = 2.059, 5 = 2.326, 6 = 2.534 -- Cpk = LEAST(usl - xbarbar, xbarbar - lsl) / (3 * rbar / d2)
Table and column names are generic placeholders: replace them with your own schema. The query uses standard SQL with a CTE and works on SQL Server, PostgreSQL, Oracle and MySQL 8 or later; use LEAST or MIN-style functions per your dialect. Subgroup ids must sort in time order. Rows not in complete subgroups of size n are excluded by the HAVING clause.
Build SPC views from ERP quality data
Optional: a conversation about a governed, read-only SPC data layer over your inspection tables.
Optional. The tool and every export work without this. No spam.
How to use it
Enter the name of your measurement table, the value column and a column that identifies each subgroup, such as a lot number, an inspection batch or an hour bucket. Add a filter for the characteristic and the date range, set the subgroup size and type the matching constants A2, D3 and D4 from the help text. Copy the query into your SQL tool and run it. The output is one row per subgroup with limits and a status flag.
- Use a stable subgroup id so rows group correctly
- Filter to one characteristic and one machine or line
- Complete subgroups only: partial ones are dropped by HAVING
How the query works
The first CTE groups rows by subgroup and computes the mean and the range, which is maximum minus minimum. The second CTE averages those across all subgroups to get the grand mean and Rbar. The final select applies the standard X-bar and R formulas: grand mean plus or minus A2 times Rbar for the X-bar chart, D4 times Rbar for the upper range limit and D3 times Rbar for the lower. A CASE expression labels the status for easy filtering.
Worked example
Suppose 25 subgroups of five bore diameters give a grand mean of 25.004 and an Rbar of 0.027. With A2 = 0.577 the X-bar limits are 25.004 plus or minus 0.0156, so 24.988 to 25.020. The upper range limit is 2.114 times 0.027, about 0.057. A subgroup with a mean of 25.024 would be flagged XBAR ABOVE UCL, prompting a check of what changed on that run.
Common mistakes
The most common issue is computing limits from data that include a known upset, which inflates the range and widens the limits. Remove subgroups only with a documented assignable cause. Another is leaving the filter open so that several machines mix in one subgroup. Finally, remember that limits from the same data that you chart are trial limits; lock them after the process is shown to be stable.
- Do not mix machines, shifts or fixtures in one subgroup
- Treat first-run limits as trial limits
- Verify the constants match your subgroup size
Frequently Asked Questions
Which tables hold inspection results in my ERP?
It varies by product and version, so this tool uses generic names. Ask your ERP administrator for the quality results table and its columns, and confirm the column holding the numeric measured value and the lot or sample id.
Can I use this for individuals data?
No. This query forms subgroups of a fixed size. For individuals data, use a window function such as LAG to compute moving ranges, then apply the 2.66 and 3.267 multipliers from the chart selection guide.
Why are some of my subgroups missing?
The HAVING clause keeps only subgroups with exactly n readings. Incomplete groups are excluded so that the constants stay valid. Remove the clause only if you switch to a method that handles varying subgroup sizes.
Will this query modify my data?
No. It is a read-only SELECT. Even so, test it on a non-production copy or with a row limit first, and have your database administrator review any query before it runs on a live system.
If your inspection results sit in an ERP quality module, Netray can help build a read-only SPC layer on top of it with the query shown and approved by your team.
Related Tools
Control Chart Type Selection Guide
Pick the correct SPC chart from your data type and subgroup size, with center line and limit formulas for each chart.
Quality & InspectionWestern Electric and Nelson Rules Reference
Look up every Western Electric and Nelson run rule with its zone, point count and the process cause it usually signals.
Developer ToolsPython SPC X-bar R and Capability Script Generator
Fill in your CSV column, subgroup size and spec limits to get a ready Python script for X-bar and R limits, Cp, Cpk, Pp and Ppk.
Quality & InspectionExcel Process Capability Formulas Generator
Type your data range and cell addresses and get Excel formulas for Cp, Cpk, Pp, Ppk, expected PPM and sigma level.
More Developer Tools tools
See all- SAP Sales Order ABAP SELECT Generator (VBAK, VBAP, VBFA)
- SAP Sales Order Create BAPI ABAP Generator (BAPI_SALESORDER_CREATEFROMDAT2)
- SAP ABAP Open Items SELECT Generator
- SAP ACDOCA SQL Query Generator
- SAP QM Inspection Lot ABAP SELECT Generator
- SAP Quality Notification Pareto SQL Query Generator
- SAP QM Usage Decision BAPI Skeleton
- ABAP Custom Exception Class Generator
- ABAP Unit Test Class Generator