Sql Combine Two Rows Into One

8 min read

Combining two rows into a single row is a common data transformation requirement in SQL, often encountered during reporting, data migration, or when preparing datasets for analytics. Whether you are merging duplicate records, pivoting key-value pairs into columns, or concatenating text values from multiple rows, the approach depends heavily on your specific database engine and the structure of your data. Mastering these techniques allows you to reshape raw transactional data into meaningful summaries without relying on external scripting languages.

Understanding the Core Scenarios

Before writing a query, you must identify why the rows need combining. The solution differs significantly based on the scenario:

  1. String Aggregation (Concatenation): You have multiple rows for a single entity (e.g., multiple tags for one blog post) and want a single comma-separated list in one column.
  2. Pivoting (Row-to-Column): You have an Entity-Attribute-Value (EAV) structure where attributes are stored in rows, and you want each attribute to become a distinct column.
  3. Deduplication/Merging: You have two distinct rows representing the same logical entity (perhaps from different sources) and need to merge their non-null values into one surviving row.
  4. Analytical Grouping: You need to compare values from the "current" row and the "previous/next" row (e.g., calculating session gaps or running totals).

Method 1: String Aggregation (Combining Text Values)

This is the most frequent interpretation of "combining rows." Modern SQL standards and vendor-specific extensions make this straightforward Simple as that..

PostgreSQL, Oracle, and SQL Server (2017+): STRING_AGG / LISTAGG

These functions are purpose-built for concatenation. They accept the column to aggregate and a delimiter It's one of those things that adds up..

SELECT 
    user_id,
    STRING_AGG(tag_name, ', ') AS all_tags
FROM user_tags
GROUP BY user_id;

In Oracle, the syntax is LISTAGG(tag_name, ', ') WITHIN GROUP (ORDER BY tag_name). In SQL Server (pre-2017), developers historically used the STUFF function with FOR XML PATH, though STRING_AGG is now the standard.

MySQL and MariaDB: GROUP_CONCAT

MySQL has long supported GROUP_CONCAT, which offers extensive control over ordering and distinct values.

SELECT 
    product_id,
    GROUP_CONCAT(DISTINCT category_name ORDER BY category_name SEPARATOR ' | ') AS categories
FROM product_categories
GROUP BY product_id;

Pro Tip: Be aware of the group_concat_max_len system variable in MySQL. The default limit (often 1024 bytes) truncates long results. You may need to set SET SESSION group_concat_max_len = 1000000; before running the query.

SQLite: GROUP_CONCAT

SQLite uses GROUP_CONCAT as well, but lacks the DISTINCT keyword inside the function in older versions. A common workaround involves a subquery:

SELECT 
    student_id,
    GROUP_CONCAT(course_name, '; ') AS courses
FROM (
    SELECT DISTINCT student_id, course_name FROM enrollments
)
GROUP BY student_id;

Method 2: Pivoting Rows into Columns (Crosstab)

When your data is stored in a "long" format (Key-Value pairs) but your report requires a "wide" format, you are pivoting Worth keeping that in mind..

Standard SQL: Conditional Aggregation (The Portable Way)

This works on every major database (PostgreSQL, MySQL, SQL Server, Oracle, SQLite). Here's the thing — it uses CASE statements inside aggregate functions like MAX or MIN. Since you are grouping by the primary key, MAX effectively picks the single non-null value for that attribute.

This changes depending on context. Keep that in mind Worth keeping that in mind..

SELECT 
    entity_id,
    MAX(CASE WHEN attribute_key = 'color' THEN attribute_value END) AS color,
    MAX(CASE WHEN attribute_key = 'size' THEN attribute_value END) AS size,
    MAX(CASE WHEN attribute_key = 'weight' THEN attribute_value END) AS weight
FROM entity_attributes
GROUP BY entity_id;

This method is highly performant because it requires only a single table scan.

Vendor-Specific PIVOT Operators

SQL Server and Oracle offer dedicated PIVOT syntax, which can be more readable for static columns.

-- SQL Server Syntax
SELECT * 
FROM entity_attributes
PIVOT (
    MAX(attribute_value) 
    FOR attribute_key IN ([color], [size], [weight])
) AS pvt;

PostgreSQL provides the crosstab function via the tablefunc extension, which is powerful for dynamic categories but requires defining the output column structure explicitly in the query call.

Method 3: Merging Two Specific Rows (Deduplication)

Sometimes "combine two rows" means you have exactly two rows (e.Consider this: g. , id=1 and id=2) representing the same customer, and you want one row containing the best data from both Most people skip this — try not to..

The COALESCE / FULL OUTER JOIN Pattern

Assume table_a and table_b share a primary key id. You want to keep table_a values where present, falling back to table_b Easy to understand, harder to ignore..

SELECT 
    COALESCE(a.id, b.id) AS id,
    COALESCE(a.email, b.email) AS email,
    COALESCE(a.phone, b.phone) AS phone,
    COALESCE(a.address, b.address) AS address
FROM table_a a
FULL OUTER JOIN table_b b ON a.id = b.id;

The UNION ALL + Aggregation Pattern

If the rows are in the same table (e.On top of that, g. , source='A' and source='B'), filter them first, then aggregate Worth keeping that in mind. Turns out it matters..

