tags:

views:

52

answers:

4

I'm asking for MySQL specifically, but the answer might work for a lot of SQL databases.

If I have a select statement like this:

select * from users where age > 5;

How do I assign that to a new table?

+5  A: 
insert into old_farts
select * from users where age > 5;

Here's the reference page.

Ken
It's worth noting that you have to create the destination table first.
Neil
`CREATE TABLE AS ... SELECT` is the right answer, as mentioned by Bob.
Evan Carroll
+3  A: 

You need to use the INSERT...SELECT syntax -

INSERT INTO NewTable SELECT * FROM Users WHERE AGE > 5

(Edited to add: In SQL that would be SELECT * INTO NewTable FROM Users WHERE AGE > 5)

froadie
+5  A: 

At least in Oracle you can do something like

CREATE TABLE SOME_KIDS AS
  SELECT * FROM USERS WHERE AGE > 5;
Bob Jarvis
MySQL can do this too. http://dev.mysql.com/doc/refman/5.5/en/create-table.html
Evan Carroll
+1  A: 

It sounds like what you actually want is a view.

CREATE OR REPLACE VIEW users_over_five AS (SELECT * FROM users WHERE age > 5);

Unless you want a non-normalized database, or are just moving data around for maintenance, a view is the way to go.

Dolph