SQL Lecture 1
SQL Lecture 1
INSERT INTO Employee VALUES ('Joe Smith', '123 4th St.', 101, 2500)
Using INSERT INTO .. VALUES
• You may INSERT a row with less than all the columns by naming the
columns you want to insert into, like this:
• INSERT INTO Employee (names, address) VALUES ('Joe Smith', '123
4th St.')
• The row will contain nulls or default values for the values left out,
which you will see if you type:
SELECT * FROM Employee
• Values MUST be inserted in the same order as the definition of the
table:
Using INSERT INTO .. SELECT
• INSERT INTO .. VALUES option, you insert only one row at a time into a
table. With the INSERT INTO .. SELECT option, you may (and usually
do) insert many rows into a table at one time.
• The general syntax for the INSERT INTO .. SELECT option is:
INSERT INTO target_table(column1, column2, column3, ...)
"SELECT clause"
• To copy all the names from the Employee table into the Names table,
type the following:
INSERT INTO Names(fullname)
SELECT names FROM Employee
Using INSERT INTO .. SELECT
• You could restrict the INSERT .. SELECT like this:
INSERT INTO Names(fullname)
SELECT names FROM Employee
WHERE salary > 2600
Using UPDATE
• You often UPDATE more than one row. To examine how the UPDATE
command works, we will use the tables we created.
• The general format for the UPDATE command is:
UPDATE TableName SET fieldname...
• For example, if you want to set all salaries in the table Emp2 to zero,
you may do so with one UPDATE command:
UPDATE Emp2 SET sal = 0
Using UPDATE
• Useful to include a WHERE clause in the UPDATE command so that
values are set selectively.
• UPDATE Employee SET salary = 0
• WHERE employee_number=101
Using DELETE FROM
• To delete all the rows in the Employee table as well as in the Names
table, type:
DELETE FROM Employee
• Then:
DELETE FROM Names
ALTER TABLE Command
• To add, change, and update rows in a table we use INSERT and
UPDATE commands.
• you can add, change (modify), and delete columns in a table's
definition by using SQL's ALTER TABLE command. ALTER TABLE
commands are known as data definition (DDL) commands, because
they change the definition of a table.
Adding a Column to a Table
• The general syntax for adding a column to a table is:
ALTER TABLE Tablename ADD column-name type
(condition) determines which rows of the table will be deleted. As you saw earlier, if
no WHERE condition is used, all the rows of the table will be deleted.
• Multiple rows can be affected by the DELETE command, so be careful when using it.
Here is an example of using the DELETE command on our original Employee table:
DELETE FROM Employee WHERE salary < 1500
Deleting a Table
• The general syntax to delete or remove an entire table and its
contents is:
DROP TABLE Tablename
• For example, to delete the table called Names from your database,
you would type the following:
DROP TABLE Names
CREATE SCHEMA example
CREATE SCHEMA sales;