Duplicate a row in SQL?

Insert Into TableName (userID, courseID)
  Select userID, 11 From TableName Where courseID=6;

Also, I'm a bit confused by your comment that both are primary keys. Both rows can be part of the primary key or both can be Unique keys but they cannot both be a primary key. As far as errors go, it is probably because the query tried to insert rows that were duplicates of already existing rows. To eliminate this possibility you could do this:

Insert Into TableName (userID, courseID)
  Select userID, 11 From TableName Where courseID=6 
     AND (userID not in (Select userID From TableName Where courseID=11))

Depending on your database this could work too:

INSERT OR IGNORE INTO TableName (userID, courseID)
    SELECT userID, 11 FROM TableName WHERE courseID=6;

Anyway, there you go.


insert into TableName (userId, courseId)
    select userId, 11
    from   TableName
    where  courseId = 6
    and    not exists (
               select 1
               from   TableName nested
               where  nested.userId = TableName.UserId
               and    nested.courseId = 11
           )

Selects all users that are assigned to courseId 6 but are not yet assigned to courseId 11 and inserts a new record into the table for them for courseId 11.

Tags:

Sql