writing basic sql select statements - spsharmag.com filewriting basic sql select statements basic...

16
Writing Basic SQL SELEC Basic SELECT Statement Selecting All Columns Selecting Specific Columns Writing SQL Statements Column Heading Defaults Arithmetic Expressions Using Arithmetic Operators Operator Precedence Using Parentheses Defining a Null Value Null Values in Arithmetic Exp Defining a Column Alias Using Column Aliases Concatenation Operator Using the Concatenation Ope Literal Character Strings Using Literal Character Strin Duplicate Rows Eliminating Duplicate Rows Restricting and Sorting Da Limiting Rows Using a Select Limiting the Rows Selected Using the WHERE Clause Character Strings and Dates Comparison Conditions Using Comparison Condition Other Comparison Condition Using the BETWEEN Conditio CT Statements pressions erator ngs ata tion s ns ns on

Upload: lamhanh

Post on 19-Jul-2018

238 views

Category:

Documents


0 download

TRANSCRIPT

Writing Basic SQL SELECT Statements

Basic SELECT StatementSelecting All ColumnsSelecting Specific ColumnsWriting SQL StatementsColumn Heading DefaultsArithmetic ExpressionsUsing Arithmetic OperatorsOperator PrecedenceUsing ParenthesesDefining a Null ValueNull Values in Arithmetic ExpressionsDefining a Column AliasUsing Column AliasesConcatenation OperatorUsing the Concatenation OperatorLiteral Character StringsUsing Literal Character StringsDuplicate RowsEliminating Duplicate Rows

Restricting and Sorting Data

Limiting Rows Using a SelectionLimiting the Rows SelectedUsing the WHERE ClauseCharacter Strings and DatesComparison ConditionsUsing Comparison ConditionsOther Comparison ConditionsUsing the BETWEEN Condition

Writing Basic SQL SELECT Statements

Null Values in Arithmetic Expressions

Using the Concatenation Operator

Using Literal Character Strings

Restricting and Sorting Data

Limiting Rows Using a Selection

Character Strings and Dates

Using Comparison ConditionsComparison Conditions

Using the BETWEEN Condition

Using the IN ConditionUsing the LIKE ConditionUsing the NULL ConditionsLogical ConditionsUsing the AND OperatorUsing the OR OperatorUsing the NOT OperatorRules of PrecedenceORDER BY ClauseSorting in Descending OrderSorting by Column AliasSorting by Multiple Columns

Single-Row Functions

SQL FunctionTwo Types of SQL FunctionsSingle-Row FunctionsSingle-Row FunctionsCharacter FunctionsCharacter FunctionsCase Manipulation FunctionsUsing Case Manipulation FunctionsCharacter-Manipulation FunctionsUsing the Character-Manipulation FunctionsNumber FunctionsUsing the ROUND FunctionUsing the TRUNC FunctionUsing the MOD FunctionWorking with DatesArithmetic with DatesUsing Arithmetic Operators with DatesDate FunctionsUsing Date FunctionsPractice 3, Part One:Conversion FunctionsImplicit Data Type ConversionExplicit Data Type ConversionUsing the TO_CHAR Function with DatesElements of the Date Format ModelUsing the TO_CHAR Function with DatesUsing the TO_CHAR Function with NumbersUsing the TO_NUMBER and TO_DATE Functions

Sorting in Descending Order

Two Types of SQL Functions

Case Manipulation FunctionsUsing Case Manipulation Functions

Manipulation FunctionsManipulation Functions

Using Arithmetic Operators with Dates

Implicit Data Type ConversionExplicit Data Type Conversion

the TO_CHAR Function with DatesElements of the Date Format ModelUsing the TO_CHAR Function with DatesUsing the TO_CHAR Function with NumbersUsing the TO_NUMBER and TO_DATE Functions

RR Date FormatExample of RR Date FormatNesting FunctionsGeneral FunctionsNVL FunctionUsing the NVL FunctionUsing the NVL2 FunctionUsing the NULLIF FunctionUsing the COALESCE FunctionConditional ExpressionsThe CASE ExpressionUsing the CASE ExpressionThe DECODE FunctionUsing the DECODE Function

Displaying Data from Multiple Tables