SELECT 
    id,
    MAX(CASE WHEN source = 'A' THEN email END) AS email_a,
    MAX(CASE WHEN source = 'B' THEN email END) AS email_b,
    -- Pick the non-null email, preferring Source A
    COALESCE(MAX(CASE WHEN source = 'A' THEN email END), MAX(CASE WHEN source = 'B' THEN email END)) AS final_email
FROM customer_data
WHERE source IN ('A', 'B')
GROUP BY id;

This approach is flexible because it lets you define complex precedence logic (e.And g. , "Prefer Source A email, but Source B phone") clearly within the SELECT clause And it works..

Method 4: Combining Adjacent Rows with Window Functions

Advanced analytics often require combining a row with its neighbor—calculating the time difference between consecutive logins, or creating a "From/To" date range from a list of start dates.

Using LEAD and LAG

Window functions (LEAD, LAG, FIRST_VALUE, LAST_VALUE) access data from subsequent or preceding rows in the result set without a self-join.

Scenario: Convert a list of price_change_dates into price_periods (start_date, end_date).

SELECT 
    product_id,
    change_date AS period_start,
    LEAD(change_date, 1, '9999-12-31') OVER (PARTITION BY product_id ORDER BY change_date) AS period_end,
    new_price
FROM price_history;

Here, LEAD pulls the change_date from the next row (partitioned by product) to serve as the end_date for the current row. The third argument (`'9999-

The third argument ('9999-12-31') provides a default "open-ended" date for the most recent price change, effectively representing "current until further notice."

Using FIRST_VALUE and LAST_VALUE for Sessionization

A common requirement is collapsing a session of events into a single row containing the session start time, end time, and aggregated metrics (e.g., page views, cart additions) That's the whole idea..

SELECT DISTINCT
    user_id,
    session_id,
    FIRST_VALUE(event_timestamp) OVER (PARTITION BY user_id, session_id ORDER BY event_timestamp) AS session_start,
    LAST_VALUE(event_timestamp) OVER (
        PARTITION BY user_id, session_id 
        ORDER BY event_timestamp 
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    ) AS session_end,
    COUNT(*) OVER (PARTITION BY user_id, session_id) AS event_count
FROM user_events
WHERE event_date = CURRENT_DATE;

Critical Note on LAST_VALUE: The default window frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. You must explicitly define ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING (or RANGE equivalent) to make LAST_VALUE look at the actual last row of the partition rather than the current row.

Method 5: String Aggregation (Combining Rows into a Delimited List)

When the goal is not new columns but a single concatenated string (e.Think about it: g. , "Tags: SQL, Python, Postgres"), use vendor-specific aggregation functions.

Database Function Example
PostgreSQL STRING_AGG(expr, delimiter) STRING_AGG(tag_name, ', ' ORDER BY tag_name)
SQL Server (2017+) STRING_AGG(expr, delimiter) STRING_AGG(tag_name, ', ') WITHIN GROUP (ORDER BY tag_name)
MySQL / MariaDB GROUP_CONCAT(expr SEPARATOR delim) GROUP_CONCAT(tag_name ORDER BY tag_name SEPARATOR ', ')
Oracle (19c+) LISTAGG(expr, delimiter) LISTAGG(tag_name, ', ') WITHIN GROUP (ORDER BY tag_name)
SQLite GROUP_CONCAT(expr, delim) GROUP_CONCAT(tag_name, ', ')
-- PostgreSQL / SQL Server Syntax
SELECT 
    article_id,
    STRING_AGG(tag_name, ', ' ORDER BY tag_name) AS tags_csv
FROM article_tags
GROUP BY article_id;

Performance Considerations & Best Practices

  1. Index the Partition/Group By Columns: Methods relying on GROUP BY, PARTITION BY, or JOIN keys (id, user_id, session_id) require indexes on those columns to avoid costly Sort or Hash Match operations.
  2. Filter Early: Apply WHERE clauses before aggregation or windowing. Reducing the row count early drastically reduces memory pressure for sorts/hashes.
  3. Avoid SELECT * in Pivots: Explicitly list output columns. SELECT * FROM PIVOT (or crosstab without column definitions) is often invalid syntax or returns unpredictable metadata.
  4. Watch for Data Expansion: CROSS JOIN (Method 1) and PIVOT (Method 2) increase column count. Ensure the resulting row width doesn't exceed your database's maximum row size limit (e.g., ~8KB in SQL Server, 65KB in MySQL/PostgreSQL default configs).
  5. Null Semantics: Be explicit. SUM ignores nulls; COUNT(column) ignores nulls; COUNT(*) counts rows. STRING_AGG usually ignores nulls, but CONCAT/|| often propagates them. Use COALESCE defensively.

Conclusion

"Combining two rows" is rarely a single problem—it is a family of problems ranging from set operations (UNION), relational reshaping (PIVOT/JOIN), entity resolution (COALESCE/FULL JOIN), temporal analytics (LEAD/LAG), to string serialization (STRING_AGG).

The optimal technique depends entirely on the cardinality of your relationship (one-to-one vs. one-to-many), the direction of the transformation (vertical-to-horizontal vs. Practically speaking, horizontal-to-vertical), and whether you are resolving conflicts or preserving history. By matching your specific data shape to the patterns above—Vertical Concatenation for history, Pivoting for attributes, Coalescing for deduplication, Windowing for sequences, and Aggregation for lists—you ensure the query is not only correct but performant and maintainable.

Freshly Posted

Out This Week

Cut from the Same Cloth

If You Liked This

Thank you for reading about Sql Combine Two Rows Into One. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home