Monday, May 9, 2016

CREATE TABLE AS STATEMENT


This SQL tutorial explains how to use the SQL CREATE TABLE AS statement with syntax and examples.

DESCRIPTION

You can also use the SQL CREATE TABLE AS statement to create a table from an existing table by copying the existing table's columns.
It is important to note that when creating a table in this way, the new table will be populated with the records from the existing table (based on the SELECT Statement).

CREATE TABLE - BY COPYING ALL COLUMNS FROM ANOTHER TABLE

Syntax

The syntax for the SQL CREATE TABLE AS statement copying all of the columns is:
CREATE TABLE new_table
  AS (SELECT * FROM old_table);

Example

Let's look at an example that shows how to create a table by copying all columns from another table.
For Example:
CREATE TABLE suppliers
AS (SELECT *
    FROM companies
    WHERE id > 1000);
This would create a new table called suppliers that included all columns from the companies table.
If there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement.

CREATE TABLE - BY COPYING SELECTED COLUMNS FROM ANOTHER TABLE

Syntax

The syntax for the CREATE TABLE AS statement copying the selected columns is:
CREATE TABLE new_table
  AS (SELECT column_1, column2, ... column_n
      FROM old_table);

Example

Let's look at an example that shows how to create a table by copying selected columns from another table.
For Example:
CREATE TABLE suppliers
  AS (SELECT id, address, city, state, zip
      FROM companies
      WHERE id > 1000);
This would create a new table called suppliers, but the new table would only include the specified columns from the companiestable.
Again, if there were records in the companies table, then the new suppliers table would also contain the records selected by the SELECT statement.

CREATE TABLE - BY COPYING SELECTED COLUMNS FROM MULTIPLE TABLES

Syntax

The syntax for the CREATE TABLE AS statement copying columns from multiple tables is:
CREATE TABLE new_table
  AS (SELECT column_1, column2, ... column_n
      FROM old_table_1, old_table_2, ... old_table_n);

Example

Let's look at an example that shows how to create a table by copying selected columns from multiple tables.
For Example:
CREATE TABLE suppliers
  AS (SELECT companies.id, companies.address, categories.cat_type
      FROM companies, categories
      WHERE companies.id = categories.id
      AND companies.id > 1000);
This would create a new table called suppliers based on columns from both the companies and categories tables.

FREQUENTLY ASKED QUESTIONS

Question: How can I create a SQL table from another table without copying any values from the old table?
Answer: To do this, the SQL CREATE TABLE syntax is:
CREATE TABLE new_table
  AS (SELECT *
      FROM old_table WHERE 1=2);
For example:
CREATE TABLE suppliers
  AS (SELECT *
      FROM companies WHERE 1=2);
This would create a new table called suppliers that included all columns from the companies table, but no data from thecompanies table.

CREATE TABLE STATEMENT


This SQL tutorial explains how to use the SQL CREATE TABLE statement with syntax, examples, and practice exercises.

DESCRIPTION

The SQL CREATE TABLE statement allows you to create and define a table.

SYNTAX

The syntax for the SQL CREATE TABLE statement is:
CREATE TABLE table_name
( 
  column1 datatype [ NULL | NOT NULL ],
  column2 datatype [ NULL | NOT NULL ],
  ...
);

Parameters or Arguments

table_name
The name of the table that you wish to create.
column1, column2
The columns that you wish to create in the table. Each column must have a datatype. The column should either be defined as NULL or NOT NULL and if this value is left blank, the database assumes NULL as the default.

EXAMPLE

Let's look at a SQL CREATE TABLE example.
CREATE TABLE suppliers
( supplier_id int NOT NULL,
  supplier_name char(50) NOT NULL,
  contact_name char(50)
);
This SQL CREATE TABLE example creates a table called suppliers which has 3 columns.
  • The first column is called supplier_id which is created as a number datatype (maximum 10 digits in length) and can not contain null values.
  • The second column is called supplier_name which is a char datatype (50 maximum characters in length) and also can not contain null values.
  • The third column is called contact_name which is a char datatype but can contain null values.
Now the only problem with this SQL CREATE TABLE statement is that you have not defined a primary key for the table. We could modify this SQL CREATE TABLE statement and define the supplier_id as the primary key as follows:
CREATE TABLE suppliers
( supplier_id int NOT NULL,
  supplier_name char(50) NOT NULL,
  contact_name char(50),
  CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id)
);

