Insert, Update and the rest… SQL COMMANDS Insert, Update and the rest…
Lecture Objectives Utilize the standard query language (SQL) to perform the following tasks: Add Rows to the Database Change Existing Rows in the Database Delete Rows from the Database Create, Alter and Remove Tables from the Database
Insert Command What about NULL values? Allows the insertion of data into a table one row at a time Used for new tables, or tables with existing data Syntax 1: INSERT INTO <tbl_name> VALUES (attrib_value1, attrib_value2,…) Values for all attributes in the table Name of the table What about NULL values? Syntax 2: INSERT INTO <tbl_name> VALUES (attrib_value1, attrib_value2, NULL, …) Column cannot be specified as not null
Insert Command Alternate syntax When will Insert NOT Work? Syntax 3: INSERT INTO <tbl_name>(col1, col2, …) VALUES (attrib_value1, attrib_value2,…) All other columns will be inserted as null or their default value Does not need to be all columns, just those columns specified as not null with no default value When will Insert NOT Work?
Update Command Modify an attribute of one or more rows in a given table Syntax: UPDATE <tbl_name> SET columnname = value [, columnname=value,..] [WHERE CLAUSE] One or more changes to attributes Where clause acts just like a select where clause with =, LIKE, sub-queries etc. When will Update NOT Work?
Delete Command Removes rows from a single table Syntax: DELETE FROM <tbl_name> [WHERE CLAUSE] Table name to delete rows from Where clause acts just like a select where clause with =, LIKE, sub-queries etc. Will delete ever remove from more than one table?
Create Table Command Creates a new relation/table by giving the name, attributes and constraints on the table This is a “water-downed” version of the command Name of New Table Syntax: CREATE TABLE <tbl_name> ( column1 datatype [constraint], column2 datatype [constraint], . PRIMARY KEY (column1, column2, …) FOREIGN KEY (column1, column2, …) REFERENCES <tbl_name2>) Column Names Set Primary and Foreign Keys
Create Table Command Data types – a few examples Numeric Data types NUMBER(I,D) INTEGER SMALLINT DECIMAL(I,D) Character Data types CHAR(L) VARCHAR(L) Date DATE
Alter Table Command Change the table structure in a pre-existing table Syntax 1: ALTER TABLE <tbl_name> [ADD|MODIFY] (columnname datatype) Syntax 2: ALTER TABLE <tbl_name> DROP COLUMN <column_name> Table name to Alter Remove a Column from the table Add or Change Column Settings Note: more options available for the alter command
Drop Table Command Remove the table and its data from the database Syntax: DROP TABLE <tbl_name> Table name to remove from the database
Examples