SQL DML and DDL SQL can be divided into two parts: The Data Manipulation Language (DML

) and the Data Definition Language (DDL). The query and update commands form the DML part of SQL:
y y y y

SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database

The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are:
y y y y y y y

CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index

The SQL SELECT DISTINCT Statement In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table. The DISTINCT keyword can be used to return only distinct (different) values. Combining AND & OR You can also combine AND and OR (use parenthesis to form complex expressions). SELECT * FROM Persons WHERE LastName='Svendson' AND (FirstName='Tove' OR FirstName='Ola') The ORDER BY Keyword

Note: Not all database systems support the TOP clause. The TOP clause can be very useful on large tables with thousands of records. If you want to sort the records in a descending order. Returning a large number of records can impact on performance. SQL SELECT TOP Equivalent in MySQL and Oracle MySQL Syntax SELECT column_name(s) FROM table_name LIMIT number Example SELECT * FROM Persons LIMIT 5 Oracle Syntax SELECT column_name(s) FROM table_name WHERE ROWNUM <= number Example SELECT * FROM Persons WHERE ROWNUM <=5 . The ORDER BY keyword sort the records in ascending order by default. SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC The TOP Clause The TOP clause is used to specify t he number of records to return.The ORDER BY keyword is used to sort the result-set by a specified column. you can use the DESC keyword.

we will list the types of JOIN you can use. .. and the differences between them.) SQL Alias You can give a table or a column another name by using an alias. SQL Alias Syntax for Tables SELECT column_name(s) FROM table_name AS alias_name SQL Alias Syntax for Columns SELECT column_name AS alias_name FROM table_name Different SQL JOINs Before we continue with examples. This can be a good thing to do if you have very long or complex table names or column names.. even if there are no matches in the left table FULL JOIN: Return rows when there is a match in one of the tables The SQL UNION Operator The UNION operator is used to combine the result-set of two or more SELECT statements.value2. even if there are no matches in the right table RIGHT JOIN: Return all rows from the right table.The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. An alias name could be anything.. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE column_name IN (value1. y y y y JOIN: Return rows when there is at least one match in both tables LEFT JOIN: Return all rows from the left table. but usually it is short.

SQL UNION Syntax SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 The SQL SELECT INTO Statement The SELECT INTO statement selects data from one table and inser ts it into a different table. The columns must also have similar data types. Also. We will focus on the following constraints: y NOT NULL . SQL SELECT INTO Syntax We can select all columns into the new table: SELECT * INTO new_table_name [IN externaldatabase] FROM old_tablename Or we can select only the columns we want into the new table: SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_tablename SQL Constraints Constraints are used to limit the type of data that can go into a table. the columns in each SELECT statement must be in the same order. The SELECT INTO statement is most often used to create backup copies of tables. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).Notice that each SELECT statement within the UNION must have the same number of columns.

SQL NOT NULL Constraint The NOT NULL constraint enforces a column to NOT accept NULL values. SQL UNIQUE Constraint on CREATE TABLE . LastName varchar(255) NOT NULL. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. This means that you cannot insert a new record. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values: CREATE TABLE Persons ( P_Id int NOT NULL. City varchar(255) ) SQL UNIQUE Constraint The UNIQUE constraint uniquely identifies each record in a database table.y y y y y UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT The next chapters will describe each constraint in details. Note that you can have many UNIQUE constraints per table. The NOT NULL constraint enforces a field to always contain a value. but only one PRIMARY KEY constraint per table. FirstName varchar(255). Address varchar(255). or update a record without adding a value to this field.

LastName varchar(255) NOT NULL. LastName varchar(255) NOT NULL.LastName) ) SQL UNIQUE Constraint on ALTER TABLE To create a UNIQUE constraint on the "P_Id" column when the table is already created. City varchar(255). City varchar(255). FirstName varchar(255).The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created: MySQL: CREATE TABLE Persons ( P_Id int NOT NULL. Address varchar(255). use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL. FirstName varchar(255). use the following SQL: . Address varchar(255). City varchar(255) ) To allow naming of a UNIQUE constraint. LastName varchar(255) NOT NULL. and for defining a UNIQUE constraint on multiple columns. CONSTRAINT uc_PersonID UNIQUE (P_Id. FirstName varchar(255). UNIQUE (P_Id) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE. Address varchar(255).

LastName) To DROP a UNIQUE Constraint To drop a UNIQUE constraint.MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD UNIQUE (P_Id) To allow naming of a UNIQUE constraint. SQL PRIMARY KEY Constraint on CREATE TABLE The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created: . Primary keys must contain unique values. use the following SQL: MySQL: ALTER TABLE Persons DROP INDEX uc_PersonID SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT uc_PersonID SQL PRIMARY KEY Constraint The PRIMARY KEY constraint uniquely identifies each record in a database table. and for defining a UNIQUE constraint on multiple columns. A primary key column cannot contain NULL values. use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id. Each table should have a primary key. and each table can have only ONE primary key.