PRACTICE EXERCISE #1:

Create a SQL table called customers that stores customer ID, name, and address information.

Solution for Practice Exercise #1:

The SQL CREATE TABLE statement for the customers table is:
CREATE TABLE customers
( customer_id int NOT NULL,
  customer_name char(50) NOT NULL,
  address char(50),
  city char(50),
  state char(25),
  zip_code char(10)
);

PRACTICE EXERCISE #2:

Create a SQL table called customers that stores customer ID, name, and address information.
But this time, the customer ID should be the primary key for the table.

Solution for Practice Exercise #2:

The SQL CREATE TABLE statement for the customers table is:
CREATE TABLE customers
( customer_id int NOT NULL,
  customer_name char(50) NOT NULL,
  address char(50),
  city char(50),
  state char(25),
  zip_code char(10),
  CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);

PRACTICE EXERCISE #3:

Based on the departments table below, create a SQL table called employees that stores employee number, employee name, department, and salary information. The primary key for the employees table should be the employee number. Create a foreign key on the employees table that references the departments table based on the department_id field.
CREATE TABLE departments
( department_id int NOT NULL,
  department_name char(50) NOT NULL,
  CONSTRAINT departments_pk PRIMARY KEY (department_id)
);

Solution for Practice Exercise #3:

The SQL CREATE TABLE statement for the employees table is:
CREATE TABLE employees
( employee_number int NOT NULL,
  employee_name char(50) NOT NULL,
  department_id int,
  salary int,
  CONSTRAINT employees_pk PRIMARY KEY (employee_number),
  CONSTRAINT fk_departments
    FOREIGN KEY (department_id)
    REFERENCES departments(department_id)
);

EXISTS CONDITION


This SQL tutorial explains how to use the SQL EXISTS condition with syntax and examples.

DESCRIPTION

The SQL EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL EXISTS condition is:
WHERE EXISTS ( subquery );

Parameters or Arguments

subquery
The subquery is a SELECT statement. If the subquery returns at least one record in its result set, the EXISTS clause will evaluate to true and the EXISTS condition will be met. If the subquery does not return any records, the EXISTS clause will evaluate to false and the EXISTS condition will not be met.

NOTE

  • SQL statements that use the EXISTS condition are very inefficient since the sub-query is rerun for EVERY row in the outer query's table. There are more efficient ways to write most queries, that do not use the EXISTS condition.

DDL/DML FOR EXAMPLES

If you want to follow along with this tutorial, get the DDL to create the tables and the DML to populate the data. Then try the examples in your own database!

EXAMPLE - USING EXISTS WITH SELECT STATEMENT

Let's look at an example that shows how to use the EXISTS condition with a SELECT statement.
In this example, we have a customers table with the following data:
CUSTOMER_ID  LAST_NAME  FIRST_NAME  FAVORITE_WEBSITE
-----------  ---------  ----------  ---------------------
       4000  Jackson    Joe         www.techonthenet.com
       5000  Smith      Jane        www.digminecraft.com
       6000  Ferguson   Samantha    www.bigactivities.com
       7000  Reynolds   Allen       www.checkyourmath.com
       8000  Anderson   Paige
       9000  Johnson    Derek       www.techonthenet.com
And a table called orders with the following data:
ORDER_ID  CUSTOMER_ID
--------  -----------
       1         5000
       2         6000
       3         7000
       4         9000
Now let's find all of the records from the customers table where there is at least one record in the orders table with the samecustomer_id. Enter the following SELECT statement:
SELECT *
FROM customers
WHERE EXISTS (SELECT *
              FROM orders
              WHERE customers.customer_id = orders.customer_id);
These are the results that you should see:
CUSTOMER_ID  LAST_NAME  FIRST_NAME  FAVORITE_WEBSITE
-----------  ---------  ----------  ---------------------
       5000  Smith      Jane        www.digminecraft.com
       6000  Ferguson   Samantha    www.bigactivities.com
       7000  Reynolds   Allen       www.checkyourmath.com
       9000  Johnson    Derek       www.techonthenet.com
In this example, there are 4 records in the customers where the customer_id value appears in the orders table.