Obtaining Data from Multiple TablesCartesian ProductsGenerating a Cartesian ProductTypes of JoinsJoining Tables Using Oracle SyntaxWhat is an Equijoin?Retrieving Records with EquijoinsAdditional Search Conditions Using the AND OperatorQualifying Ambiguous Column NamesUsing Table AliasesJoining More than Two TablesNon-EquijoinsRetrieving Records with NonOuter Joins Outer Joins SyntaxUsing Outer JoinsSelf JoinsJoining a Table to ItselfJoining Tables Using SQL: 1999 SyntaxCreating Cross JoinsCreating Natural JoinsRetrieving Records with Natural JoinsCreating Joins with the USING ClauseRetrieving Records with the USING ClauseCreating Joins with the ON ClauseRetrieving Records with the ON ClauseCreating Three-Way Joins with the ON Clause

Using the COALESCE Function

Displaying Data from Multiple Tables

Obtaining Data from Multiple Tables

Generating a Cartesian Product

Joining Tables Using Oracle Syntax

Retrieving Records with EquijoinsAdditional Search Conditions Using the AND Operator

fying Ambiguous Column Names

Joining More than Two Tables

Retrieving Records with Non-EquijoinsOuter Joins Outer Joins Syntax

ng Tables Using SQL: 1999 Syntax

Retrieving Records with Natural JoinsCreating Joins with the USING ClauseRetrieving Records with the USING ClauseCreating Joins with the ON ClauseRetrieving Records with the ON Clause

Way Joins with the ON Clause

INNER Versus OUTER JoinsLEFT OUTER JOINRIGHT OUTER JOINFULL OUTER JOINAdditional Conditions

Aggregating Data Using Group Functions

What Are Group Functions?Types of Group FunctionsGroup Functions SyntaxUsing the AVG and SUM FunctionsUsing the MIN and MAX FunctionsUsing the COUNT FunctionUsing the DISTINCT KeywordGroup Functions and Null ValuesUsing the NVL Function with Group FunctionsCreating Groups of DataCreating Groups of Data: The GROUP BY Clause SyntaxUsing the GROUP BY ClauseGrouping by More Than One ColumnUsing the GROUP BY Clause on Multiple ColumnsIllegal Queries Using Group FunctionsExcluding Group ResultsExcluding Group Results: The HAVING ClauseUsing the HAVING ClauseNesting Group Functions

Subqueries

ObjectivesUsing a Subquery to Solve a ProblemSubquery SyntaxUsing a SubqueryGuidelines for Using SubqueriesTypes of SubqueriesSingle-Row SubqueriesExecuting Single-Row SubqueriesUsing Group Functions in a SubqueryThe HAVING Clause with SubqueriesWhat is Wrong with this Statement?Will this Statement Return Rows?Multiple-Row Subqueries

Aggregating Data Using Group Functions

Using the AVG and SUM FunctionsUsing the MIN and MAX Functions

Using the DISTINCT KeywordGroup Functions and Null ValuesUsing the NVL Function with Group Functions

Creating Groups of Data: The GROUP BY Clause Syntax

Grouping by More Than One Columnthe GROUP BY Clause on Multiple Columns

al Queries Using Group Functions

Excluding Group Results: The HAVING Clause

Using a Subquery to Solve a Problem

Guidelines for Using Subqueries

Row SubqueriesUsing Group Functions in a SubqueryThe HAVING Clause with SubqueriesWhat is Wrong with this Statement?Will this Statement Return Rows?

Using the ANY Operator in MultipleUsing the ALL Operator in MultipleNull Values in a Subquery

Manipulating Data

Data Manipulation LanguageAdding a New Row to a TableThe INSERT Statement Syntax 8Inserting New RowsInserting Rows with Null ValuesInserting Special ValuesInserting Specific Date ValuesCreating a ScriptCopying Rows from Another TableChanging Data in a TableThe UPDATE Statement SyntaxUpdating Rows in a TableUpdating Two Columns with a SubqueryUpdating Rows Based on Another TableUpdating Rows: Integrity Constraint ErrorRemoving a Row from a TableThe DELETE StatementDeleting Rows from a TableDeleting Rows Based on Another TableDeleting Rows: Integrity Constraint ErrorUsing a Subquery in an INSERT StatementUsing the WITH CHECK OPTION Keyword on DML StatementsOverview of the Explicit Default FeatureUsing Explicit Default ValuesThe MERGE StatementThe MERGE Statement SyntaxMerging RowsDatabase TransactionsAdvantages of COMMIT and ROLLBACK StatementsControlling TransactionsRolling Back Changes to a MarkerImplicit Transaction ProcessingState of the Data Before COMMIT or ROLLBACKState of the Data after COMMITCommitting DataState of the Data After ROLLBACKStatement-Level Rollback