Address varchar(255). CONSTRAINT pk_PersonID PRIMARY KEY (P_Id. LastName varchar(255) NOT NULL. LastName varchar(255) NOT NULL. FirstName varchar(255). City varchar(255). City varchar(255). FirstName varchar(255). use the following SQL: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons . FirstName varchar(255).MySQL: CREATE TABLE Persons ( P_Id int NOT NULL. Address varchar(255). Address varchar(255).LastName) ) SQL PRIMARY KEY Constraint on ALTER TABLE To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created. and for defining a PRIMARY KEY constraint on multiple columns. use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL. LastName varchar(255) NOT NULL. City varchar(255) ) To allow naming of a PRIMARY KEY constraint. PRIMARY KEY (P_Id) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY.

SQL DEFAULT Constraint on CREATE TABLE The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created: My SQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( . use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id. the primary key column(s) must already have been declared to not contain NULL values (when the table was first created). use the following SQL: MySQL: ALTER TABLE Persons DROP PRIMARY KEY SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT pk_PersonID SQL DEFAULT Constraint The DEFAULT constraint is used to insert a default value into a column. if no other value is specified. The default value will be added to all new records.LastName) Note: If you use the ALTER TABLE statement to add a primary key. and for defining a PRIMARY KEY constraint on multiple columns. To DROP a PRIMARY KEY Constraint To drop a PRIMARY KEY constraint.ADD PRIMARY KEY (P_Id) To allow naming of a PRIMARY KEY constraint.

FirstName varchar(255). OrderDate date DEFAULT GETDATE() ) SQL DEFAULT Constraint on ALTER TABLE To create a DEFAULT constraint on the "City" column when the table is already created. City varchar(255) DEFAULT 'Sandnes' ) The DEFAULT constraint can also be used to insert system values. LastName varchar(255) NOT NULL. use the following SQL: MySQL: ALTER TABLE Persons ALTER City DROP DEFAULT SQL Server / Oracle / MS Access: ALTER TABLE Persons ALTER COLUMN City DROP DEFAULT . P_Id int. Address varchar(255). OrderNo int NOT NULL. use the following SQL: MySQL: ALTER TABLE Persons ALTER City SET DEFAULT 'SANDNES' SQL Server / Oracle / MS Access: ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'SANDNES' To DROP a DEFAULT Constraint To drop a DEFAULT constraint. by using functions like GETDATE(): CREATE TABLE Orders ( O_Id int NOT NULL.P_Id int NOT NULL.

SQL CREATE VIEW Syntax CREATE VIEW view_name AS SELECT column_name(s) . The users cannot see the indexes. Duplicate values are allowed: CREATE INDEX index_name ON table_name (column_name) SQL CREATE UNIQUE INDEX Syntax Creates a unique index on a table. So you should only create indexes on columns (and tables) that will be frequently searched against. and JOIN statements to a view and present the data as if the data were coming from one single table. SQL CREATE INDEX Syntax Creates an index on a table. Duplicate values are not allowed: CREATE UNIQUE INDEX index_name ON table_name (column_name) Note: The syntax for creating indexes varies amongst different databases. SQL CREATE VIEW Statement In SQL. You can add SQL functions. Therefore: Check the syntax for c reating indexes in your database.Indexes An index can be created in a table to find data more quickly and efficiently. A view contains rows and columns. The fields in a view are fields from one or more real tables in the database. WHERE. they are just used to speed up searches/queries. a view is a virtual table based on the result-set of an SQL statement. just like a real table. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an upd ate).

Category FROM Products WHERE Discontinued=No SQL Dropping a View You can delete a view with the DROP VIEW command. using the view's SQL statement. We will update the view with the following SQL: CREATE VIEW [Current Product List] AS SELECT ProductID.45 32. SQL Updating a View You can update a view by using the following syntax: SQL CREATE OR REPLACE VIEW Syntax CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition Now we want to add the "Category" column to the "Current Product List" view.67 UnitsInStock 16 23 9 UnitsOnOrder 15 20 .56 15.ProductName. SQL DROP VIEW Syntax DROP VIEW view_name SQL ISNULL(). every time a user queries a view.FROM table_name WHERE condition Note: A view always shows up-to-date data! The database engine recreates the data. NVL(). IFNULL() and COALESCE() Functions Look at the following "Products" table: P_Id 1 2 3 ProductName Jarlsberg Mascarpone Gorgonzola UnitPrice 10.

