Structured Query Language ALTERing and SELECTing
Altering the table structure SQL: ALTER Table
SQL: Alter Table The ALTER TABLE command allows you to add, modify, or drop a column from an existing table. Add or drop a constraint from an existing table.
Adding column(s) to a table To add a column to an existing table: SQL> ALTER TABLE table_name ADD column_name column-definition; For example: ALTER TABLE supplier ADD supplier_name varchar2(50); This will add a column called supplier_name to the supplier table. To add multiple columns to an existing table: SQL> ALTER TABLE table_name ADD (column_1 column-definition, column_2 column-definition,... column_n column_definition ); For example: ALTER TABLE supplier ADD (supplier_name varchar2(50), city varchar2(45) ); This will add two columns (supplier_name and city) to the supplier table.
Remember our BOOK table? TITLE AUTHOR ISBN SHELF_CODE CATEGORY Databases Elmasri and Navathe 0-21-542263 C33-14 Computing Algorithms Upensky,Semenov 3-540-529217 M14-35 Maths Accounting Atrill, McLaney 0-273-688227 B23-43 Business C++ Schildt 0-072-232153 C33-14 Computing Operating System Bacon, Harris 0-321-117891 C33-20 Computing
EXERCISE Add the following columns to the BOOK table: price (a number in the format 99999.99, with a value of less than 100) qtyinstock (a 3-digit value that can be empty) datepublished (a date field);
Modifying column(s) in a table To modify a column in an existing table: ALTER TABLE table_name MODIFY column_name column_type; For example: ALTER TABLE supplier MODIFY supplier_name varchar2(100) not null; This will modify the column called supplier_name to be a data type of varchar2(100) and force the column to not allow null values. To modify multiple columns in an existing table: ALTER TABLE table_name MODIFY (column_1 column_type, column_2 column_type,... column_n column_type ); For example: ALTER TABLE supplier MODIFY (supplier_name varchar2(100) not null, city varchar2(75) ); This will modify both the supplier_name and city columns.
EXERCISE Modify the Title column to make it variable length, with a maximum length of 50. Change the size of the category column to 12. Change the size of the ISBN to 13 characters. Make the ISBN a primary key.
Drop column(s) in a table To drop a column in an existing table: ALTER TABLE table_name DROP COLUMN column_name; For example: ALTER TABLE supplier DROP COLUMN supplier_name; This will drop the column called supplier_name from the table called supplier.
Rename column(s) in a table To rename a column in an existing table: ALTER TABLE table_name RENAME COLUMN old_name to new_name; For example: ALTER TABLE supplier RENAME COLUMN supplier_name to sname; This will rename the column called supplier_name to sname.
ALTERING constraints To use ALTER to change constraints, you may: Add a constraint Drop a constraint Enable a constraint This happens automatically when the constraint is added. Disable a constraint Only used for legacy data.
Altering to add CHECK constraints ALTER TABLE table_name add CONSTRAINT constraint_name CHECK (column_name condition); E.g. ALTER TABLE suppliers add CONSTRAINT check_supplier_name CHECK (supplier_name IN ('IBM', 'Microsoft', 'Nvidia'));
Others alter table book add constraint testnull check (title is not null); alter table book add constraint book_type foreign key (category) references bookcat (category); ALTER TABLE book add CONSTRAINT shelfcodeuq UNIQUE (shelf_code);
Assume Book table now See Handout populated
SQL SQL stands for Structured Query Language. There is a standard SQL called the American National Standards Institute s 2003 Standard SQL (ANSI:2003 SQL) Most database vendors cover much of the standard, but do not adhere to it completely. Note, when you start using Oracle SQL, you will see that many of the functions are different.
Some definitions Metadata: This is data about data, i.e. table definitions, column definitions, etc. Data: This is the value that is held in the database, that must follow the rules of the metadata. Transaction: A transaction is a unit of work, passed to the database for processing. Session: A process that connects to the database, relating an individual user to a specific database (or schema) allowing the user to interact with the database, ending when the user disconnects from the database.
SQL What s in it? SQL is made up of different categories of commands: Data Definition Language Data Manipulation Language Transaction control statements Session or data control statements
Data Definition Language (DDL) This consists of commands that enable the database administrator, in association with the application developer, to manipulate the infrastructure of the database. This infrastructure is known as the conceptual schema. It enables definition of the metadata. The commands used to do this are: CREATE DROP ALTER TRUNCATE
Data Manipulation Language (DML) This consists of commands that enable the application developer to manipulate the data in the tables. The commands used are: SELECT INSERT UPDATE DELETE MERGE
Transaction Control Statements These statements allow the application developer to group DML statements, in order to conduct a transaction. A transaction is a unit of work, passed to the database for processing. A transaction will often require: Selection from one or more tables or views Insertion to one or more tables or views Update to one or more tables or views Deletion from one or more tables. Examples: Place an order for several items Register as a student Pay a phone bill.
Transaction Control Statements Most of the statements used during a transaction are DML statements (some DDL statements may be used). There are also transaction safeguard statements. These are: Commit Rollback
Data Control Language (DCL) These consist of statements that allow the database (schema) owner to control either his / her own sessions, or sessions of other users trying to access his / her data. The statements are: GRANT REVOKE And various SET commands (Session control)
So far we have met SELECT INSERT CREATE DROP Let s look back at them.
SELECT This statement is very versatile and is the single retrieval mechanism. Its basic components are SELECT Field-list FROM Table-list We have tried these in the labs, and will continue to do so.
SELECT field-list The field-list in a SELECT statement can be: A wildcard character * to denote all eligible fields. A column name that is unique to one of the tables in the table list. A table-name.column-name to specify a column from a specific table from the table list. A schema.table-name.column-name to specify a column in a specific table in a specific database A derived field
Derived fields in the SELECT fieldlist Fields can be derived by: Performing calculations on column-fields from the table-list. E.g. unitprice * quantity as linecost Using functions on the column-fields from the table list. E.g. day(orderdate) Using database provided functions. Oracle: Select sysdate from dual; (Dual is a working storage area for use in sessions connected to the database). This statement returns the current system date.
Table-list Initially, the queries we do will be on single tables, but as we get more fluent with SQL, we will start to do multi-table selects. The tables must belong to the same database / schema. Sometimes the database/schema name is required to qualify the table name. See later.
Additions to Select If you think of a table (e.g. Dog) as a 2D grid, the columnlist manipulates the columns: DogId Name Weight Age Diet Exercise Breed_Id 1 Goldie 40 3 Standard Standard Glab 2 Mutt 46 2 Standard Standard Glab 3 Spot 44 4 Standard Standard Pood 4 Sooty 55 5 Standard Standard Blab 5 Beauty 50 3 Specialised Specialised Grtv 6 Jack 67 4 Specialised Specialised GDan 7 Pal 55 5 Standard Standard Blab I ve shortened the column names here to fit it in the slide.
Select name, age from dog This query picks out specific columns from the table. This is known as projection. DogId Name Weight Age Diet Exercise Breed_Id 1 Goldie 40 3 Standard Standard Glab 2 Mutt 46 2 Standard Standard Glab 3 Spot 44 4 Standard Standard Pood 4 Sooty 55 5 Standard Standard Blab 5 Beauty 50 3 Specialised Specialised Grtv 6 Jack 67 4 Specialised Specialised GDan 7 Pal 55 5 Standard Standard Blab
To pick out rows: This is called selection and is done using the WHERE clause. This clause goes after the basic select: SELECT column-list FROM table-list WHERE condition The condition usually relates to a value in one or more of the columns from the column list.conditions The conditions can include: >,<,<>,<=,>=,!=, NOT, between, IS NULL, IS LIKE. The IS NULL returns a true if the value in the column is null, and a false otherwise. You will NEVER get anything if you use the condition WHERE column = NULL Null means undefined. You cannot equate to undefined!
LIKE LIKE allows us to match patterns in strings. Wildcard characters can be used to represent A character from a string _ A variable length substring from a string %.
Manipulating ROWS The WHERE clause allows to choose from specific ROWS in our query: SELECT dogname, dogage FROM dog WHERE dogage BETWEEN 2 and 4 Dogname DogAge Goldie 3 Mutt 2 Spot 4 Beauty 3 Jack 4
Formatting output What formatting may we want? String formatting Concatenation: Renaming AS clause SELECT price as cost FROM BOOK»or SELECT price as Unit Price FROM book; Numeric formatting (to_char).
Ordering your data To sort the output by a particular column, add the suffix ORDER BY column-name E.g. SELECT dogname, dogage FROM dog ORDER BY dogage Dogname DogAge Mutt 2 Goldie 3 Beauty 3 Jack 4 Spot 4 Sooty 5 Pal 5
Ordering your data You can reverse the order: SELECT dogname, dogage FROM dog ORDER BY dogage DESC Dogname DogAge Sooty 5 Pal 5 Jack 4 Spot 4 Goldie 3 Beauty 3 Mutt 2
Ordering your data You can also order it by two columns: SELECT dogname, dogage FROM dog ORDER BY dogage, dogname DESC Dogname DogAge Mutt 2 Goldie 3 Beauty 3 Spot 4 Jack 4 Sooty 5 Pal 5
FORMAT OF SELECT SELECT attribute list FROM This can be *, a list of attributes or a list of attributes with embedded text. Table list WHERE Condition list ORDER BY List of ordering fields.
Exercises Return the title and the price from the book table. Return the titles of all books that start with the letters Har