what is the sql select statement

Upload: michael-rutor

Post on 08-Aug-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/22/2019 What is the SQL SELECT Statement

    1/13

    What is the SQL SELECT Statement?

    The SQL SELECT statement is the SQL command that retrieves data from an SQL database. Thisoperation is also known as a query and is the key to the use of SQL for analysis and reporting. Thistutorial section shows the basic SQL SELECT statement so see theSQL Advancedtutorial section formore in depth knowledge.

    Why Use the SQL SELECT Statement?

    Anytime you want to retrieve information from a SQL database use the SQL SELECT statement torequest the information.

    How To Use the SQL SELECT Statement

    The SQL SELECT command is used as follows. The asterisk can be used to SELECT all columns of atable.

    SQL SELECT Statement Syntax

    SELECT FROM

    SQL SELECT Statement Example 1

    The following example retrieves the columns product_nbr and product_name from all rows ofthe product table.

    SELECT product_nbr, product_nameFROM product

    Results from the execution of the SQL SELECT statement, also known as a query are as follows:

    product_nbrproduct_name

    1001 SQL Tool 1.0

    2001 SQL Tool 2.0 Light

    2002 SQL Tool 2.0 Professional

    2003 SQL Tool 2.0 Enterprise

    SQL SELECT Statement Example 2

    The following example retrieves all of the columns from all rows of the product table.

    SELECT *FROM product

    http://infogoal.com/sql/sql-advanced.htmhttp://infogoal.com/sql/sql-advanced.htmhttp://infogoal.com/sql/sql-advanced.htmhttp://infogoal.com/sql/sql-advanced.htm
  • 8/22/2019 What is the SQL SELECT Statement

    2/13

    Results show the product_status_code column that was not present in Example 1.

    product_nbrproduct_name product_status_code

    1001 SQL Tool 1.0 Inactive

    2001 SQL Tool 2.0 Light Active

    2002 SQL Tool 2.0 Professional Active

    2003 SQL Tool 2.0 Enterprise Active

    How To Use the SQL CREATE DATABASE Statement

    The SQL CREATE DATABASE statement is used as follows.

    SQL CREATE DATABASE Statement Syntax

    CREATE DATABASE

    SQL CREATE DATABASE Statement Example

    The following example creates a new database named CUSTOMER_DB.

    CREATE DATABASE customer_db

    What is the SQL CREATE INDEX Statement?

    The SQL INDEX TABLE statement is the SQL command that adds a new index to an existing table to anSQL database. Indexed enable faster and more efficient retrieval of information from SQL databases.

    Why Use the SQL CREATE INDEX Statement?

    SQL indexes are used because they can provide the following benefits / functions:

    Rapid access of information

    Efficient access of information

    Enforcement of uniqueness constraints

    Correct use of indexes can make the difference between a top performing database with highcustomer satisfaction and a non-performing database with low customer satisfaction.

    How To Use the SQL CREATE INDEX Statement

    The SQL CREATE INDEX command is used as follows.

  • 8/22/2019 What is the SQL SELECT Statement

    3/13

    SQL CREATE INDEX Statement Syntax

    CREATE INDEX ON (

    ,

    ,

    )

    CREATE UNIQUE INDEX ON (

    ,

    ,

    )

    The number of characters that can make up SQL names for tables, columns and indexes varies byDBMS. In many cases the limit is 30 characters. The leading character of the name must be alphabetic -not a number or special character. The name of a new index can not duplicate the name of an existing

    index for the same table and should not be the same as a SQL reserved word. The underscore charactercan be used to improve readability. List elements are seperated by commas.

    SQL CREATE INDEX Statement Example 1 - Rapid Access

    The following example creates an non-unique index named IDX_PERSON_NAME ontable PERSON with columns named person_name and gender_code in ascending sequence..

    Here are the contents of the table:

    Column Name Datatype Nullability

    person_id INT NOT NULL

    person_name VARCHAR(20) NOT NULL

    social_security_nbr CHAR(9) NULL

    gender_code CHAR(1) NULL

    line_1_addr VARCHAR(50) NULL

    city_name VARCHAR(50) NOT NULL

    state_code CHAR(2) NOT NULL

    zip_code CHAR(9) NOT NULL

    This SQL CREATE VIEW Statement is executed:

    CREATE INDEX IDX_PERSON_NAME ON PERSON

  • 8/22/2019 What is the SQL SELECT Statement

    4/13

    CREATE INDEX IDX_PERSON_NAME ON PERSON

    SQL CREATE INDEX Statement Example 2 - Enforce Uniqueness

    The following example creates a unique index named IDX_PERSON_SSN on table PERSON with thecolumn named social_security_nnbr. This assures that two rows can not be added to the PERSONtable with the same social security number.

    This SQL CREATE TABLE Statement is executed:

    CREATE INDEX IDX_PERSON_NAME ON PERSON

    What is the SQL CREATE TABLE Statement?

    The SQL CREATE TABLE statement is the SQL command that adds a new table to an SQL database.Tables are a basic unit of organization and storage of data in SQL. Each table tends to represent anentity such as a customer, product, code or event. A table is similar to a file in a non-database system.

    Tables are organized into rows and columns. For example, a customer table would likely have a seperaterow for each customer. Columns are attributes that describe a row. For example, a row in a customertable would have columns like customer_name, customer_nbr, account_balance_amt andestablished_date.

    Why Use the SQL CREATE TABLE Statement?

    Anytime you want to add a new table to the database you would use the SQL CREATE TABLEstatement.

    How To Use the SQL CREATE TABLE Statement

    The SQL CREATE TABLE command is used as follows.

    SQL CREATE TABLE Statement Syntax

    CREATE TABLE ( )

    The number of characters that can make up SQL table names and column names varies by DBMS. Inmany cases the limit is 30 characters. The leading character of the name must be alphabetic - not a

  • 8/22/2019 What is the SQL SELECT Statement

    5/13

    number or special character. The name of a new table can not duplicate the name of an existing tableand should not be the same as a SQL reserved word. The underscore character can be used to improvereadability. The same column name can not be repeated within a table. List elements are seperated bycommas.

    Here are some example datatypes:

    SQL Datatype Description

    integer(size)int(size)smallint(size)tinyint(size)

    Integers

    decimal(size,decimals)numeric(size,decimals)

    Numbers with decimals

    char(size) Fixed length character string

    varchar(size) Variable length character string

    date A date in yyyymmdd format

    SQL CREATE TABLE Statement Example

    The following example creates a table named product with columnsnamed product_nbr, product_name, product_status_code, start_date, end_date andraw_material_cost_amt.

    This SQL CREATE TABLE Statement is executed:

    CREATE TABLE product ( product_nbr int NOT NULL,product_name varchar(40) NOT NULL,product_status_code char(10) NOT NULL,start_date date NULL,

    end_date date NULL,raw_material_cost decimal(12,2) NULL,primary key (product_nbr))

    What is the SQL CREATE VIEW Statement?

    A SQL view is a virtual table and the SQL CRERATE VIEW statement is the SQL command that adds anew view to a SQL database.

    A view can be accessed using the SQL SELECT statement like a table. A view is built by selecting data

    from one or more tables.

    Some views can also support the SQL INSERT, SQL UPDATE and SQL DELETE statements. In thatcase, the view must refer to a single table and include all NOT NULL columns of that table.

    Why Use the SQL CREATE VIEW Statement?

    SQL views are used because they can provide the following benefits / functions:

  • 8/22/2019 What is the SQL SELECT Statement

    6/13

    Database queries are simplified

    Database complexity is hidden

    Flexibility is increased - queries of views may not change when underlying tables chagne

    Security is increased - sensitive information can be excluded from a view

    How To Use the SQL CREATE VIEW Statement

    The SQL CREATE VIEW command is used as follows.

    SQL CREATE VIEW Statement Syntax

    CREATE VIEW (,) AS

    The number of characters that can make up SQL names for tables, columns and views varies by DBMS.In many cases the limit is 30 characters. The leading character of the name must be alphabetic - not anumber or special character. The name of a new view can not duplicate the name of an existing view ortable and should not be the same as a SQL reserved word. The underscore character can be used toimprove readability. List elements are seperated by commas.

    SQL CREATE VIEW Statement Example - Data Filtering

    The following example creates a view named V_TOP_CUSTOMER on table CUSTOMER with thefollowing columns:

    customer_id

    customer_name ytd_sales_amt

    zip_code

    Here are the contents of the table:

    Column Name Datatype Nullability

    customer_id INT NOT NULL

    customer_name VARCHAR(20) NOT NULL

    ytd_sales_amt MONEY NOT NULL

    line_1_addr VARCHAR(50) NULL

    city_name VARCHAR(50) NOT NULL

    state_code CHAR(2) NOT NULL

    zip_code CHAR(9) NOT NULL

    This SQL CREATE VIEW Statement is executed:

    CREATE VIEW V_TOP_CUSTOMER (customer_id,

  • 8/22/2019 What is the SQL SELECT Statement

    7/13

    customer_name,ytd_sales_amt,zip_code)AS SELECT customer_id,customer_name,ytd_sales_amt,zip_codeFROM CUSTOMERWHERE ytd_sales_amt > 1200.00

    What is the SQL ALTER TABLE Statement?

    The SQL ALTER TABLE statement is the SQL command that makes changes to the definition of an SQLtable.

    Why Use the SQL ALTER TABLE Statement?

    Anytime you want to change the definition of an SQL table. For example, you could:

    Add a column to a table

    Change the definition of an existing column in a table

    Drop a column from a table

    How To Use the SQL ALTER TABLE Statement

    The SQL ALTER TABLE command is used as follows.

    SQL ALTER TABLE Statement Syntax

    ALTER TABLE ADD

    ALTER TABLE ALTER COLUMN

    ALTER TABLE DROP COLUMN

    SQL ALTER TABLE Statement Example 1 - Add a Column

    The following example adds a new column into the person table. Before the operation takes place thefollowing columns exists in the table:

    Column NameDatatype Nullability

    person_id INT NOT NULL

    person_name VARCHAR(20) NOT NULL

  • 8/22/2019 What is the SQL SELECT Statement

    8/13

    gender_code CHAR(1) NULL

    line_1_addr VARCHAR(50) NULL

    line_2_addr VARCHAR(50) NULL

    apartment_nbr VARCHAR(50) NULL

    city_name VARCHAR(50) NOT NULL

    state_code CHAR(2) NOT NULL

    zip_code CHAR(9) NOT NULL

    This ALTER TABLE Statement is executed:

    ALTER TABLE PERSONADD marital_status_code CHAR(1) NULL

    Results from the execution of the SQL ALTER TABLE statement are:

    Column Name Datatype Nullability

    person_id INT NOT NULL

    person_name ARCHAR(20) NOT NULL

    gender_code CHAR(1) NULL

    line_1_addr ARCHAR(50) NULL

    line_2_addr ARCHAR(50) NULL

    apartment_nbr ARCHAR(50) NULL

    city_name ARCHAR(50) NOT NULL

    state_code CHAR(2) NOT NULL

    zip_code CHAR(9) NOT NULL

    marital_status_codeCHAR(1) NULL

    SQL ALTER TABLE Statement Example 2 - Alter a Column Datatype

    The following example changes the datatype of an existing column in the person table. Before theoperation takes place the following columns exists in the table:

    Column NameDatatype Nullability

    person_id INT NOT NULL

    person_name VARCHAR(20) NOT NULL

    gender_code CHAR(1) NULL

    line_1_addr VARCHAR(50) NULL

    line_2_addr VARCHAR(50) NULL

    apartment_nbr VARCHAR(50) NULL

    city_name VARCHAR(50) NOT NULLstate_code CHAR(2) NOT NULL

    zip_code CHAR(9) NOT NULL

    This ALTER TABLE Statement is executed:

    ALTER TABLE PERSONALTER COLUMN person_name VARCHAR(50) NOT NULL

  • 8/22/2019 What is the SQL SELECT Statement

    9/13

    Results from the execution of the SQL ALTER TABLE statement are:

    Column Name Datatype Nullability

    person_id INT NOT NULL

    person_name VARCHAR(50)NOT NULL

    gender_code CHAR(1) NULL

    line_1_addr VARCHAR(50) NULL

    line_2_addr VARCHAR(50) NULL

    apartment_nbr VARCHAR(50) NULL

    city_name VARCHAR(50) NOT NULL

    state_code CHAR(2) NOT NULL

    zip_code CHAR(9) NOT NULL

    marital_status_code CHAR(1) NULL

    SQL ALTER TABLE Statement Example 3 - Drop a column

    The following example removes an existing column in the person table. Before the operation takes placethe following columns exists in the table:

    Column NameDatatype Nullability

    person_id INT NOT NULL

    person_name VARCHAR(50) NOT NULL

    gender_code CHAR(1) NULL

    line_1_addr VARCHAR(50) NULL

    line_2_addr VARCHAR(50) NULL

    apartment_nbr VARCHAR(50) NULL

    city_name VARCHAR(50) NOT NULL

    state_code CHAR(2) NOT NULLzip_code CHAR(9) NOT NULL

    This ALTER TABLE Statement is executed:

    ALTER TABLE dbo.PERSONDROP COLUMN apartment_nbr

    Results from the execution of the SQL ALTER TABLE statement are:

    Column NameDatatype Nullabilityperson_id INT NOT NULL

    person_name VARCHAR(50) NOT NULL

    gender_code CHAR(1) NULL

    line_1_addr VARCHAR(50) NULL

    line_2_addr VARCHAR(50) NULL

    city_name VARCHAR(50) NOT NULL

    state_code CHAR(2) NOT NULL

    zip_code CHAR(9) NOT NULL

  • 8/22/2019 What is the SQL SELECT Statement

    10/13

    What is SQL JOIN?

    The SQL JOIN is a clause that enables a SELECT statement to access more than one table. The JOIN

    clause controls how tables are linked. It is a qualifier of the SQL FROM clause.

    The standard JOIN clause (also known as the INNER JOIN clause) differs from the OUTER JOIN in thatrows are returned only when there are matches for the JOIN critieria on the second table.

    Why Use SQL JOIN?

    Use the SQL JOIN whenever multiple tables must be accessed through a SQL SELECT statement andno results should be returned if there is not a match between the JOINed tables.

    How To Use SQL JOIN

    SQL JOIN is used as follows. The ON clause describes the conditions of the JOIN.

    Important! A "cartesian product" can result if there is no relating the tables for the join. A row would beincluded for each combination between the two tables so if one table has 1,000 rows and the secondtable has 2,000 rows then 2,000,000 rows would be returned.

    Important! If there are no matches on the JOIN criteria then no rows will be returned. This is known an"INNER JOIN". Use the "OUTER JOIN" in cases where rows should be returned when one side of the joinis missing.

    SQL JOIN Syntax

    SELECT , FROM JOIN ON

    SQL JOIN Example

    The following example JOINs the region and branch tables on the region_nbr column.

    Here are the contents of the tables:

    Table: REGION

    region_nbrregion_name

    100 East Region

    200 Central Region

    300 Virtual Region

    400 West Region

    Table: BRANCH

  • 8/22/2019 What is the SQL SELECT Statement

    11/13

    branch_nbrbranch_nameregion_nbremployee_count

    108 New York 100 10

    110 Boston 100 6

    212 Chicago 200 5

    404 San Diego 400 6

    415 San Jose 400 3

    This SQL Statement with JOIN is executed:

    SELECT region.region_nbr, region.region_name, branch.branch_nbr, branch.branch_nameFROM dbo.regionJOIN dbo.branchON branch.region_nbr = region.region_nbrORDER BY region.region_nbr

    Here is the result. Note that the "Virtual Region" is included in the results even though it has no rows in

    the branch table. This is the difference between the INNER JOIN and OUTER JOIN.

    region_nbrregion_name branch_nbrbranch_name

    100 East Region 108 New York

    100 East Region 110 Boston

    200 Central Region 212 Chicago

    400 West Region 404 San Diego

    400 West Region 415 San Jose

    What is SQL OUTER JOIN?

    The SQL OUTER JOIN clause is a variation of the SQL JOIN clause enables a SELECT statement toaccess more than one table. The JOIN clause controls how tables are linked. It is a qualifier of the SQLFROM clause.

    The OUTER JOIN clause differs from the standard JOIN clause (also known as the INNER JOIN clause)in that rows are returned even when there are no matches through the JOIN critieria on the second table.

    Why Use SQL OUTER JOIN?

    Use the SQL OUTER JOIN whenever multiple tables must be accessed through a SQL SELECTstatement and results should be returned if there is not a match between the JOINed tables.

    It can be useful when there is a need to merge data from two tables and to include all rows from both

    tables without depending on a match. Another use is to generate a large result set for testing purposes.

    How To Use SQL OUTER JOIN

    SQL OUTER JOIN is used as follows. The ON clause describes the conditions of the JOIN.

  • 8/22/2019 What is the SQL SELECT Statement

    12/13

    Important! A "cartesian product" can result if there is no relating the tables for the join. A row would beincluded for each combination between the two tables so if one table has 1,000 rows and the secondtable has 2,000 rows then 2,000,000 rows would be returned.

    Important! If there are matches on the JOIN criteria then rows will still be returned. This is known an"OUTER JOIN". Use the "INNER JOIN" in cases where no rows should be returned when one side of the

    join is missing.

    SQL OUTER JOIN Syntax

    SELECT , FROM LEFT OUTER JOIN ON

    SQL OUTER JOIN Example

    The following example JOINs the region and branch tables on the region_nbr column.

    Here are the contents of the tables:

    Table: REGION

    region_nbrregion_name

    100 East Region

    200 Central Region

    300 Virtual Region

    400 West Region

    Table: BRANCH

    branch_nbrbranch_nameregion_nbremployee_count

    108 New York 100 10

    110 Boston 100 6

    212 Chicago 200 5

    404 San Diego 400 6

    415 San Jose 400 3

    This SQL Statement with OUTER JOIN is executed:

    SELECT region.region_nbr, region.region_name, branch.branch_nbr, branch.branch_nameFROM dbo.regionLEFT OUTER JOIN dbo.branchON branch.region_nbr = region.region_nbrORDER BY region.region_nbr

    Here is the result. Note that the "Virtual Region" is included in the results even though it has no rows inthe branch table. This is the difference between the INNER JOIN and OUTER JOIN.

  • 8/22/2019 What is the SQL SELECT Statement

    13/13

    region_nbrregion_name branch_nbrbranch_name

    100 East Region 108 New York

    100 East Region 110 Boston

    200 Central Region 212 Chicago

    300 Virtual Region NULL NULL

    400 West Region 404 San Diego

    400 West Region 415 San Jose