Microsoft's ISNULL() function is used to specify how we want to treat NULL values. we can use the NVL() function to achieve the same result: SELECT ProductName.0)) FROM Products or we can use the COALESCE() function. it works a little bit different from Microsoft's ISNULL() function. We have the following SELECT statement: SELECT ProductName.UnitPrice*(UnitsInStock+NVL(UnitsOnOrder.UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder. In this case we want NULL values to be zero. like this: SELECT ProductName. Below.UnitPrice*(UnitsInStock+UnitsOnOrder) FROM Products In the example above.0)) FROM Products MySQL MySQL does have an ISNULL() function. The NVL(). the result is NULL. and may contain NULL values.Suppose that the "UnitsOnOrder" column is optional.UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder. like this: SELECT ProductName.0)) FROM Products Oracle Oracle does not have an ISNULL() function. if "UnitsOnOrder" is NULL it will not harm the calculation.0)) FROM Products . and COALESCE() functions can also be used to achieve the same result. because ISNULL() returns a zero if the value is NULL: SQL Server / MS Access SELECT ProductName. if any of the "UnitsOnOrder" values are NULL. IFNULL(). However. In MySQL we can use the IFNULL() function.UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder. However.

a blank value will be inserted.'Z') Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice VARCHAR(size) TINYTEXT TEXT BLOB MEDIUMTEXT MEDIUMBLOB LONGTEXT LONGBLOB ENUM(x. and special characters). Can store up to 255 characters. Holds up to 65.z.967.777.535 characters For BLOBs (Binary Large OBjects).777. If a value is inserted that is not in the list. Holds up to 4.535 bytes of data Holds a string with a maximum length of 16. The fixed size is specified in parenthesis.295 characters For BLOBs (Binary Large OBjects).967. You enter the possible values in this format: ENUM('X'. Can store up to 255 characters Holds a variable length string (can contain letters. 0 to 16777215 UNSIGNED*.294.215 characters For BLOBs (Binary Large OBjects). The maximum number of . and special characters).d) A small number with a floating decimal point. numbers.etc. The maximum number of digits may be specified in parenthesis MEDIUMINT(size) -8388608 to 8388607 normal.215 bytes of data Holds a string with a maximum length of 4. Note: If you put a greater value than 255 it will be converted to a TEXT type Holds a string with a maximum length of 255 characters Holds a string with a maximum length of 65. 0 to 255 UNSIGNED*. 0 to 65535 UNSIGNED*.y. The maximum size is specified in parenthesis. Note: The values are sorted in the order you enter them.295 bytes of data Let you enter a list of possible values. 0 to 18446744073709551615 UNSIGNED*.294. The maximum number of digits may be specified in parenthesis FLOAT(size. The maximum number of digits may be specified in parenthesis INT(size) -2147483648 to 2147483647 normal.'Y'. numbers. The maximum number of digits may be specified in parenthesis BIGINT(size) -9223372036854775808 to 9223 372036854775807 normal. Holds up to 16. You can list up to 65535 values in an ENUM list. Text types: Data type CHAR(size) Description Holds a fixed length string (can contain letters.MySQL Data Types In MySQL there are three main types : text. The maximum number of digits may be specified in parenthesis SMALLINT(size) -32768 to 32767 normal.) SET Number types: Data type TINYINT(size) Description -128 to 127 normal. and Date/Time types. number. 0 to 4294967295 UNSIGNED*.

Date types: Data type DATE() Description A date. TIMESTAMP also accepts various formats. The maximum number of digits to the right of the decimal point is specified in the d parameter DECIMAL(size. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59' *A timestamp. The maximum number of digits may be specified in the size parameter. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59' A year in two-digit or four-digit format. the TIMESTAMP automatically set itself to the current date and time. The maximum number of digits to the right of the decimal point is specified in the d parameter *The integer types have an extra option called UNSIGNED. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31' *A date and time combination. Note: Values allowed in four-digit format: 1901 to 2155. In an INSERT or UPDATE query. DATETIME() TIMESTAMP() TIME() YEAR() . YYYYMMDD.digits may be specified in the size parameter. Values allowed in two-digit format: 70 to 69. like YYYYMMDDHHMMSS. the integer goes from an negative to positive value. Format: YYYY-MMDD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038 01-09 03:14:07' UTC A time. or YYMMDD. Normally. The maximum number of digits to the right of the decimal point is specified in the d parameter DOUBLE(size.d) A large number with a floating decimal point.d) A DOUBLE stored as a string . The maximum number of digits may be specified in the size parameter. YYMMDDHHMMSS. allowing for a fixed decimal point. they work very differently. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number. representing years from 1970 to 2069 *Even if DATETIME and TIMESTAMP return the same format.

Sign up to vote on this title
UsefulNot useful