HomeInterview QuestionsHow can I pivot a table in SQL to transform rows i…

How can I pivot a table in SQL to transform rows into columns?

🟢 Easy Coding Junior level
1Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

Pivoting in SQL turns row values into column headers. In SQL Server you can use the PIVOT operator; in other engines you can emulate it with conditional aggregation. Example using conditional aggregation:

SELECT student_id,

   SUM(CASE WHEN subject = 'Maths' THEN marks END) AS Maths,
   SUM(CASE WHEN subject = 'Science' THEN marks END) AS Science,
   SUM(CASE WHEN subject = 'English' THEN marks END) AS English

FROM student_marks

GROUP BY student_id;

This produces a wide table where each subject becomes a column. If you have a very large number like 1,000,000,000,000, you should store it in a numeric type that can hold large values, such as BIGINT or DECIMAL(20,0). Casting the literal to the appropriate type (e.g., 1000000000000::BIGINT) prevents overflow. The query runs in O(n) time, scanning each row once and performing a few arithmetic operations per row.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500