Using the ANY Operator in Multiple-Row Subqueriesthe ALL Operator in Multiple-Row Subqueries

Data Manipulation LanguageAdding a New Row to a TableThe INSERT Statement Syntax 8-5

Inserting Rows with Null Values

Inserting Specific Date Values

ng Rows from Another Table

The UPDATE Statement Syntax

Updating Two Columns with a SubqueryUpdating Rows Based on Another TableUpdating Rows: Integrity Constraint ErrorRemoving a Row from a Table

Deleting Rows Based on Another TableDeleting Rows: Integrity Constraint ErrorUsing a Subquery in an INSERT StatementUsing the WITH CHECK OPTION Keyword on DML StatementsOverview of the Explicit Default FeatureUsing Explicit Default Values

The MERGE Statement Syntax

Advantages of COMMIT and ROLLBACK Statements

Rolling Back Changes to a MarkerImplicit Transaction ProcessingState of the Data Before COMMIT or ROLLBACKState of the Data after COMMIT

of the Data After ROLLBACK

Read ConsistencyImplementation of Read ConsistencyLockingImplicit LockingRead Consistency Example

Creating and Managing Tables

Database ObjectsNaming RulesThe CREATE TABLE StatementReferencing Another User?s TablesThe DEFAULT OptionCreating TablesTables in the Oracle DatabaseQuerying the Data Dictionary 9Data TypesDateTime Data TypesTIMESTAMP WITH TIME ZONE Data TypeTIMESTAMP WITH LOCAL TIME Data TypeINTERVAL YEAR TO MONTH Data TypeINTERVAL DAY TO SECOND Data TypeCreating a Table by Using a Subquery SyntaxCreating a Table by Using a SubqueryThe ALTER TABLE StatementAdding a ColumnModifying a ColumnDropping a ColumnThe SET UNUSED OptionDropping a TableChanging the Name of an ObjectTruncating a TableAdding Comments to a Table

Including Constraints

What are Constraints?Constraint GuidelinesDefining ConstraintsThe NOT NULL ConstraintThe UNIQUE ConstraintThe PRIMARY KEY ConstraintThe FOREIGN KEY Constraint

Implementation of Read Consistency

Creating and Managing Tables

The CREATE TABLE Statementencing Another User?s Tables

Tables in the Oracle DatabaseQuerying the Data Dictionary 9-10

TIMESTAMP WITH TIME ZONE Data TypeTIMESTAMP WITH LOCAL TIME Data Type

VAL YEAR TO MONTH Data TypeINTERVAL DAY TO SECOND Data TypeCreating a Table by Using a Subquery SyntaxCreating a Table by Using a SubqueryThe ALTER TABLE Statement

Changing the Name of an Object

Adding Comments to a Table

The PRIMARY KEY ConstraintOREIGN KEY Constraint

FOREIGN KEY Constraint KeywordsThe CHECK ConstraintAdding a Constraint SyntaxAdding a ConstraintDropping a ConstraintDisabling ConstraintsEnabling ConstraintsCascading ConstraintsViewing ConstraintsViewing the Columns Associated with Constraints

Creating Views

Database ObjectsWhat is a View?Why use Views?Simple Views and Complex ViewsCreating a ViewRetrieving Data from a ViewQuerying a ViewModifying a ViewCreating a Complex ViewRules for Performing DML Operations on a ViewUsing the WITH CHECK OPTION ClauseDenying DML OperationsRemoving a ViewInline ViewsTop-N AnalysisPerforming Top-N AnalysisExample of Top-N Analysis

Other Database Objects

Database ObjectsWhat is a Sequence?The CREATE SEQUENCE Statement SyntaxCreating a SequenceConfirming SequencesNEXTVAL and CURRVAL PseudocolumnsUsing a SequenceModifying a SequenceGuidelines for Modifying a SequenceRemoving a Sequence

