Share to: share facebook share twitter share wa share telegram print page

Insert (SQL)

An SQL INSERT statement adds one or more records to any single table in a relational database.

Basic form

Insert statements have the following form:

INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])

The number of columns and values must be the same. If a column is not specified, the default value for the column is used. The values specified (or implied) by the INSERT statement must satisfy all the applicable constraints (such as primary keys, CHECK constraints, and NOT NULL constraints). If a syntax error occurs or if any constraints are violated, the new row is not added to the table and an error returned instead.

Example:

INSERT INTO phone_book (name, number) VALUES ('John Doe', '555-1212');

Shorthand may also be used, taking advantage of the order of the columns when the table was created. It is not required to specify all columns in the table since any other columns will take their default value or remain null:

INSERT INTO table VALUES (value1, [value2, ... ])

Example for inserting data into 2 columns in the phone_book table and ignoring any other columns which may be after the first 2 in the table.

INSERT INTO phone_book VALUES ('John Doe', '555-1212');

Advanced forms

Multirow inserts

A SQL feature (since SQL-92) is the use of row value constructors to insert multiple rows at a time in a single SQL statement:

INSERT INTO tablename (column-a, [column-b, ...])
VALUES ('value-1a', ['value-1b', ...]),
       ('value-2a', ['value-2b', ...]),
       ...

This feature is supported by IBM Db2, SQL Server (since version 10.0 - i.e. 2008), PostgreSQL (since version 8.2), MySQL, SQLite (since version 3.7.11) and H2.

Example (assuming that 'name' and 'number' are the only columns in the 'phone_book' table):

INSERT INTO phone_book VALUES ('John Doe', '555-1212'), ('Peter Doe', '555-2323');

which may be seen as a shorthand for the two statements

INSERT INTO phone_book VALUES ('John Doe', '555-1212');
INSERT INTO phone_book VALUES ('Peter Doe', '555-2323');

Note that the two separate statements may have different semantics (especially with respect to statement triggers) and may not provide the same performance as a single multi-row insert.

To insert multiple rows in MS SQL you can use such a construction:

INSERT INTO phone_book
SELECT 'John Doe', '555-1212'
UNION ALL
SELECT 'Peter Doe', '555-2323';

Note that this is not a valid SQL statement according to the SQL standard (SQL:2003) due to the incomplete subselect clause.

To do the same in Oracle use the DUAL table, which always consists of a single row only:

INSERT INTO phone_book
SELECT 'John Doe', '555-1212' FROM DUAL
UNION ALL
SELECT 'Peter Doe','555-2323' FROM DUAL

A standard-conforming implementation of this logic shows the following example, or as shown above:

INSERT INTO phone_book
SELECT 'John Doe', '555-1212' FROM LATERAL ( VALUES (1) ) AS t(c)
UNION ALL
SELECT 'Peter Doe','555-2323' FROM LATERAL ( VALUES (1) ) AS t(c)

Oracle PL/SQL supports the INSERT ALL statement, where multiple insert statements are terminated by a SELECT:[1]

INSERT ALL
INTO phone_book VALUES ('John Doe', '555-1212')
INTO phone_book VALUES ('Peter Doe', '555-2323')
SELECT * FROM DUAL;

In Firebird inserting multiple rows can be achieved like this:

INSERT INTO phone_book (name, number)
SELECT 'John Doe', '555-1212' FROM RDB$DATABASE
UNION ALL
SELECT 'Peter Doe', '555-2323' FROM RDB$DATABASE;

Firebird, however, restricts the number of rows than can be inserted in this way, since there is a limit to the number of contexts that can be used in a single query.

Copying rows from other tables

An INSERT statement can also be used to retrieve data from other tables, modify it if necessary and insert it directly into the table. All this is done in a single SQL statement that does not involve any intermediary processing in the client application. A subselect is used instead of the VALUES clause. The subselect can contain joins, function calls, and it can even query the same table into which the data is inserted. Logically, the select is evaluated before the actual insert operation is started. An example is given below.

INSERT INTO phone_book2
SELECT *
FROM   phone_book
WHERE  name IN ('John Doe', 'Peter Doe')