EXAMPLE - USING NOT EXISTS WITH SELECT STATEMENT

The EXISTS condition can also be combined with the NOT operator to create a NOT EXISTS condition.
Let's use the NOT EXISTS condition to find all of the customers where there is not a record in the orders table with the samecustomer_id. Using the same customers and orders data as the previous example, enter the following SELECT statement:
SELECT *
FROM customers
WHERE NOT EXISTS (SELECT *
                  FROM orders
                  WHERE customers.customer_id = orders.customer_id);
These are the results that you should see:
CUSTOMER_ID  LAST_NAME  FIRST_NAME  FAVORITE_WEBSITE
-----------  ---------  ----------  ---------------------
       4000  Jackson    Joe         www.techonthenet.com
       8000  Anderson   Paige
In this example, there are 2 records in the customers table where the customer_id value does not appear in the orders table.

EXAMPLE - USING EXISTS WITH INSERT STATEMENT

Now, let's look at an example that shows how to use the EXISTS condition with an INSERT statement.
In this example, we have a contacts table that is empty and we want to populate:
CONTACT_ID  LAST_NAME  FIRST_NAME
----------  ---------  ----------
Let's insert into the contacts table all of the customer_id, last_name, and first_name values from the customers table where there is at least one record in the orders table with a matching customer_id.
INSERT INTO contacts
(contact_id, last_name, first_name)
SELECT customer_id, last_name, first_name
FROM customers
WHERE EXISTS (SELECT *
              FROM orders
              WHERE customers.customer_id = orders.customer_id);
Then select the data from the contacts table:
SELECT * FROM contacts;
These are the results that you should see:
CONTACT_ID  LAST_NAME  FIRST_NAME
----------  ---------  ----------
      5000  Smith      Jane
      6000  Ferguson   Samantha
      7000  Reynolds   Allen
      9000  Johnson    Derek
In this example, 4 records from the customers table will be inserted into the contacts table.

EXAMPLE - USING EXISTS WITH UPDATE STATEMENT

Let's look at an example that uses the EXISTS condition in an UPDATE statement.
In this example, we have a table called products with the following data:
PRODUCT_ID  PRODUCT_NAME  QUANTITY
----------  ------------  --------
         1  Pear                25
         2  Banana               0
         3  Orange              18
         4  Apple               45
And a table called summary_data with the following data:
PRODUCT_ID  CURRENT_LEVELS
----------  --------------
         1              10
         2              10
         3              10
         4              10
         5              10
Now let's update the summary_data table with values from the products table. Enter the following SQL statement:
UPDATE summary_data
SET current_levels = (SELECT quantity
                 FROM products
                 WHERE products.product_id = summary_data.product_id)
WHERE EXISTS (SELECT quantity
                 FROM products
                 WHERE products.product_id = summary_data.product_id);
Then select the data from the summary_data table again:
SELECT * FROM summary_data;
These are the results that you should see:
PRODUCT_ID  CURRENT_LEVELS
----------  --------------
         1              25
         2               0
         3              18
         4              45
         5              10
In this example, 4 records would be updated in the summary_data table.
TIP: Notice that our UPDATE statement included an EXISTS condition in the WHERE clause to make sure that there was a matching product_id in both the products and summary_data table before updating the record.
If we hadn't included the EXISTS condition, the UPDATE query would have updated the current_levels field to NULL in the last row of the summary_data table (because the products table does not have a record where product_id is 5).

EXAMPLE - USING EXISTS WITH DELETE STATEMENT

Let's look at an example that uses the EXISTS condition in a DELETE statement.
In this example, we have a table called products with the following data:
PRODUCT_ID  PRODUCT_NAME  QUANTITY
----------  ------------  --------
         1  Pear                25
         2  Banana               0
         3  Orange              18
         4  Apple               45
And a table called archival with the following data:
PRODUCT_ID
----------
         1
         2
         3
         4
         5
Now let's delete records from the archival table where there is at least one record in the products table with a matchingproduct_id. Enter the following SQL statement:
DELETE FROM archival
WHERE EXISTS (SELECT *
              FROM products
              WHERE products.product_id = archival.product_id);
Then select the data from the archival table again:
SELECT * FROM archival;
These are the results that you should see:
PRODUCT_ID
----------
         5
In this example, 4 records from the archival table will be deleted, leaving just one record remaining.