FOREIGN KEY Constraint Keywords

Viewing the Columns Associated with Constraints

Simple Views and Complex Views

Retrieving Data from a View

Rules for Performing DML Operations on a ViewUsing the WITH CHECK OPTION Clause

The CREATE SEQUENCE Statement Syntax

NEXTVAL and CURRVAL Pseudocolumns

Guidelines for Modifying a Sequence

What is an Index?How Are Indexes Created?Creating an IndexWhen to Create an IndexWhen Not to Create an IndexConfirming IndexesFunction-Based IndexesRemoving an IndexCreating and Removing Synonyms

Controlling User Access

ObjectivesControlling User AccessPrivilegesSystem PrivilegesCreating UsersUser System PrivilegesGranting System PrivilegesWhat is a Role?Creating and Granting Privileges to a RoleChanging Your PasswordObject PrivilegesGranting Object PrivilegesUsing the WITH GRANT OPTION and PUBLIC KeywordsConfirming Privileges GrantedHow to Revoke Object PrivilegesRevoking Object PrivilegesDatabase Links

SQL Workshop

Workshop Overview

Using SET Operators

The SET OperatorsTables Used in This LessonThe UNION OperatorUsing the UNION OperatorThe UNION ALL OperatorUsing the UNION ALL OperatorThe INTERSECT Operator

When Not to Create an Index

ing and Removing Synonyms

ing and Granting Privileges to a Role

Using the WITH GRANT OPTION and PUBLIC KeywordsConfirming Privileges GrantedHow to Revoke Object Privileges

Using the UNION ALL Operator

Using the INTERSECT OperatorThe MINUS OperatorSET Operator GuidelinesThe Oracle Server and SET OperatorsMatching the SELECT StatementsControlling the Order of Rows

Enhancements to the GROUP BY Clause

Review of Group FunctionsReview of the GROUP BY ClauseReview of the HAVING ClauseGROUP BY with ROLLUP and CUBE OperatorsROLLUP OperatorROLLUP Operator ExampleCUBE OperatorCUBE Operator: ExampleGROUPING FunctionGROUPING Function: ExampleGROUPING SETSGROUPING SETS: ExampleComposite ColumnsComposite Columns: ExampleConcatenated GroupingsConcatenated Groupings Example

Advanced Subqueries

What Is a Subquery?SubqueriesUsing a SubqueryMultiple-Column SubqueriesColumn ComparisonsPairwise Comparison SubqueryNonpairwise Comparison SubqueryUsing a Subquery in the FROM ClauseScalar Subquery ExpressionsScalar Subqueries: ExamplesCorrelated SubqueriesUsing Correlated SubqueriesUsing the EXISTS OperatorUsing the NOT EXISTS OperatorCorrelated UPDATE

Using the INTERSECT Operator

The Oracle Server and SET OperatorsMatching the SELECT StatementsControlling the Order of Rows

Enhancements to the GROUP BY Clause

Review of the GROUP BY ClauseReview of the HAVING ClauseGROUP BY with ROLLUP and CUBE Operators

GROUPING Function: Example

Composite Columns: Example

tenated Groupings Example

Pairwise Comparison SubqueryNonpairwise Comparison SubqueryUsing a Subquery in the FROM Clause

r Subquery ExpressionsScalar Subqueries: Examples

Using Correlated Subqueries

Using the NOT EXISTS Operator

Correlated DELETEThe WITH ClauseWITH Clause: Example

Hierarchical Retrieval

Sample Data from the EMPLOYEES TableNatural Tree StructureHierarchical QueriesWalking the TreeWalking the Tree: From the Bottom UpWalking the Tree: From the Top DownRanking Rows with the LEVEL PseudocolumnFormatting Hierarchical Reports Using LEVEL and LPADPruning Branches

Extensions to DML and DDL Statements

Review of the INSERT StatementReview of the UPDATE StatementOverview of Multitable INSERT StatementsOverview of Multitable INSERT StatementsTypes of Multitable INSERT StatementsMultitable INSERT StatementsUnconditional INSERT ALLConditional INSERT ALLConditional FIRST INSERTPivoting INSERTExternal TablesCreating an External TableExample of Creating an External TableQuerying External TablesCREATE INDEX with CREATE TABLE Statement