A variation is needed when some of the data from the source table is being inserted into the new table, but not the whole record. (Or when the tables' schemas are not the same.)

INSERT INTO phone_book2 (name, number)
SELECT name, number
FROM   phone_book
WHERE  name IN ('John Doe', 'Peter Doe')

The SELECT statement produces a (temporary) table, and the schema of that temporary table must match with the schema of the table where the data is inserted into.

Default Values

It is possible to insert a new row without specifying any data, using default values for all columns. However, some databases reject the statement if no data is given, such as Microsoft SQL Server, and in this case the DEFAULT keyword can be used.

INSERT INTO phone_book
VALUES ( DEFAULT )

Sometimes databases also support alternative syntax for this; for example, MySQL allows omitting the DEFAULT keyword, and T-SQL can use DEFAULT VALUES instead of VALUES(DEFAULT). The DEFAULT keyword can also be used in normal insertion to explicitly fill a column using that column's default value:

INSERT INTO phone_book VALUES ( DEFAULT, '555-1212' )

What happens when a column does not specify a default value is database dependent. For example, MySQL and SQLite will fill in with a blank value (except when in strict mode), while many other databases will reject the statement.

Retrieving the key

Database designers that use a surrogate key as the primary key for every table will run into the occasional scenario where they need to automatically retrieve the database-generated primary key from an SQL INSERT statement for use in other SQL statements. Most systems do not allow SQL INSERT statements to return row data. Therefore, it becomes necessary to implement a workaround in such scenarios. Common implementations include:

  • Using a database-specific stored procedure that generates the surrogate key, performs the INSERT operation, and finally returns the generated key. For example, in Microsoft SQL Server, the key is retrieved via the SCOPE_IDENTITY() special function, while in SQLite the function is named last_insert_rowid().
  • Using a database-specific SELECT statement on a temporary table containing last inserted row(s). Db2 implements this feature in the following way:
    SELECT *
    FROM NEW TABLE (
        INSERT INTO phone_book
        VALUES ( 'Peter Doe','555-2323' )
    ) AS t
    
    • Db2 for z/OS implements this feature in the following way.
      SELECT EMPNO, HIRETYPE, HIREDATE
      FROM FINAL TABLE (
          INSERT INTO EMPSAMP (NAME, SALARY, DEPTNO, LEVEL)
          VALUES('Mary Smith', 35000.00, 11, 'Associate')
      );
      
  • Using a SELECT statement after the INSERT statement with a database-specific function that returns the generated primary key for the most recently inserted row. For example, LAST_INSERT_ID() for MySQL.
  • Using a unique combination of elements from the original SQL INSERT in a subsequent SELECT statement.
  • Using a GUID in the SQL INSERT statement and retrieving it in a SELECT statement.
  • Using the OUTPUT clause in the SQL INSERT statement for MS-SQL Server 2005 and MS-SQL Server 2008.
  • Using an INSERT statement with RETURNING clause for Oracle.
    INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' )
    RETURNING phone_book_id INTO v_pb_id
    
  • Using an INSERT statement with RETURNING clause for PostgreSQL (since 8.2). The returned list is identical to the result of a INSERT.
    • Firebird has the same syntax in Data Modification Language statements (DSQL); the statement may add at most one row.[2] In stored procedures, triggers and execution blocks (PSQL) the aforementioned Oracle syntax is used.[3]
      INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' )
      RETURNING phone_book_id
      
  • Using the IDENTITY() function in H2 returns the last identity inserted.
    SELECT IDENTITY();
    

Triggers

If triggers are defined on the table on which the INSERT statement operates, those triggers are evaluated in the context of the operation. BEFORE INSERT triggers allow the modification of the values that shall be inserted into the table. AFTER INSERT triggers cannot modify the data anymore, but can be used to initiate actions on other tables, for example, to implement auditing mechanism.

References

  1. ^ "Oracle PL/SQL: INSERT ALL". psoug.org. Archived from the original on 2010-09-16. Retrieved 2010-09-02.
  2. ^ "Firebird 2.5 Language Reference Update". Retrieved 2011-10-24.
  3. ^ "Firebird SQL Language Dictionary".

Read other articles:

Will SmithLahirWillard Carroll Smith, Jr.25 September 1968 (umur 55)Philadelphia, PennsylvaniaTempat tinggalLos AngelesNama lainThe Fresh PrinceSuami/istriSheree Zampino(m. 1992–1995; bercerai)Jada Koren Pinkett(m. 1997–sekarang)AnakWillard Carroll Smith IIIJaden Christopher Syre SmithWillow Camille Reign SmithOrang tuaWillard Carroll Smith, Sr.Caroline BrightKarier musikGenreHip hopPekerjaanAktor, produser, penyanyi rapTahun aktif1985–sekarangLabel Jive/RCA Records Columbia/SME …

Peta infrastruktur dan tata guna lahan di Komune Jouac.  = Kawasan perkotaan  = Lahan subur  = Padang rumput  = Lahan pertanaman campuran  = Hutan  = Vegetasi perdu  = Lahan basah  = Anak sungaiJouac merupakan sebuah komune di departemen Haute-Vienne di Prancis. Lihat pula Komune di departemen Haute-Vienne Referensi INSEE lbsKomune di departemen Haute-Vienne Aixe-sur-Vienne Ambazac Arnac-la-Poste Augne Aureil Azat-le-Ris Balledent La Bazeuge Beaumont-du-La…

Cinta Fitri Season 3Genre Drama Roman Keluarga PembuatMD EntertainmentDitulis olehHilman HariwijayaSkenarioHilman HariwijayaSutradaraEncep MasdukiPemeran Shireen Sungkar Teuku Wisnu Adly Fairuz Dinda Kanya Dewi Shandy Syarif Donita Verlita Evelyn Iqbal Pakula Boy Tirayoh Irene Librawati Penggubah lagu temaRossaLagu pembukaAtas Nama Cinta oleh RossaLagu penutupAtas Nama Cinta oleh RossaPenata musikIwang ModulusNegara asalIndonesiaBahasa asliBahasa IndonesiaJmlh. musim7Jmlh. episode150 (daft…

Malam Tahun BaruPerayaan malam tahun baru di SydneyNama lain Hogmanay (Skotlandia) Calennig (Wales) Silvester (Austria, Bosnia dan Herzegovina, Kroasia, Republik Ceko, Prancis, Jerman, Hungaria, Israel, Italia, Liechtenstein, Luxembourg, Polandia, Slowakia, Slovenia, Swiss) Réveillon (Belgia, Brasil, Prancis, Portugal, Rumania, dan lokasi pembicaraan Prancis dalam Amerika Utara) Novyy God (Belarusia, Rusia, Ukraina) JenisInternasionalMaknaHari terakhir dari tahun GregorianPerayaanRefleksi; berp…

German football player and manager Falko Götz Götz coaching Holstein Kiel in 2009Personal informationDate of birth (1962-03-26) 26 March 1962 (age 62)Place of birth Rodewisch, East GermanyHeight 1.81 m (5 ft 11 in)Position(s) Attacking midfielder, forward[1]Youth career1969–1971 FC Vorwärts Berlin1971–1979 Berliner FC DynamoSenior career*Years Team Apps (Gls)1979–1983 Berliner FC Dynamo 40 (12)1984–1988 Bayer Leverkusen 115 (26)1988–1992 1. FC Köln 127 (…

Milenio Televisión affiliate in Tecate This article needs to be updated. Please help update this article to reflect recent events or newly available information. (December 2022) XHDTV-TDTTecate–Tijuana, Baja California/San Diego, CaliforniaMexico/United StatesCityTecate, Baja CaliforniaChannelsDigital: 21 (UHF)Virtual: 49[1]BrandingMilenio TelevisiónProgrammingAffiliations49.1: Milenio TelevisiónOwnershipOwnerTelevisora Alco, S. de R.L. de C.V.OperatorEntravision Communications(40% …

Hartenstein. Hartenstein adalah kota yang terletak di distrik Nürnberger Land di Bayern, Jerman. Kota Hartenstein memiliki luas sebesar 22.80 km². Hartenstein pada tahun 2006, memiliki penduduk sebanyak 1.395 jiwa. lbsKota dan kotamadya di Nürnberger Land Alfeld Altdorf bei Nürnberg Burgthann Engelthal Feucht Happurg Hartenstein Henfenfeld Hersbruck Kirchensittenbach Lauf an der Pegnitz Leinburg Neuhaus an der Pegnitz Neunkirchen am Sand Offenhausen Ottensoos Pommelsbrunn Reichenschwand…

Cet article est une ébauche concernant une localité italienne et le Trentin-Haut-Adige. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Bedollo Armoiries Drapeau Noms Nom allemand Beduln Administration Pays Italie Région Trentin-Haut-Adige  Province Trentin   Code postal 38043 Code ISTAT 022011 Code cadastral A730 Préfixe tel. 0461 Démographie Gentilé bedoleri Population 1 480 hab. (1er jan…

Questa voce sull'argomento nobili italiani è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. A questa voce o sezione va aggiunto il template sinottico {{Militare}} Puoi aggiungere e riempire il template secondo le istruzioni e poi rimuovere questo avviso. Se non sei in grado di riempirlo in buona parte, non fare nulla; non inserire template vuoti. Girolamo Appiani d'Aragona (Piombino, 1485 – Piacenza, 7 febbraio 1559) è stato un nobil…

Chuck McCann (2013) Charles John Thomas Chuck McCann (2 September 1934 – 8 April 2018)[1] adalah seorang tokoh kebugaran Amerika, aktor, dan komedian. Catatan ^ Chuck McCann. IMDb. Diakses tanggal March 7, 2008.  Pranala luar Chuck McCann di IMDb (dalam bahasa Inggris) (Inggris) http://www.chuckmccann.net Diarsipkan 2018-04-10 di Wayback Machine. Wikimedia Commons memiliki media mengenai Chuck McCann.

Prime Minister of Australia from 2015 to 2018 The HonourableMalcolm TurnbullACOfficial portrait, 201529th Prime Minister of AustraliaIn office15 September 2015 – 24 August 2018MonarchElizabeth IIGovernor GeneralSir Peter CosgroveDeputyWarren TrussBarnaby JoyceMichael McCormackPreceded byTony AbbottSucceeded byScott MorrisonLeader of the Liberal PartyIn office14 September 2015 – 24 August 2018DeputyJulie BishopPreceded byTony AbbottSucceeded byScott MorrisonIn office16 Septe…

Artikel ini bukan mengenai Chinese Television System atau China Central Television. China Television Company, Ltd.中國電視公司JenisJaringan televisi, Televisi satelit dan Televisi kabelIndustriPenyiaran televisiDidirikan3 September 1968KantorpusatTaipei, Republik Tiongkok (Taiwan)ProdukKonten televisi, program televisiIndukWant Want China Times GroupSitus webwww.ctv.com.tw Gedung CTV di Kota Taipei. China Television Company, Ltd. (CTV, Hanzi tradisional: 中國電視公司; Hanzi seder…

1927 film by Abel Gance This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Napoléon 1927 film – news · newspapers · books · scholar · JSTOR (March 2020) (Learn how and when to remove this message) NapoléonPoster from the 1981 Radio City Music Hall screeningsDirected byAbel GanceWritten byAbel GanceProduced …

Unmotorised transport powered by activity This article is about human transport systems. For transport in cellular biology, see active transport. The urban bicycle, one of the most widespread and well-known vehicles for active mobility Active mobility, soft mobility, active travel, active transport or active transportation is the transport of people or goods, through non-motorized means, based around human physical activity.[1] The best-known forms of active mobility are walking and cycl…

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: コルク – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2017年4月) コルクを打ち抜いて作った瓶の栓 コルク(木栓、蘭&…

The Battle at Elderbush GulchPoster filmSutradaraD. W. GriffithDitulis olehD. W. GriffithHenry Albert PhillipsPemeranMae MarshLillian GishSinematograferG. W. BitzerDistributorGeneral Film CompanyTanggal rilis November 1913 (1913-11) Durasi29 menitNegaraAmerika SerikatBahasaBisu dengan intertitel Inggris Film lengkap The Battle at Elderbush Gulch (juga dikenal sebagai The Battle of Elderbush Gulch) adalah sebuah film koboi bisu Amerika Serikat tahun 1913 garapan D. W. Griffith[1] dan…

  لمعانٍ أخرى، طالع الحرب الأهلية العراقية (توضيح). الحرب الأهلية العراقية جزء من حرب الخليج الثالثة و صراعات الجماعات المسلحة العراقية   تحت سيطرة الشيعة   تحت سيطرة السنة    تحت سيطرة الأكراد   تحت سيطرة السريان   تحت سيطرة اليزيديين   تحت …

Italian actor (1929–2018) Paolo FerrariFerrari in 1961Born(1929-02-26)26 February 1929Brussels, BelgiumDied6 May 2018(2018-05-06) (aged 89)Rome, ItalyOccupation(s)Actor, voice actor, television presenterYears active1938-2018Height1.70 m (5 ft 7 in)Spouses Marina Bonfigli(m. 1956; div. 19??) Laura Tavanti ​(m. 1970)​ Children3, including Fabio Ferrari Paolo Ferrari (26 February 1929 – 6 May 2018) was an Italian actor, voice actor and t…

Canadian politician, entertainer and playwright The HonourableJean-Louis RouxCC CQ26th Lieutenant Governor of QuebecIn officeAugust 8, 1996 – January 30, 1997MonarchElizabeth IIGovernor GeneralRoméo LeBlancPremierLucien BouchardPreceded byMartial AsselinSucceeded byLise ThibaultSenator for Mille Isles, QuebecIn officeAugust 31, 1994 – August 8, 1996Appointed byJean ChrétienPreceded bySolange Chaput-RollandSucceeded byLéonce Mercier Personal detailsBorn(1923-05-18…

Boubacar Barry Informasi pribadiNama lengkap Boubacar Barry[1]Tanggal lahir 30 Desember 1979 (umur 44)Tempat lahir Abidjan, Pantai GadingTinggi 1,81 m (5 ft 11 in)[2]Posisi bermain GoalkeeperInformasi klubKlub saat ini LokerenNomor 1Karier senior*Tahun Tim Tampil (Gol)1999–2001 ASEC Mimosas 17 (0)2001–2003 Rennes B 23 (0)2003–2007 Beveren 102 (0)2007– Lokeren 151 (1)Tim nasional‡2000– Pantai Gading 69 (0) * Penampilan dan gol di klub senior hanya d…

Kembali kehalaman sebelumnya