BETWEEN CONDITION


This SQL tutorial explains how to use the SQL BETWEEN condition with syntax and examples.

DESCRIPTION

The SQL BETWEEN Condition is used to retrieve values within a range in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL BETWEEN Condition is:
expression BETWEEN value1 AND value2;

Parameters or Arguments

expression
A column or calculation.
value1 and value2
These values create an inclusive range that expression is compared to.

NOTE

  • The SQL BETWEEN Condition will return the records where expression is within the range of value1 and value2(inclusive).

EXAMPLE - WITH NUMERIC

Let's look at some BETWEEN condition examples using numeric values. The following numeric example uses the BETWEEN condition to retrieve values within a numeric range.
For example:
SELECT *
FROM suppliers
WHERE supplier_id BETWEEN 5000 AND 5010;
This SQL BETWEEN example would return all rows where the supplier_id is between 5000 and 5010 (inclusive). It is equivalent to the following SQL SELECT statement:
SELECT *
FROM suppliers
WHERE supplier_id >= 5000
AND supplier_id <= 5010;

EXAMPLE - WITH DATE

Next, let's look at how you would use the BETWEEN condition with Dates. The following date example uses the SQL BETWEEN condition to retrieve values within a date range.
For example:
SELECT *
FROM orders
WHERE order_date BETWEEN TO_DATE ('2003/01/01', 'yyyy/mm/dd')
AND TO_DATE ('2003/12/31', 'yyyy/mm/dd');
This SQL BETWEEN condition example would return all orders where the order_date is between Jan 1, 2003 and Dec 31, 2003 (inclusive). It would be equivalent to the following SQL SELECT statement:
SELECT *
FROM orders
WHERE order_date >= TO_DATE('2003/01/01', 'yyyy/mm/dd')
AND order_date <= TO_DATE('2003/12/31','yyyy/mm/dd');

EXAMPLE - USING NOT OPERATOR

The SQL BETWEEN condition can also be combined with the SQL NOT operator. Here is an example of how you would combine the BETWEEN condition with the NOT Operator.
For example:
SELECT *
FROM suppliers
WHERE supplier_id NOT BETWEEN 5000 AND 5500;
This SQL BETWEEN condition example would return all rows where the supplier_id was NOT between 5000 and 5500, inclusive. It would be equivalent to the following SQL SELECT statement:
SELECT *
FROM suppliers
WHERE supplier_id < 5000
OR supplier_id > 5500;

IS NOT NULL CONDITION


This SQL tutorial explains how to use the SQL IS NOT NULL condition with syntax and examples.

DESCRIPTION

The SQL IS NOT NULL Condition is used to test for a NOT NULL value in SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL IS NOT NULL Condition is:
expression IS NOT NULL

Parameters or Arguments

expression
The expression to test for a NOT NULL value.

NOTE

  • If expression is not a NULL value, the condition evaluates to TRUE.
  • If expression is a NULL value, the condition evaluates to FALSE.

EXAMPLE - WITH SELECT STATEMENT

Let's look at an example of how to use SQL IS NOT NULL in a SQL SELECT statement:
SELECT *
FROM customers
WHERE customer_name IS NOT NULL;
This SQL IS NOT NULL example will return all records from the customers table where the customer_name does not contain a NULL value.

EXAMPLE - WITH INSERT STATEMENT

Next, let's look at an example of how to use SQL IS NOT NULL in a SQL INSERT statement:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE account_no IS NOT NULL;
This SQL IS NOT NULL example will insert records into the suppliers table where the account_no does not contain a NULL value in the customers table.

EXAMPLE - WITH UPDATE STATEMENT

Next, let's look at an example of how to use SQL IS NOT NULL in a SQL UPDATE statement:
UPDATE suppliers
SET supplier_name = 'Apple'
WHERE supplier_name IS NOT NULL;
This SQL IS NOT NULL example will update records in the suppliers table where the supplier_name does not contain a NULL value.

EXAMPLE - WITH DELETE STATEMENT

Next, let's look at an example of how to use SQL IS NOT NULL in a SQL DELETE statement:
DELETE FROM customers
WHERE status IS NOT NULL;
This SQL IS NOT NULL example will delete all records from the customers table where the status does not contain a NULL value.

Sunday, May 1, 2016