Part I: Programming in PL/SQL

Introduction to PL/SQLWhat Is PL/SQL?The Origins of PL/SQL

Sample Data from the EMPLOYEES Table

Walking the Tree: From the Bottom UpWalking the Tree: From the Top DownRanking Rows with the LEVEL Pseudocolumn

tting Hierarchical Reports Using LEVEL and LPAD

Extensions to DML and DDL Statements

Review of the INSERT StatementReview of the UPDATE StatementOverview of Multitable INSERT StatementsOverview of Multitable INSERT StatementsTypes of Multitable INSERT StatementsMultitable INSERT Statements

Example of Creating an External Table

CREATE INDEX with CREATE TABLE Statement

Plsql syllabus

Part I: Programming in PL/SQL

About PL/SQL VersionsResources for PL/SQL Developers

Creating and Running PL/SQL Code

SQL*PlusPerforming Essential PL/SQL TasksCalling PL/SQL from Other LanguagesLanguage FundamentalsPL/SQL Block StructureThe PL/SQL Character SetIdentifiersLiteralsThe Semicolon DelimiterCommentsThe PRAGMA KeywordLabels

Part II: PL/SQL Program Structure

Conditional and Sequential ControlIF StatementsCASE Statements and ExpressionsThe GOTO StatementThe NULL StatementIterative Processing with Loops

Loop Basics

The Simple LoopThe WHILE LoopThe Numeric FOR LoopThe Cursor FOR LoopLoop LabelsTips for Iterative Processing

Exception Handlers

Exception-Handling Concepts and TerminologyDefining ExceptionsRaising ExceptionsHandling Exceptions

rces for PL/SQL Developers

Creating and Running PL/SQL Code

Performing Essential PL/SQL TasksCalling PL/SQL from Other Languages

Part II: PL/SQL Program Structure

Conditional and Sequential Control

CASE Statements and Expressions

Iterative Processing with Loops

Handling Concepts and Terminology

Building an Effective Error Management ArchitectureMaking the Most of PL/SQL Error Management

Part III: PL/SQL Program Data

Working with Program DataNaming Your Program DataOverview of PL/SQL DatatypesDeclaring Program DataProgrammer-Defined SubtypesConversion Between Datatypes

Strings

String DatatypesWorking with StringsString Function Quick Reference

Numbers

Numeric DatatypesNumber ConversionsNumeric Functions

Records

Records in PL/SQL

Collections

Collections OverviewCollection Methods (Built-Ins)Working with CollectionsNested Table Multiset OperationsMaintaining Schema-Level Collections

Miscellaneous Datatypes

The BOOLEAN DatatypeThe RAW DatatypeThe UROWID and ROWID DatatypesThe LOB Datatypes

ing an Effective Error Management ArchitectureMaking the Most of PL/SQL Error Management

Part III: PL/SQL Program Data

Overview of PL/SQL Datatypes

Defined SubtypesConversion Between Datatypes

g Function Quick Reference

Ins)

Nested Table Multiset OperationsLevel Collections

The UROWID and ROWID Datatypes

Working with LOBsPredefined Object Types

Part IV: SQL in PL/SQL

DML and Transaction ManagementDML in PL/SQLBulk DML with the FORALL StatementTransaction ManagementAutonomous Transactions

Data Retrieval

Cursor BasicsWorking with Implicit CursorsWorking with Explicit CursorsBULK COLLECTSELECT ... FOR UPDATECursor Variables and REF CURSORsCursor Expressions

Procedures, Functions, and Parameters

ProceduresFunctionsParametersLocal ModulesModule OverloadingForward DeclarationsAdvanced TopicsGo Forth and Modularize!

Packages

Why Packages?Rules for Building PackagesRules for Calling Packaged ElementsWorking with Package DataWhen to Use PackagesPackages and Object Types

Triggers

DML and Transaction Management

Bulk DML with the FORALL Statement

Working with Implicit Cursorsng with Explicit Cursors

Cursor Variables and REF CURSORs

Procedures, Functions, and Parameters

Rules for Calling Packaged Elements

DML TriggersDDL TriggersDatabase Event TriggersINSTEAD OF TriggersAFTER SUSPEND TriggersMaintaining Triggers

Managing PL/SQL Code

