Copy Table — SQL Technical Interview Questions & Answers
Copy Table
Copy Table
- CREATE TABLE students2 LIKE students; copies structure (columns, indexes) without rows. CREATE TABLE students2 AS SELECT * FROM students; copies data but may skip some indexes/PK details — check SHOW CREATE TABLE after.
- INSERT INTO students2 SELECT * FROM students; fills a table that already exists.
- Trap: AS SELECT then wondering why AUTO_INCREMENT / FKs vanished. LIKE then INSERT is cleaner for a clone.
- On the example next to this theory: Copy Table: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.
Technical Interview Tip: LIKE = structure. AS SELECT = data. Combine for a clone.
Code Examples for Copy Table
Copy Table — sample query
-- Copy Table
CREATE TABLE demo (
id INTEGER PRIMARY KEY,
label TEXT NOT NULL,
qty INTEGER DEFAULT 0
);
INSERT INTO demo (id, label, qty) VALUES
(1, 'alpha', 2),
(2, 'beta', 5);
SELECT label, qty FROM demo WHERE qty >= 2 ORDER BY qty DESC;Copy Table: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.
How to Explain Copy Table to an Interviewer
Copy structure only?
CREATE TABLE t2 LIKE t1;