IS NULL CONDITION


This SQL tutorial explains how to use the SQL IS NULL condition with syntax and examples.

DESCRIPTION

The SQL IS NULL condition is used to test for a NULL value in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL IS NULL condition is:
expression IS NULL

Parameters or Arguments

expression
The expression to test for a NULL value.

NOTE

  • If expression is a NULL value, the condition evaluates to TRUE.
  • If expression is not a NULL value, the condition evaluates to FALSE.

EXAMPLE - WITH SELECT STATEMENT

Let's look at an example of how to use IS NULL in a SELECT statement:
SELECT *
FROM suppliers
WHERE supplier_name IS NULL;
This SQL IS NULL example will return all records from the suppliers table where the supplier_name contains a NULL value.

EXAMPLE - WITH INSERT STATEMENT

Next, let's look at an example of how to use SQL IS NULL in an INSERT statement:
INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM customers
WHERE city IS NULL;
This SQL IS NULL example will insert records into the suppliers table where the city contains a NULL value.

EXAMPLE - WITH UPDATE STATEMENT

Next, let's look at an example of how to use SQL IS NULL in an UPDATE statement:
UPDATE suppliers
SET supplier_name = 'Apple'
WHERE supplier_name IS NULL;
This SQL IS NULL example will update records in the suppliers table where the supplier_name contains a NULL value.

EXAMPLE - WITH DELETE STATEMENT

Next, let's look at an example of how to use SQL IS NULL in a DELETE statement:
DELETE FROM suppliers
WHERE supplier_name IS NULL;
This SQL IS NULL example will delete all records from the suppliers table where the supplier_name contains a NULL value

NOT CONDITION


This SQL tutorial explains how to use the SQL NOT condition with syntax and examples.

DESCRIPTION

The SQL NOT Condition (also known as the SQL NOT Operator) is used to negate a condition in a SELECT, INSERT, UPDATE, or DELETE statement.

SYNTAX

The syntax for the SQL NOT Condition is:
NOT condition

Parameters or Arguments

condition
This is the condition to negate. The opposite of the condition be must be met for the record to be included in the result set.

EXAMPLE - COMBINE WITH IN CONDITION

The SQL NOT condition can be combined with the IN Condition.
For example:
SELECT *
FROM suppliers
WHERE supplier_name NOT IN ( 'IBM', 'Hewlett Packard', 'Microsoft' );
This SQL NOT example would return all rows where the supplier_name is neither IBM, Hewlett Packard, or Microsoft. Sometimes, it is more efficient to list the values that you do not want, as opposed to the values that you do want.

EXAMPLE - COMBINE WITH IS NULL CONDITION

The SQL NOT condition can also be combined with the IS NULL Condition.
For example,
SELECT *
FROM customers
WHERE customer_name IS NOT NULL;
This SQL NOT example would return all records from the customers table where the customer_name does not contain a NULL value.

EXAMPLE - COMBINE WITH LIKE CONDITION

The SQL NOT condition can also be combined with the LIKE Condition.
For example:
SELECT supplier_name
FROM suppliers
WHERE supplier_name NOT LIKE 'T%';
By placing the SQL NOT Operator in front of the SQL LIKE condition, you are able to retrieve all suppliers whose supplier_namedoes not start with 'T'.

EXAMPLE - COMBINE WITH BETWEEN CONDITION

The SQL NOT condition can also be combined with the BETWEEN Condition. Here is an example of how you would combine the NOT Operator with the BETWEEN Condition.
For example:
SELECT *
FROM suppliers
WHERE supplier_id NOT BETWEEN 5000 AND 5500;
This SQL NOT example would return all rows where the supplier_id was NOT between 5000 and 5500, inclusive. It would be equivalent to the following SQL SELECT statement:
SELECT *
FROM suppliers
WHERE supplier_id < 5000
OR supplier_id > 5500;

EXAMPLE - COMBINE WITH EXISTS CONDITION

The SQL NOT condition can also be combined with the EXISTS Condition.
For example,
SELECT *
FROM suppliers
WHERE NOT EXISTS (SELECT * 
                  FROM orders
                  WHERE suppliers.supplier_id = orders.supplier_id);
This SQL NOT example would return all records from the suppliers table where there are no records in the orders table for the given supplier_id.