Managing Code in the DatabaseUsing Native CompilationUsing the Optimizing Compiler and CompileConditional CompilationTesting PL/SQL ProgramsDebugging PL/SQL ProgramsTuning PL/SQL ProgramsProtecting Stored Code

I/O and PL/SQL

Displaying InformationReading and Writing FilesSending EmailWorking with Web-Based Data (HTTP)Other Types of I/O Available in PL/SQL

Oracle Forms Developer 10g: Build Internet Applications

Introducing Oracle Forms Developer and Forms ServicesGrid ComputingOracle 10g ProductsOracle Application Server 10g ArchitectureBenefits and Components of Oracle Developer Suite 10gRunning a Forms Developer ApplicationWorking in the Forms Developer EnvironmentCreating Forms ModulesWorking with Data Blocks and FramesWorking with Input ItemsWorking with Non Input Items

Managing Code in the Database

Using the Optimizing Compiler and Compile-Time Warnings

Debugging PL/SQL Programs

Based Data (HTTP)Other Types of I/O Available in PL/SQL

Oracle Forms

Oracle Forms Developer 10g: Build Internet Applications

Introducing Oracle Forms Developer and Forms Services

Oracle Application Server 10g Architectureits and Components of Oracle Developer Suite 10g

Running a Forms Developer ApplicationWorking in the Forms Developer Environment

Working with Data Blocks and Frames

Working with Non Input Items

Working with Windows and CanvasesProducing TriggersDebugging TriggersAdding Functionality to ItemsRun-Time Messages and AlertsQuery TriggersValidationNavigationTransaction ProcessingSharing Objects and CodeUsing WebUtil to Interact with the ClientIntroducing Multiple Form Applications

Oracle Reports Developer 10g: Build Reports

Introduction to Oracle Reports DeveloperBusiness IntelligenceEnterprise ReportingOracle Reports DeveloperOracle Database 10gOracle Developer Suite 10gOracle Application Server 10gOracleAS Reports ServicesOracleAS Reports Services Architecture for the WebDesigning and Running ReportsExploring Oracle Reports DeveloperCreating a Paper ReportEnhancing a Basic Paper ReportManaging Report TemplatesCreating a Web ReportEnhancing Reports Using the Data Model: Queries and GroupsEnhancing Reports Using the Data Model: Data SourcesEnhancing Reports Using the Data Model: Creating ColumnsEnhancing Reports Using the Paper LayoutControlling the Paper Layout: Common PropertiesControlling the Paper Layout: Specific PropertiesWeb ReportingExtending Functionality Using XMLCreating and Using Report ParametersEmbedding a Graph in a Report

Working with Windows and Canvases

Adding Functionality to ItemsTime Messages and Alerts

Using WebUtil to Interact with the Clientducing Multiple Form Applications

Oracle Reports

Oracle Reports Developer 10g: Build Reports

duction to Oracle Reports Developer

Oracle Application Server 10g

OracleAS Reports Services Architecture for the Webning and Running Reports

Exploring Oracle Reports Developer

Enhancing a Basic Paper Report

Enhancing Reports Using the Data Model: Queries and GroupsEnhancing Reports Using the Data Model: Data Sources

cing Reports Using the Data Model: Creating Columnscing Reports Using the Paper Layout

Controlling the Paper Layout: Common PropertiesControlling the Paper Layout: Specific Properties

Extending Functionality Using XMLCreating and Using Report ParametersEmbedding a Graph in a Report

Enhancing Matrix ReportsCoding PL/SQL TriggersExtending Functionality Using the SRW PackageMaximizing Performance UsingOracleAS Reports ServicesBuilding Reports: Efficiency GuidelinesWorking with SQL WorksheetUsing SQL Developer

107, Jaina Extn. (2nd Floor), Above Arya Gas Agency, Near Batra Cinema, Dr.E-Mail: [email protected]

ding Functionality Using the SRW PackageMaximizing Performance Using

Building Reports: Efficiency GuidelinesWorking with SQL Worksheet

Above Arya Gas Agency, Near Batra Cinema, Dr. Mukherjee Nagar, [email protected], Website: www.parashartechnologies.com

Mob: 09910707562, 07840057408

Mukherjee Nagar, Delhi-110009www.parashartechnologies.com