+ All Categories
Home > Documents > iq_query

iq_query

Date post: 12-Jul-2015
Category:
Upload: shyam-singh
View: 44 times
Download: 1 times
Share this document with a friend
Popular Tags:

of 172

Transcript

Sybase IQ Query Guide

Sybase IQ Version 11.2.x Document ID: 39650-01-1121-01 Last Revised: August 15, 1997

Principal author: AIPD Technical Publications Document ID: 39650-01-1121 This publication pertains to Sybase IQ Version 11.2.x of the Sybase database management software and to any subsequent release until otherwise indicated in new editions or technical notes. Information in this document is subject to change without notice. The software described herein is furnished under a license agreement, and it may be used or copied only in accordance with the terms of that agreement.

Document OrdersTo order additional documents, U.S. and Canadian customers should call Customer Fulllment at (800) 685-8225, fax (617) 229-9845. Customers in other countries with a U.S. license agreement may contact Customer Fulllment via the above fax number. All other international customers should contact their Sybase subsidiary or local distributor. Upgrades are provided only at regularly scheduled software release dates. Copyright 19891997 by Sybase, Inc. All rights reserved. No part of this publication may be reproduced, transmitted, or translated in any form or by any means, electronic, mechanical, manual, optical, or otherwise, without the prior written permission of Sybase, Inc.

Sybase TrademarksSybase, the Sybase logo, APT-FORMS, Certied SYBASE Professional, Data Workbench, First Impression, InfoMaker, PowerBuilder, Powersoft, Replication Server, S-Designor, SQL Advantage, SQL Debug, SQL SMART, SQL Solutions, Transact-SQL, VisualWriter, and VQL are registered trademarks of Sybase, Inc. Adaptable Windowing Environment, Adaptive Component Architecture, Adaptive Server, Adaptive Server Monitor, ADA Workbench, AnswerBase, Application Manager, AppModeler, APT-Build, APT-Edit, APT-Execute, APT-Library, APT-Translator, APT Workbench, Backup Server, BayCam, Bit-Wise, ClearConnect, Client-Library, Client Services, CodeBank, Column Design, Connection Manager, DataArchitect, Database Analyzer, DataExpress, Data Pipeline, DataWindow, DB-Library, dbQ, Developers Workbench, DirectConnect, Distribution Agent, Distribution Director, Dynamo, Embedded SQL, EMS, Enterprise Client/Server, Enterprise Connect, Enterprise Manager, Enterprise SQL Server Manager, Enterprise Work Architecture, Enterprise Work Designer, Enterprise Work Modeler, EWA, Formula One, Gateway Manager, GeoPoint, ImpactNow, InformationConnect, InstaHelp, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, KnowledgeBase, Logical Memory Manager, MainframeConnect, Maintenance Express, MAP, MDI Access Server, MDI Database Gateway, media.splash, MetaWorks, MethodSet, Net-Gateway, NetImpact, Net-Library, ObjectConnect, ObjectCycle, OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Client, Open ClientConnect, Open Client/Server, Open Client/Server Interfaces, Open Gateway, Open Server, Open

ServerConnect, Open Solutions, Optima++, PB-Gen, PC APT-Execute, PC DB-Net, PC Net Library, Power++, Power AMC, PowerBuilt, PowerBuilt with PowerBuilder, PowerDesigner, Power J, PowerScript, PowerSite, PowerSocket, Powersoft Portfolio, Power Through Knowledge, PowerWare Desktop, PowerWare Enterprise, ProcessAnalyst, Quickstart Datamart, Replication Agent, Replication Driver, Replication Server Manager, Report-Execute, Report Workbench, Resource Manager, RW-DisplayLib, RW-Library, SAFE, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners, smart.parts, smart.script, SQL Anywhere, SQL Central, SQL Code Checker, SQL Edit, SQL Edit/TPU, SQL Modeler, SQL Remote, SQL Server, SQL Server/CFT, SQL Server/DBM, SQL Server Manager, SQL Server SNMP SubAgent, SQL Station, SQL Toolset, Sybase Client/Server Interfaces, Sybase Development Framework, Sybase Gateways, Sybase IQ, Sybase MPP, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL Workgroup, Sybase Synergy Program, Sybase Virtual Server Architecture, Sybase User Workbench, SybaseWare, SyBooks, System 10, System 11, the System XI logo, SystemTools, Tabular Data Stream, The Architecture for Change, The Enterprise Client/Server Company, The Model for Client/Server Solutions, The Online Information Center, Translation Toolkit, Turning Imagination Into Reality, Unibom, Unilib, Uninull, Unisep, Unistring, Viewer, Visual Components, VisualSpeller, WarehouseArchitect, WarehouseNow, Warehouse WORKS, Watcom, Watcom SQL, Watcom SQL Server, Web.SQL, WebSights, WebViewer, WorkGroup SQL Server, XA-Library, and XA-Server are trademarks of Sybase, Inc. 6/97 All other company and product names used herein may be trademarks or registered trademarks of their respective companies.

Restricted RightsUse, duplication, or disclosure by the government is subject to the restrictions set forth in subparagraph (c)(1)(ii) of DFARS 52.227-7013 for the DOD and as set forth in FAR 52.227-19(a)-(d) for civilian agencies. Sybase, Inc., 6475 Christie Avenue, Emeryville, CA 94608.

Table of ContentsAbout This BookAudience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii How to Use This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Other Sources of Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv Sybase Certications on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv Formatting SQL Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv SQL Syntax Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Mandatory Options {You Must Choose At Least One}. . . . . . . . . . . xvii Optional Options [You Dont Have to Choose Any]. . . . . . . . . . . . . xviii Ellipsis: Do It Again (and Again)... . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii Pathname Differences Between Windows NT and UNIX. . . . . . . . . . . . xviii If You Need Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix

1. Getting StartedIntroduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1 Data Warehousing and Decision Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1 About Sybase IQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 Architecture Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 Documentation Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4 Connecting to Sybase IQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Connecting Through a Client Application . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Connecting Through isql . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Creating and Populating the Indexspace . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7 Opening and Closing the Indexspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7 Sybase IQ Commands and Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8 Passing Statements to the Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11 Identiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11 Qualifying Name Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13 Customizing Your Sybase IQ Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13

2. Using QueriesIntroduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1

Sybase IQ Query Guide

v

Sybase IQ Version 11.2.x

Overview of Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1 Sybase IQ Queries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1 Query Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 Datatypes for Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 General Datatype Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 NULLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 Dening Literals and E Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 Datatype of Mixed-Mode Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 Matching Datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 Implicit and Explicit Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 Retrieving Data from Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 Query Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 The SELECT Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9 Qualifying Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9 Selecting Data from Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-11 The FROM Clause. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12 The WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-17 The GROUP BY Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-20 The HAVING Clause. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-21 Search Conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-24 Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-24 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-24 Value Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-25 Comparison Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-26 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-27 BETWEEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28 IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28 LIKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-29 Wildcards for LIKE Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30 Wildcards as Literals in LIKE Predicates. . . . . . . . . . . . . . . . . . . . . . . 2-31 IS NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-31 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-33 EXISTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-33 Arithmetic Expressions and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-34 The CASE Expression. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-35 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-37

vi

Table of Contents

Sybase IQ Version 11.2.x

The ORDER BY Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-37 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 2-41

3. Using Subqueries and FunctionsIntroduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1 Using Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1 Using Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5 Aggregate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-10 CAST Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10 Style Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11 Punctuation Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13 Literal Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14 General CAST Formatting Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-16 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-19 CONVERT Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-21 DATEADD Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-23 DATEDIFF Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-25 DATEPART Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-29 ROUND Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-29 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-31 String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-31 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-36 SUSER_ID and SUSER_NAME Functions . . . . . . . . . . . . . . . . . . . . . . . . 3-36 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 3-37

4. Retrieving Data from Multiple TablesIntroduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Join Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Join Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Join Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Other Predicates as Join Conditions . . . . . . . . . . . . . . . . . . . . . How Joins Are Processed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Equijoins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Joins Not Based on Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Joins with Additional Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1 4-1 4-2 4-3 4-3 4-3 4-4 4-4 4-5

Sybase IQ Query Guide

vii

Sybase IQ Version 11.2.x

Self-Joins and Correlation Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6 Joining More Than Two Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 Joining Tables in Main and Private Indexspaces . . . . . . . . . . . . . . . . . . . . 4-9 Types of Joins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9 Inner Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10 Outer Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10 Outer Join Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14 NULLs in Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . 4-16 Predened vs. Ad Hoc Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17 Joined Indexsets vs. Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20 Improving Query Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20 Optimizing Ad Hoc Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-21 Union Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-26 Compliance with Transact-SQL and SQL-92 . . . . . . . . . . . . . . . . . . . . . . 4-28 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29 View Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-30 Creating Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-30 The CREATE VIEW Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-31 Dening Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-32 Dropping Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-32

Glossary Index

viii

Table of Contents

List of FiguresFigure 1-1: Figure 2-1: Figure 2-2: Figure 2-3: Figure 2-4: Figure 4-1: Figure 4-2: Open architecture ..........................................................................................................1-3 Sybase IQ datatype hierarchy ......................................................................................2-6 Explicit, implicit, and unsupported datatype conversions .....................................2-7 Data from SQL Server to Sybase IQ ............................................................................2-7 Truth table for combined logical expressions ..........................................................2-22 Sample query execution plan.....................................................................................4-25 Illustration of a view ...................................................................................................4-29

Sybase IQ Query Guide

ix

Sybase IQ Version 11.2.x

x

List of Figures

List of TablesTable 1: Table 1-1: Table 1-2: Table 1-3: Table 1-4: Table 2-1: Table 2-2: Table 2-3: Table 2-4: Table 2-5: Table 3-1: Table 3-2: Table 3-3: Table 3-4: Table 3-5: Table 3-6: Table 3-7: Table 3-8: Table 4-1: Syntax statement conventions .................................................................................... xvi A map to Sybase IQ information.................................................................................1-4 isql command line parameters.....................................................................................1-5 Sybase IQ SQL statements............................................................................................1-8 Sybase IQ SET options ................................................................................................1-14 Sybase IQ datatypes ......................................................................................................2-3 WHERE clause qualiers............................................................................................2-15 Comparison operators ................................................................................................2-26 Wildcards ......................................................................................................................2-30 Arithmetic operators ...................................................................................................2-34 Sybase IQ aggregate functions.....................................................................................3-7 General style characters ..............................................................................................3-12 DATE style characters .................................................................................................3-12 Time style characters ...................................................................................................3-13 Display formats for date/time information.............................................................3-20 Date parts and values..................................................................................................3-25 Arguments used in string functions .........................................................................3-31 Function names, arguments, and results..................................................................3-32 Outer join operators ....................................................................................................4-11

Sybase IQ Query Guide

xi

Sybase IQ Version 11.2.x

xii

List of Tables

About This BookThe Sybase IQ Query Guide is a guide to data retrieval using Sybase IQ.

AudienceThis manual is intended for Sybase IQ end users who are familiar with ANSI-standard SQL and Transact-SQL. It provides syntax and usage information for Sybase IQ data retrieval statements and functions.

How to Use This BookThis manual consists of the following sections: Chapter 1, Getting Started, provides an introduction to Sybase IQ and its SQL interface. Chapter 2, Using Queries, explains Sybase IQ datatypes and the SELECT command. Chapter 3, Using Subqueries and Functions, describes the subqueries and functions that Sybase IQ supports. Chapter 4, Retrieving Data from Multiple Tables, describes Sybase IQ operations that let you examine data from multiple tables. The Glossary denes common terms used throughout the documentation set.

Related DocumentsOther manuals that you may nd useful are: Sybase IQ Administration Guide, which explains Sybase IQ system administration issues Sybase IQ Installation and Conguration Guide, which describes the installation procedure for Sybase IQ Sybase IQ Language Reference, which provides syntax and usage notes for commands

Sybase IQ Query Guide

xiii

Other Sources of Information

Sybase IQ Version 11.2.x

Sybase IQ Quick Reference, which provides syntax for commands and stored procedures

Other Sources of InformationUse the SyBooks and SyBooks-on-the-Web online resources to learn more about your product: SyBooks documentation is on the CD that comes with your software. The DynaText browser, also included on the CD, allows you to access technical information about your product in an easy-to-use format. Refer to Installing SyBooks in your documentation package for instructions on installing and starting SyBooks. SyBooks-on-the-Web is an HTML version of SyBooks that you can access using a standard Web browser. To use SyBooks-on-the-Web, go to http://www.sybase.com, and choose Documentation.

Sybase Certications on the WebThe Technical Support information on the Sybase Web site is updated frequently. For the latest information on product certications and/or the EBF Rollups: 1. Point your Web browser to the Technical Information Library at the following URL: http://techinfo.sybase.com 2. In the Browse section, click on the Hot entry. 3. Explore your area of interest: Hot Docs covering various topics, or Hot Links to Technical News, Certication Reports, Partner Certications, and so on. If you are a registered SupportPlus user: 1. Point your Web browser to the Technical Information Library at the following URL. http://techinfo.sybase.com 2. In the Browse section, click on the Hot entry.

xiv

About This Book

Sybase IQ Version 11.2.x

Conventions

3. Click on the EBF Rollups entry. You can research EBFs using the Technical Information Library, and you can download EBFs using Electronic Software Distribution (ESD). 4. Follow the instructions associated with the SupportPlusSM Online Services entries. If you are not a registered SupportPlus user and want to become one: You can register by following the instructions on the Web. To use SupportPlus, you need: A Web browser that supports the Secure Sockets Layer (SSL), such as Netscape Navigator 1.2 or later An active support license A named technical support contact Your user ID and password Whether or not you are a registered SupportPlus user: You may use Sybases Technical Information Library. Certication Reports are among the features documented at this site. 1. Point your Web browser to the Technical Information Library at the following URL: http://techinfo.sybase.com 2. In the Browse section, click on the Hot entry. 3. Click on the topic that interests you.

ConventionsFormatting SQL StatementsSQL is a free-form language: there are no rules about the number of words you can put on a line, or where you must break a line. However, for readability, all examples and syntax statements in this manual are formatted so that each clause of a statement begins on a new line. Clauses that have more than one part extend to additional lines, which are indented.

Sybase IQ Query Guide

xv

Conventions

Sybase IQ Version 11.2.x

SQL Syntax ConventionsThe conventions for syntax statements in this manual are as follows.Table 1: Syntax statement conventions Keycommand or COMMAND

DenitionCommand keywords, stored procedures, and function names are in Bold Courier in syntax statements and Bold Helvetica in text. Sybase IQ commands and functions are in UPPERCASE and Sybase SQL Sever commands and functions are in lowercase, although Sybase IQ and SQL Server allow all keywords to be in mixed case. Datatypes and system tables are in Bold Courier in syntax statements, and in italics in text. Sybase IQ datatypes are in UPPERCASE and SQL Server datatypes are in lowercase. Variables, or words that stand for names, numbers, or phrases that you ll in, are in italics. Curly braces designate options or groups of options that are repeated. Do not include braces in your option. Brackets mean the enclosed options are optional. Do not include brackets in your option. Parentheses are to be typed as part of the command. The vertical bar means you may select only one of the options shown. Ellipses indicate you can repeat the previous argument. Comma means you may choose more than one option, separating your choices with commas. Underlined words in syntax represent the default value. Comment delimeters in examples.

datatype or DATATYPE variable {}

[] () | ... , ____ /* */ or --

Syntax statements (displaying the syntax and all options for a command) are printed like this:SELECT column_name FROM table_name WHERE search_conditions

xvi

About This Book

Sybase IQ Version 11.2.x

Conventions

In syntax statements, keywords (commands) are in normal font and identiers are in lowercase; italics is used for user-supplied words. Examples showing the use of Sybase IQ commands are printed in the following font:SELECT * FROM publishers

Examples of output from the computer are printed like this:pub_id 0736 0877 1389 pub_name New Age Books Binnet & Hardley Algodata Infosystems city Boston Washington Berkeley state MA DC CA IQ_ROWID 1.000000 2.000000 3.000000

(3 rows affected) Note Sybase IQ is always case sensitive with respect to identiers. SQL Server may or may not be case sensitive, depending on the sort order installed on your SQL Server. Sybase IQ object names are case sensitive when used in conjunction with SQL Server, regardless of the sort order installed.

Case You can disregard case when you type Sybase IQ keywords:SELECT is the same as Select is the same as select.

However, this manual distinguishes keywords that Sybase IQ handles by making them uppercase, as opposed to keywords handled by SQL Server, which are in lowercase. Mandatory Options {You Must Choose At Least One} Curly Braces and Vertical Bars: Choose one and only one option.{die_on_your_feet | live_on_your_knees | live_on_your_feet}

Curly Braces and Commas: Choose one or more options. If you choose more than one, separate your choices with commas.{cash, check, credit}

Sybase IQ Query Guide

xvii

Conventions

Sybase IQ Version 11.2.x

Optional Options [You Dont Have to Choose Any] One Item in Square Brackets: You dont have to choose it.[anchovies]

Square Brackets and Vertical Bars: Choose none or only one.[beans | rice | sweet_potatoes]

Square Brackets and Commas: Choose none, one, or more than one option. If you choose more than one, separate your choices with commas.[extra_cheese, avocados, sour_cream]

Ellipsis: Do It Again (and Again)... An ellipsis (...) means that you can repeat the last unit as many times as you like. In this syntax statement, buy is a required keyword:buy thing = price [cash | check | credit] [{, thing = price [cash | check | credit]}... ]

You must buy at least one thing and give its price. You may choose a method of payment: one of the items enclosed in square brackets. You may also choose to buy additional things: as many of them as you like. For each thing you buy, give its name, its price, and (optionally) a method of payment.

Pathname Differences Between Windows NT and UNIXUNIX pathnames use the slash (/) character as the directory name separator, while Windows NT pathnames use the backslash (\) character. In addition, a fully qualied Windows NT pathname includes a device indicator (such as C:). Certain Sybase IQ commands (such as IQ CREATE INDEXSPACE) require a pathname parameter, which you should fully qualify. The following is an example of a fully qualied Windows NT pathname:C:\SYBASE\TEST.DB

This next example is a fully qualied UNIX pathname:/s1/usr/sybase/TEST.DB

If a relative pathname is specied in either example (such as just TEST.DB), then the absolute path is relative to the working directory

xviii

About This Book

Sybase IQ Version 11.2.x

If You Need Help

where Sybase IQ Open Server was started. See your Installation and Conguration Guide for more information. In the examples of this book, a distinction is made between the pathnames specied for UNIX and Windows NT. However, text references to pathnames (such as $SYBASE/bin) use only the slash (/) character to distinguish directories. For Windows NT, you should substitute the backslash (\) in these references unless indicated otherwise.

If You Need HelpHelp with your Sybase software is available in the form of SyBooks and AnswerBase CDs, and Sybase Technical Support. Each Sybase installation that has purchased a support contract has one or more designated people who are authorized to contact Sybase Technical Support. If you cannot resolve a problem using the manuals or online help, please have the designated person contact Sybase Technical Support or the Sybase subsidiary in your area.

Sybase IQ Query Guide

xix

If You Need Help

Sybase IQ Version 11.2.x

xx

About This Book

1Introduction

Getting Started

1.

This chapter provides background information you will need to execute queries using Sybase IQ (Interactive Query). It covers the following topics: Data Warehousing and Decision Support 1-1 About Sybase IQ 1-2 Connecting to Sybase IQ 1-5 Sybase IQ Commands and Conventions 1-8 Customizing Your Sybase IQ Session 1-13

Data Warehousing and Decision SupportDecision Support Systems (DSS) are used to analyze a business. They comprise a broad range of analytical applications, typically in the areas of sales and marketing, nance, and operations. Operational systems, on the other hand, are used daily to run the business. Decision support systems often contain large quantities of historical data and are used to support strategic business decision making. Data warehousing is the process of: Assembling information from a variety of operational, legacy, and external sources, at regular intervals Transforming the information into an integrated view of business activities Providing one or more DSS applications on the transformed data for business analysis Decision support analysis is becoming less batch-oriented and more interactive. Once data is accessible, more queries can be generated and decision making can be improved, so the new business market demands rapid response to queries. Sybase IQ supports this new interactive approach with the following features: More intelligent query processing, because it processes only the data needed to satisfy the query

Sybase IQ Query Guide

1-1

About Sybase IQ

Sybase IQ Version 11.2.x

Truly interactive, ad hoc query performance on a uniprocessor as well as parallel systems for multiple users Fully-exible schema support Efcient query execution without query-specic tuning by the System Administrator, under most circumstances

About Sybase IQSybase IQ is a server-based product that creates specialized indexes on either local or remote data sources, including at les. Sybase IQ then uses these indexes to resolve complex decision support queries rapidly without having to refer back to the original data source. Sybase IQ is specically designed to increase the speed of ad hoc decision support queries against large amounts of data. The fast performance of Sybase IQ on DSS queries complements the speed of the SQL Server databases for online transaction processing (OLTP). Sybase IQ can off-load DSS queries from operational databases in a mixed workload environment. Alternatively, in a pure data warehouse environment where data is periodically updated or added, Sybase IQ can be used as the sole data server or warehouse. Sybase IQ efciently supports multiple users and takes full advantage of kernel threads-based architectures for parallel index building and some query processing functions. All the major processes within the product, such as I/O, sorts and bitmap level operations, are multi-threaded and non-blocking so the operations can execute in parallel across as many processors as are available.

Architecture OverviewSybase IQ integrates transparently into your existing client/server environments. It resolves complex ad hoc queries without additional tuning and delivers more consistent interactive access to the data warehouse. Typically, Sybase IQ resides on the server between a front-end tool and a SQL Server database. You can also use Sybase IQ to speed up query resolution without directly populating a SQL Server database. Sybase IQ has an open architecture that enables indexing against other data sources. The source data for the warehouse, if it exists in formats other than SQL Server or at les, can be directly accessed

1-2

Getting Started

Sybase IQ Version 11.2.x

About Sybase IQ

through the Sybase Enterprise CONNECT product line, which includes OmniSQL Server and a large number of gateways. All information required to manage the Sybase IQ indexspaces (including its indexsets and indexes) resides in a SQL Server database and can be viewed as an extension of the SQL Server catalog for mixed applications. The product can be accessed through the Sybase DB-Library, Client-Library or ODBC Open Client APIs using ANSI-standard SQL. This integration gives the user full access to security and view functionality and a single point of administration in an environment where SQL Server already exists. In non-SQL Server environments (or pre-System 11 SQL Server), the data source, if it is a single database, is treated as an attached database and the schema, security and view information are duplicated within the SQL Server catalog. Figure 1-1 shows the Sybase IQ architecture.

Figure 1-1: Open architecture

Information about Sybase IQ index indexspaces (including their indexsets and indexspaces) is stored in the SQL Server catalog. You can then access data from: Sybase IQ indexes An underlying SQL Server database An earlier version (such as 4.9) of the SQL Server database An attached non-SQL Server database connected through OmniSQL Server Sybase IQ stores its indexes for a database in an object called an indexspace, which is stored external to SQL Server in the le system or on raw partitions (UNIX omly).The indexes for each database table are stored within the indexspace in Sybase IQ indexsets.

Sybase IQ Query Guide

1-3

About Sybase IQ

Sybase IQ Version 11.2.x

Note Because this guide is intended for users who are already familiar with Transact-SQL or other SQL dialects, it substitutes the term database for indexspace and the term table for indexset in SELECT syntax discussions. Other Sybase IQ documentation refers to indexspaces and indexsets to avoid confusing Sybase IQ objects with objects in the underlying database.

Once you have built your indexes on the data, you can resolve standard database queries through the Sybase IQ indexes. Your System Administrator will set up indexspaces and indexsets for you, so that you can query the Sybase IQ indexes with similar syntax to that you would use to query your tables in the source database. For queries it does not support, Sybase IQ can pass the query through to the attached database for resolution.

Documentation OverviewSybase IQ documentation is designed to help you create and manage an environment with Sybase IQ, as shown in the following table:Table 1-1: A map to Sybase IQ information To Learn AboutInstalling the software and Sybase IQ Open Server Creating and maintaining Sybase IQ objects, data, user accounts, and security Syntax and usage rules for all Sybase IQ commands and stored procedures Syntax for all Sybase IQ commands Syntax and rules for formulating queries with Sybase IQ

ReadSybase IQ Installation and Conguration Guide Sybase IQ Administration Guide Sybase IQ Language Reference Sybase IQ Quick Reference Sybase IQ Query Guide (this book)

All of these books, except Sybase IQ Quick Reference, include examples of commands and output. If you duplicate these commands on your system, the query results you see on your screen may not look exactly as they do in the manual. Thats because some of the examples have been reformatted (for example, the columns realigned) for visual clarity or to take up less space on the page. 1-4 Getting Started

Sybase IQ Version 11.2.x

Connecting to Sybase IQ

Connecting to Sybase IQMost users run Sybase IQ through a graphical front-end application that connects through Sybase IQ Open Server.

Connecting Through a Client ApplicationYou must connect to the Sybase IQ Open Server each time you run the client application. The method for connecting varies depending on the application being used. For most graphical front ends, you select the Sybase IQ Open Server from a list of available servers. The application prompts you for the username and password of the catalog server. See your System Administrator for this information.

Connecting Through isqlIf you do not connect through a graphical front end, you may connect through the stand-alone utility program isql. This utility lets you use SQL directly from the operating system level.isql has a command line interface but has no scrolling or editing capabilities. isql results are displayed lengthwise by row. When the row is longer than 80 characters, the line wraps, but you can change this by specifying the -w (column width) parameter. The default termination command is go.

To invoke isql, use the following syntax:isql [-J client_charset] [-l login_timeout] [-U username] [-P password] [-S IQopenservername] [-w columnwidth]

Table 1-2 lists the isql command line parameters commonly used with Sybase IQ.Table 1-2: isql command line parameters Parameter-J client_charset

DescriptionCharacter set to use if catalog server default is not us_english

StatusOptional. Not needed if $IQcharset environment variable is set.

Sybase IQ Query Guide

1-5

Connecting to Sybase IQ

Sybase IQ Version 11.2.x

Table 1-2: isql command line parameters (continued) Parameter -l login_timeout DescriptionMaximum number of seconds allowed when connecting before timing out. Defaults to 60. Username. Defaults to login name of person issuing command. Password (prompts if not supplied on command line). Sybase IQ Open Server name. Defaults to $DSQUERY. Sets the screen width for output. Defaults to width of 80 characters, which causes lines to wrap.

StatusOptional.

-U username -P password -S IQopenservername

Optional. Optional. Optional if $DSQUERY environment variable is set. Otherwise, mandatory. Optional.

-w columnwidth

For example, to establish a connection to Sybase IQ Open Server, type:isql -U sa -P ellingsworth -S SERV1GATE

You may omit all options. SQL Server assumes that -U is your operating system username and prompts you for a password. It also supplies the value of the DSQUERY environment variable as a parameter to the -S option. If your System Administrator has set DSQUERY properly, you may simply type the following to connect:isql password:

The password you enter does not appear on the screen. Instead, the isql utility returns the following prompt:1>

You can now start issuing SQL commands. The isql utility sends the commands to Sybase IQ, formatting the results and printing them as standard output. There is no maximum size for an isql statement. Terminate a command by entering the default command terminator go. Here is an example:1> 2> 3> 4> select * from authors where city = "Oakland" go

1-6

Getting Started

Sybase IQ Version 11.2.x

Connecting to Sybase IQ

To exit isql, type quit or exit on a line by itself. The quit and exit commands do not need a go terminator. Note The examples shown in the Sybase IQ documentation set do not include the isql line prompts (1>, 2>, and so on) or the command terminator (go), since your client tool may differ. However, each example assumes that a command terminator is used after each statement.

For more information about isql, see your SQL Server documentation.

Creating and Populating the IndexspaceTo create and populate your indexspace, you need certain privileges. These tasks, like that of dening appropriate indexes, are best left to the database administrator. The relevant commands, procedures, and security requirements are described in Sybase IQ Administration Guide.

Opening and Closing the IndexspaceYour database administrator may have assigned you a default indexspace to which you are automatically connected when you invoke Sybase IQ from the front-end application. If this is not the case, issue a USE command after connecting to Sybase IQ. The USE command opens both the attached database and corresponding indexspace. For example, this command opens the sales database and indexspace:USE sales

The Sybase System Administrator usually sets up your indexspace so that by default, this command attaches you to the indexspace in Read/Only mode. This lets multiple users access the same indexspace at the same time. To close the indexspace, issue an IQ CLOSE command, as follows:IQ CLOSE INDEXSPACE

Sybase IQ Query Guide

1-7

Sybase IQ Commands and Conventions

Sybase IQ Version 11.2.x

Note The IQ CLOSE command does not close the attached database. If you continue to issue SELECT statements after an IQ CLOSE, they will query the attached database instead of your indexspace.

Sybase IQ Commands and ConventionsThe following table lists all of the Sybase IQ commands and clauses. This guide describes only the subset of commands used for data retrieval. For complete command syntax and usage notes, see Sybase IQ Language Reference.Table 1-3: Sybase IQ SQL statements Command/TopicCASE expression

DescriptionConditional expression that can be used in IQ DELETE, IQ INSERT, or SELECT statements. The CASE expression allows you to determine one of many results based on a search condition or specic value you specify. Indicates the indexsets used by the query expression to produce a virtual table. The FROM clause is always required in a SELECT statement or query expression. Groups the output of a SELECT statement by one or more columns and returns a single row of information for each group. Restricts the groups you retrieve in a GROUP BY clause of a SELECT statement. Creates a new segment for an existing Sybase IQ indexspace across multiple operating system les to add more free space for indexspace. Adds or drops a column from an existing indexset. Backs up a Sybase IQ indexspace on either raw partitions (UNIX only) or operating system les. Closes the current indexspace without exiting from Sybase IQ session.

FROM clause

GROUP BY clause HAVING clause IQ ADD SEGMENT FOR database_name IQ ALTER INDEXSET FOR table_name IQ BACKUP IQ CLOSE INDEXSPACE

1-8

Getting Started

Sybase IQ Version 11.2.x

Sybase IQ Commands and Conventions

Table 1-3: Sybase IQ SQL statements (continued) Command/TopicIQ CREATE [UNIQUE] INDEX index_name ON table_name (column_name) indextype

DescriptionAdds an index of a given indextype to a column in an indexset. If the indexset is part of a joined indexset, steps above are also performed on the joined indexset. Only columns with Sybase IQ indexes may have data. If a column does not have a Sybase IQ index, Sybase IQ produces an error and passes the query off to an attached or associated database. Creates an indexset and denes its columns. Denes an indexspace and creates the rst segment. Creates a script that in turn can be used to create an indexspace, indexsets, columns, and indexes based on an existing underlying database. This script can be used as input to Sybase IQ through some front end tool (like isql). Denes a group of prejoined indexsets to improve the performance of queries against multiple indexsets in the same indexspace. Checks every block in the indexspace and saves the information in the current session until the next IQ DBCC CHECKDB command is issued. Deletes rows from an indexset. Deletes a column index. Deletes an indexset and its column indexes. Deletes an indexspace and all its contents. Deletes a joined indexset and its column indexes. Drops the last segment of a Sybase IQ indexspace. Adds new rows to the column indexes of an indexset. Inserts data into joined indexset one indexset at a time. Tells Sybase IQ to ignore next statement and pass it directly through to SQL Server for processing.

IQ CREATE INDEXSET FOR table_name IQ CREATE INDEXSPACE FOR database_name ... IQ CREATE INDEXSPACE TEMPLATE [FOR table_name]

IQ CREATE JOINED INDEXSET ...

IQ DBCC

IQ DELETE FROM INDEXSET FOR table_name IQ DROP INDEX index_name IQ DROP INDEXSET FOR table_name IQ DROP INDEXSPACE FOR database_name IQ DROP JOINED INDEXSET joined_indexset_name IQ DROP SEGMENT FOR database_name IQ INSERT INTO ... IQ INSERT INTO JOINED INDEXSET FOR ... IQ PASS ...

Sybase IQ Query Guide

1-9

Sybase IQ Commands and Conventions

Sybase IQ Version 11.2.x

Table 1-3: Sybase IQ SQL statements (continued) Command/TopicIQ RESTORE

DescriptionRestores a Sybase IQ indexspace and associated catalog information (full restore) or the indexspace only (partial restore). You can also use this command to display the header information for the indexspace without performing any restore operation. Sets Sybase IQ query processing options, session defaults, system-wide defaults. Displays information about the named indexset. Information includes column names, datatypes, column length, precision, scale, whether or not column allows NULLs, and so on. Displays information about the indexes on columns in a specied indexset. Information includes index names, types of indexes, column names, and uniqueness settings. Displays information about joined indexsets associated with the specied indexset. Information includes the name and join relationships of each joined indexset. Displays information about the indexspace you are using. Information includes the name of indexspace and a listing of the indexsets that are part of that indexspace. The indexset listing includes creation, last update time, and the number of columns in each indexset. Displays information about column indexes associated with Sybase IQ indexspace you are using. Information includes name and type of each index, indexset and columns from which they are derived, and other data such as uniqueness. Displays information about the joined indexsets associated with the Sybase IQ indexspace you are using. Information includes the name and join relationships of each joined indexset. Displays an alphabetized list of IQ SET command options and their values. Displays the size, in blocks, of the specied indexspace object. Object can be a column index, a joined indexset, or an indexset. Displays information about the indexspace that you are using. Sorts, by column, the result table returned by a SELECT statement. Retrieves rows and columns from tables in an indexspace. Some features like compute, text/image and other datatypes, the holdlock clause, and the for browse clause are not supported in this release. If any unsupported clauses are used, the entire query is passed through to SQL Server.

IQ SET ... IQ SHOW INDEXSET

IQ SHOW INDEXSET INDEXES

IQ SHOW INDEXSET JOINED INDEXSETS IQ SHOW INDEXSPACE | INDEXSETS

IQ SHOW INDEXSPACE INDEXES

IQ SHOW INDEXSPACE JOINED INDEXSETS IQ SHOW SET VALUES IQ SHOW SIZE ... IQ STATUS ORDER BY clause SELECT

1-10

Getting Started

Sybase IQ Version 11.2.x

Sybase IQ Commands and Conventions

Table 1-3: Sybase IQ SQL statements (continued) Command/TopicSHUTDOWN

DescriptionPasses the shutdown command to the SQL Server and exits Sybase IQ. This command can only be issued by a System Administrator. Species an indexspace with which you want to work. If no indexspace exists, but the underlying database does, Sybase IQ passes the command to SQL Server. Sets conditions for rows that are retrieved by a SELECT statement.

USE database_name

WHERE clause

This book also describes other SQL language elements that Sybase IQ recognizes: DatatypesUsed to specify data characteristics of columns. Functions (scalar)Used in a SELECT statement to manipulate or evaluate individual data items, called arguments, and return a result. The functions are: aggregate functions, SUBSTRING function, DATEPART function, and a datatype conversion function (CAST).

Passing Statements to the Data SourceAny query that contains columns that do not have Sybase IQ indexes on them, or that uses stored procedures or other proprietary SQL functions, is transparently passed to the attached database for resolution. Most of the Transact-SQL DDL is supported in Sybase IQ version 11.0. These commands are sent to SQL Server for interpretation and are not interpreted by Sybase IQ. For more information, see Sybase IQ Administration Guide.

IdentiersCertain rules govern the names, or identiers, you can assign to indexspaces and indexspace objects. The indexspace name is a SQL Server database name and is governed by the naming rules for SQL Server database names. Indexspace objects include indexsets, columns, indexes, etc. Here are the rules for Sybase IQ indexspace object names:

Sybase IQ Query Guide

1-11

Sybase IQ Commands and Conventions

Sybase IQ Version 11.2.x

The rst character of a Sybase IQ identier must be an alphabetic character as dened in the current character set in use on SQL Server or the _ (underscore) symbol. After the rst character, identiers can include characters declared as alphabetic, numeric, the symbols #, @, _, or money symbols such as $ (dollars), (yen) and (pound sterling). No embedded spaces are allowed in identiers, and none of the Transact-SQL reserved keywords can be used. The list of Transact-SQL reserved words can be found in the SQL Server Reference Manual. Sybase IQ does not accept environment variables as prexes in the lenames as some operating systems allow. For example, the following is not supported:IQ CREATE INDEXSPACE FOR foo, PATHNAME='$mygroup/pww' ...

With the following exceptions, naming is Transact-SQL compliant: Sybase IQ does not permit leading # characters in identiers. This is because, in Transact-SQL, # indicates a tempdb reference, which Sybase IQ does not support. Sybase IQ does not permit leading @ characters in identiers. In Transact-SQL, @ references a local variable, which Sybase IQ does not support. Sybase IQ does not permit function names to be used as column names. For example, if you specify a table with columns suser_id and suser_name, Sybase IQ will return a parser error. SQL Server correctly parses column names that are also function names. Sybase IQ is always case sensitive with respect to identiers. SQL Server may be case sensitive or case insensitive, depending on the server conguration. Do not rely on case insensitivity from Sybase IQ in conjunction with SQL Server. Sybase IQ supports a subset of SQL Server alias syntax. SQL Server supports this syntax, for downward compatibility:SELECT col1=col2 FROM TABLE1

SQL Server releases 10 and 11 and Sybase IQ support this syntax, which complies with SQL92:SELECT col1 AS col2 SYNTAX FOR COLUMN aliases

1-12

Getting Started

Sybase IQ Version 11.2.x

Customizing Your Sybase IQ Session

Qualifying Name SyntaxIn all syntax diagrams in this manual, indexset_name, joined_indexset_name, or index_name is also covered by:[[[indexspace].][owner].]indexset_name [[[indexspace].][owner].]joined_indexset_name [[[indexspace].][owner].]index_name

When referencing a column, you can uniquely identify it by qualifying it with the indexset name to which it belongs. You separate the indexset name and column name with a period. For example:indexset_name.column_name

orcustomer.cust_name

This syntax is SQL-92 compliant, except that Sybase IQ doesnt support delimited identiers, and SQL-92 doesnt support case sensitivity except within delimited identiers.

Customizing Your Sybase IQ SessionSybase IQ provides a number of query processing options that let you customize your session. To turn on these options, use the IQ SET command, a Sybase IQ extension to the SQL standard. The IQ SET command sets query processing options for Sybase IQ and/or SQL Server for the duration of the work session. You can even use it to set some options inside a trigger or stored procedure. Options that require system privileges are described in Sybase IQ Administration Guide. Syntax for the IQ SET command is as follows:[IQ] SET option value

Sybase IQ Query Guide

1-13

Customizing Your Sybase IQ Session

Sybase IQ Version 11.2.x

Table 1-4 describes each of the IQ SET options.Table 1-4: Sybase IQ SET options Keyword and ValueAGGREGATIONCUTOFF precision_# SES (PUBLIC), SVR (SA)

Value DescriptionSpecies at which precision level Sybase IQ uses a more efcient internal storage type to do calculations on SUM or AVG numeric expressions. For precisions 10 through 18, the risk of using this efcient storage type is the possibility of overow. Valid values for this option are 9 through 18. If it is unlikely that the aggregation of numerics with precision higher than 10 will result in an overow, you can set AGGREGATIONCUTOFF higher to make the calculation use the more efcient storage type. Otherwise, Sybase IQ will use a larger but slower storage type to avoid overow for precisions greater than 10 (to avoid overow at precision 10, change AGGREGATIONCUTOFF to 9). For internal use only. Aborts a query when an overow or divideby-zero error occurs during query execution. Two types of arithmetic errors are handled by two options, ARITH_OVERFLOW and NUMERIC_TRUNCATION. You can set each option independently or with a single IQ SET ARITHABORT statement. If Sybase IQ is present, only sets ARITHABORT in IQ, and ignores ARITH_OVERFLOW. If Sybase IQ is not present, sets ARITHABORT in both Sybase IQ and SQL Server, and passes ARITH_OVERFLOW to SQL Server, if present.

Default Value10

ANSINULL {ON | OFF} ARITHABORT {ON | OFF}

OFF OFF

1-14

Getting Started

Sybase IQ Version 11.2.x

Customizing Your Sybase IQ Session

Table 1-4: Sybase IQ SET options (continued) Keyword and ValueARITHIGNORE {ON | OFF}

Value DescriptionReturns NULL when an overow or divideby-zero error occurs during query execution. No warning message is displayed. ARITHIGNORE determines whether Sybase IQ prints a warning message if a query results in an arithmetic overow. If Sybase IQ is present, system only sets ARITHIGNORE in Sybase IQ, and ignores ARITH_OVERFLOW and NUMERIC_TRUNCATION. If Sybase IQ is not present, system sets ARITHIGNORE in both Sybase IQ and SQL Server, and passes ARITH_OVERFLOW and NUMERIC_TRUNCATION to SQL Server, if present.

Default ValueOFF

ARITH_OVERFLOW {ON | OFF}

ARITHIGNORE ARITH_OVERFLOW determines whether Sybase IQ displays a message after a divide-by-zero error or a loss of precision. ARITH_OVERFLOW OFF displays a warning message after these errors. ARITH_OVERFLOW ON suppresses warning messages after these errors. The ARITH_OVERFLOW keyword is optional and can be omitted without any effect.

OFF

ARITH_OVERFLOW {ON | OFF}

ARITHABORT ARITH_OVERFLOW ON rolls back entire transaction or batch in which error occurs. ARITHABORT ARITH_OVERFLOW OFF aborts statement that causes the error, but continues to process other statements in transaction or batch.

ON

INFOMESSAGES {ON | OFF}

Controls whether or not any Sybase IQ messages get sent to a user. This option is especially useful for front-end client applications that generate a dialog box for each message.

ON

Sybase IQ Query Guide

1-15

Customizing Your Sybase IQ Session

Sybase IQ Version 11.2.x

Table 1-4: Sybase IQ SET options (continued) Keyword and ValueIQ {ON | OFF | ONLY}

Value DescriptionIQ SET IQ determines where commands will be processed. If Sybase IQ is set ON, tries input as a Sybase IQ command and passes to SQL Server if it fails. If Sybase IQ is set OFF, passes input directly to SQL Server. If Sybase IQ is set ONLY, tries only as a Sybase IQ command.

Default ValueON

JOINOPTIMIZATION {ON | OFF}

Enables/disables optimization of join order. For more information, see Sybase IQ Administration Guide. Changes join order in ad hoc join queries to be left deep (with respect to the order in which tables appear in FROM clause). Controls whether or not the Sybase IQ Open Server log for each user is removed at the end of the session. Set this option ON to save log information for Technical Support. Limits command execution for the underlying SQL Server and/or Sybase IQ. (See description of IQ keyword earlier in this table.) When ON, the only commands that can execute are [IQ] SET NOEXEC, exit, and quit. Other commands are syntax checked, and have some limited semantic checking performed, but are not executed. When OFF, all commands are executed.

ON

JOINORDERLEFTDEEP {ON | OFF}

OFF

KEEPOPENIQLOG {ON | OFF}

OFF

NOEXEC {ON | OFF}

OFF

1-16

Getting Started

Sybase IQ Version 11.2.x

Customizing Your Sybase IQ Session

Table 1-4: Sybase IQ SET options (continued) Keyword and ValueNUMERIC_TRUNCATION {ON | OFF}

Value DescriptionSpecies behavior following a loss of scale by an exact numeric type during an implicit tape conversion. (When an explicit conversion results in a loss of scale, results are truncated without warning.) ARITHABORT NUMERIC_TRUNCATION ON aborts statement that causes the error, but continues to process other statements in transaction or batch. ARITHABORT NUMERIC_TRUNCATION OFF truncates query results and continues processing.

Default ValueON

ROWCOUNT #_of_rows

Stops query processing after specied number of rows are affected. To turn this option off, use IQ SET ROWCOUNT 0. Setting the ROWCOUNT option off or reducing the number of rows limits the output of IQ SHOW commands and the IQ STATUS command (which requires at least 122 rows). Controls whether or not Sybase IQ displays its IQ_ROWID column for a query. Previous releases implicitly displayed this unique identier column with a SELECT * unless an underlying table contained other nonSybase IQ indexed columns (which forces the query to pass through to SQL Server). This option does not affect any explicit references to the IQ_ROWID column in a SELECT command.

0 (returns all rows)

SHOWIQROWID {ON | OFF} SES (PUBLIC), SVR (SA)

OFF

For example, the following statement means that, for each IQ INSERT, IQ DELETE, or SELECT command, Sybase IQ stops processing the query after it affects the rst ten rows.IQ SET ROWCOUNT 10

Sybase IQ accepts only one option per SET command. If you specify more than one option, Sybase IQ returns an error. If neither ARITHABORT nor ARITHIGNORE is set, Sybase IQ returns NULL and prints a warning message after the query executes. See Chapter 4, Retrieving Data from Multiple Tables, for information about the join optimization options.

Sybase IQ Query Guide

1-17

Customizing Your Sybase IQ Session

Sybase IQ Version 11.2.x

For information about other SET options not described here, see Sybase IQ Administration Guide. Now that you know how to invoke Sybase IQ and customize your session, you are ready to begin formulating queries.

1-18

Getting Started

2Introduction

Using Queries

2.

This chapter provides details on data retrieval concepts and implementations specic to Sybase IQ. It covers the following topics: Overview of Queries 2-1 Datatypes for Columns 2-2 Retrieving Data from Tables 2-8

Overview of QueriesQueries allow you to extract data from your database and display it. In general, queries are statements that retrieve data. For example, the question Which people named Brown work for this company? is a simple query that may be expressed as a SQL statement like this:SELECT first_name, last_name FROM employees WHERE last_name = Brown

This command returns the rst and last name of each Brown who works for your company. The Sybase IQ SELECT statement is a subset of the standard SQL select statement. This chapter provides syntax and usage details in a later section. Sybase IQ supports queries that are part of applications as well as ad hoc queries of arbitrary complexity.

Sybase IQ QueriesSybase IQ uses its indexes to resolve queries. The appropriate indexes must exist and contain data before you can perform queries. Your System Administrator can create and populate these indexes for you. Sybase IQ does not process queries on columns without Sybase IQ indexes or queries that use stored procedures or other proprietary SQL functions. Such queries are transparently passed to the original data source for resolution and all results come from the server.

Sybase IQ Query Guide

2-1

Datatypes for Columns

Sybase IQ Version 11.2.x

In order for Sybase IQ to resolve queries: The tables and columns referenced in the query must have the same names and matching datatypes as their corresponding tables and columns in the underlying database. The underlying database created by your System Administrator must have the same name as your Sybase IQ indexspace. If you plan to use an attached database with a different name from your indexspace, your System Administrator must have dened this attached database for you before you start Sybase IQ. Note When you reference a system table, the query will always be directed to the SQL Server containing the catalog information. This means it will not be possible to query the system tables/catalog on SQL Server release 4.9. For more information about queries passed through to SQL Server, see Sybase IQ Language Reference.

If you query a column that contains no data, Sybase IQ does not issue an error. It simply reports that the query returns 0 rows of data.

Query SecurityYou can query Sybase IQ indexes if you are the System Administrator, Database Owner, or have been granted SELECT permission to the corresponding underlying database table or column. You dont need any other special privilege. (Note that privileges can also be revoked by the System Administrator, Database Owner, or object owner. Sybase IQ does a privilege check each time a user issues the SELECT command). For complete information about security, see Sybase IQ Administration Guide.

Datatypes for ColumnsDatatypes specify data characteristics of columns in a table. The datatype determines the kind of data (such as characters, date, integer) that a column can store. Before you can issue any queries, your System Administrator must dene columns and their datatypes. For information about dening columns, see Sybase IQ Administration Guide.

2-2

Using Queries

Sybase IQ Version 11.2.x

Datatypes for Columns

This section contains tables that: Describe the Sybase IQ formats for character, numeric, date, and datetime data Explain which Sybase IQ datatypes are compatible with each other Explain which Sybase IQ datatypes are compatible with SQL Server datatypes Here are the valid Sybase IQ datatypes.Table 2-1: Sybase IQ datatypes Datatypes by Category CharacterCHAR (width_in_bytes) V ARCHAR (max_col_width) 1 to 255 characters 1 to 255 characters n/a n/a width_in_bytes Usually actual entry length

Range

Maximum Precision

Bytes of Storage

Exact numericDECIMAL [(precision [,scale])] Synonym: DEC INTEGER [(precision [,scale])] Synonym: INT NUMERIC [(precision [,scale])] SMALLINT [(precision [,scale])] TINYINT [(precision [,scale])] UINT [(precision [,scale])] Signed numeric values between: -1038 + 1 and 1038 - 1, inclusive Signed integer values between: -231 (-2,147,483,648) & 231 - 1 (2,147,483,647), inclusive Same as DECIMAL Signed integer values between -215 (-32,768) and 215 - 1 (32,767), inclusive Non-negative integers between 0 and 255, inclusive. Non-negative, unsigned integer values between 0 and 232 - 1 (4,294,967,295), inclusive 38 Varies

10

>= 4 bytes

38 5

Varies >= 2 bytes

3 10

>= 1 byte >= 4 bytes

Approximate numericFLOAT (precision) Machine-dependent 16 >= 8 bytes

Sybase IQ Query Guide

2-3

Datatypes for Columns

Sybase IQ Version 11.2.x

Table 2-1: Sybase IQ datatypes (continued) Datatypes by CategoryREAL (precision)

RangeMachine-dependent

Maximum Precision7

Bytes of Storage>= 4 bytes

Date/timeDATE DATETIME January 1, 1753 to December 31, 9999 January 1, 1753 to December 31, 9999 and time based on 24-hour clock accurate to within one 10,000th of a second n/a n/a 4 bytes 8 bytes

The preceding table shows certain syntax conventions that use precision and scale. Precision and scale can be a positive integer or zero. Sybase IQ treats each combination of precision and scale as a distinct datatype. For example, NUMERIC(10,0) and NUMERIC(5,0) are two separate datatypes. The precision and scale values determine the range of values that can be stored in exact or approximate numeric datatypes. Precision indicates the number of decimal digits that can be stored in the column. It includes all digits to the left and right of the decimal point. The maximum number for precision varies by datatype. The number is determined by how many decimal digits can be presented, given the bits available plus space for the positive or negative sign and a decimal point. Scale indicates the number of decimal digits that can be stored to the right of the decimal point. The scale must be less than or equal to the precision, unless you specify the default precision using 0 (zero). For example, NUMERIC(0,2). Scale applies only to exact numeric datatypes. Note Currently, Sybase IQ integer datatypes optionally allow precision and scale so that they can be compatible with other SQL Server datatypes that may require them, such as money. However, such scaled integers may not be allowed in a future Sybase IQ release; use NUMERIC or DECIMAL instead.

2-4

Using Queries

Sybase IQ Version 11.2.x

Datatypes for Columns

General Datatype RulesHere are some general rules for working with datatypes: If you insert data from an attached database table and the columns are equivalent, then Sybase IQ appropriately interprets and converts the data automatically. When specifying a query on a column, if the column has scale, specify the query value with a decimal point. Datatype storage size is always the most efcient number for the platform being used. Filler characters separate the date/time elements. Only one ller character is needed between each element. Use any character as a ller character, including blanks. (The examples in this book use a combination of - (hyphen), blank space, and : (colon).)

NULLsThe NULL value marks columns that may contain an unknown value. This is true for a column in both single table query and a joined table query. This is different from having a value of blank or 0; NULL has no value.

Dening Literals and E NotationSybase IQ follows Transact-SQL rules when dening the datatypes for literals, as follows: All character literals are typed as V ARCHAR, allowing them to be enclosed within (single quotes) or (double quotes). character literals cannot span lines. All numeric literals containing the E notation are typed as FLOAT. All numeric literals without a decimal point or E notation and between 231-1 and -231 are typed as INTEGER. All other numeric literals are typed as NUMERIC. Sybase IQ allows numeric literals up to 77 digits, but it can only store numeric values of up to 38 digits (the maximum precision of the NUMERIC and DECIMAL datatypes). Sybase IQ accepts the following syntax for E notation literals:

Sybase IQ Query Guide

2-5

Datatypes for Columns

Sybase IQ Version 11.2.x

[{+ | -}]decimal-sequence[{E | e}][{+ | -}]digits

decimal-sequence = {digits | .digits | digits. | digits.digits}

Some valid examples are:3.e23 +6.02E+0023 3e-23 -.2E23 .2e0

Some invalid examples are:.e23 2E. +6.023e E -2.0e.45

Datatype of Mixed-Mode ExpressionsWhen you perform comparisons or mixed-mode arithmetic on values with different datatypes, Sybase IQ must determine the datatype and precision of the result. In general, it follows the hierarchy rules established by Transact-SQL to determine if one or both of the values must be promoted before the comparison or arithmetic operation can be completed. The following chart denes the hierarchy for the exact and approximate numeric types in Sybase IQ:

Figure 2-1:

Sybase IQ datatype hierarchy

This datatype hierarchy determines the results of computations using values of different datatypes. In general, the result value is assigned the datatype that is closest to the top of the list in Figure 21. For example, if a SMALLINT column of a table is multiplied by a DECIMAL column of a table, the resulting datatype is a DECIMAL:SMALLINT(qty) * DECIMAL(price) = DECIMAL

However, the exception is the REAL datatype. Sybase IQ converts any operation involving the REAL datatype with another datatype to the FLOAT datatype, which has a higher possible precision. Also according to the hierarchy described above, when approximate numeric types are involved in a mixed type expression with an exact numeric datatype, the result is always the approximate numeric datatype FLOAT. This may result in a possible loss of precision that will not produce an error.

2-6

Using Queries

Sybase IQ Version 11.2.x

Datatypes for Columns

Matching DatatypesThe following table shows implicit and explicit conversions that Sybase IQ supports in queries.

Figure 2-2: Explicit, implicit, and unsupported datatype conversions

Implicit and Explicit ConversionsThe following table indicates which Sybase IQ datatypes are compatible with SQL Server datatypes.

Figure 2-3: Data from SQL Server to Sybase IQ

These SQL Server datatypes are not supported by Sybase IQ in this release and, therefore, are not part of the chart: nchar, nvarchar, text, binary, varbinary, image and timestamp. Here are some general rules regarding which Sybase IQ datatypes are compatible with SQL Server datatypes: Sybase IQ character string types accept any SQL Server character string type. Sybase IQ exact numeric types accept any SQL Server number types. However, if the Sybase IQ datatype holds a smaller

Sybase IQ Query Guide

2-7

Retrieving Data from Tables

Sybase IQ Version 11.2.x

amount of data than the SQL Server type, the value converts to a NULL (for example, when inserting data from the underlying database into indexsets). Sybase IQ date/time types accept any SQL Server date/time types. Sybase IQ NATIVE type is compatible with all SQL Server datatypes. However, you cannot create a Sybase IQ index on a NATIVE column and therefore cannot store data in that column.

Retrieving Data from TablesThis section discusses the use of query expressions to retrieve data from tables. For each query component, this section describes: Syntax Usage rules Compliance with Transact-SQL and SQL-92

Query ExpressionsQueries are composed of a query expression and associated clauses. You can use query expressions for selections, which retrieve a subset of the rows in one or more tables, and for projections, which retrieve a subset of the columns in one or more tables. The number of columns in a table is referred to as its degree and the number of rows as its cardinality. The syntax for a query expression looks like this:{query_expression | (SELECT_statement)} [UNION [ALL] {query_expression | (SELECT_statement)}]... [ORDER BY clause]

A query expression contains a SELECT statement. It may also contain one or more UNION operations, which combine the output from one query expression with the output from another query expression into a single result table. The SELECT statement species the columns you want to retrieve. The FROM clause species the tables that contain the columns. The WHERE clause species which rows in the tables you want to nd. The remaining clauses rene the data retrieved. Each clause is described later in this section. 2-8 Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

You can include query expressions in IQ INSERT statements, which are described in Sybase IQ Language Reference. Here is an example of the simplest form of a query expression:SELECT select_list FROM table_list WHERE search_conditions

The SELECT StatementThe Sybase IQ SELECT statement species the columns you want to retrieve. It is a subset of the standard SQL select statement, and has the following syntax:SELECT [ALL | DISTINCT] select_list FROM clause [WHERE clause] [GROUP BY clause] [HAVING clause] [ORDER BY clause] Note See Sybase IQ Language Reference for more specic information about the SELECT statement.

A simple statement:SELECT column_name FROM table_name

returns all data from the specied indexed column. Before issuing a SELECT statement, you must issue a USE command for an indexspace to which you have Read access.

Qualifying NamesIf a SELECT statement references columns from multiple tables and two or more of the tables have a column name in common, qualify all references to the columns with the appropriate table names to avoid ambiguity. To do this, specify the table name before the column name and separate the two with a period. For example:SELECT table1.col1, table2.col1, table3.col2

Sybase IQ Query Guide

2-9

Retrieving Data from Tables

Sybase IQ Version 11.2.x

You can also qualify the table name with the owner name or database name. A name used to identify a database object, such as a table name or column name, is called an identier. You can dene correlation names for tables in the FROM clause and use those names instead of the table name to qualify the column name. A correlation name is a substitute name to be used in place of the table name. Correlation names are particularly useful if the table name is long or if your SELECT statement needs to specify the same table several times. If you do dene a correlation name in the FROM clause, you must use those names throughout the SELECT statement, even in earlier clauses. In the following example, the correlation name t stands for the table titles:SELECT t.pub_id FROM titles AS t WHERE pubdate < '1995-01-01' pub_id -----1389 1389 0736 1389 0877 0877 1389 1389 0877 0736 0736 0736 0736 0877 0877 0877 (16 rows affected)

To avoid unexpected results, specify the Sybase IQ columns by name in all SELECT statements.

2-10

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

Selecting Data from Multiple TablesYou can retrieve data from multiple tables in a single SELECT statement if the tables are joined together in that statement. Tables in associated main and private indexspaces (as specied in sysIQ_logins) may be joined in any statement that supports ad hoc joins (including the SELECT statement and the INSERT...SELECT statement). Note You must create and preallocate a private indexspace with the IQ CREATE INDEXSPACE command and associate it with the main indexspace in sysIQ_logins using the sp_IQAddLogin stored procedure.

As with a standard SQL join, a Sybase IQ join combines rows from two or more tables. Each combination is based on the join condition between columns specied in the WHERE clause. Chapter 4, Retrieving Data from Multiple Tables, describes joins in detail. Compliance with Transact-SQL and SQL-92 The SELECT command used in Sybase IQ is a subset of the SQL-92 standard select command, except for the following unsupported features: - Sybase IQ does not support the SQL-92 join operation keywords inner join, left outer join and right outer join. Sybase IQ supports Transact-SQL outer join syntax and semantics. - Restrictions on SELECT statements in subqueries, as described in Using Subqueries on page 3-1. - Sybase IQ does not support except [all], intersect [all], and corresponding clauses in query expressions. - SQL-92 row value constructors. Row value constructors are parenthesized lists of column values that let you manipulate rows of data at a time. For example:WHERE (COL1, COL2, COL3) = (COL4, COL5, COL6)

In Sybase IQ, you need to use the following syntax to perform such a query:WHERE COL1 = COL4 AND COL2 = COL5 AND COL3 = COL6

Sybase IQ Query Guide

2-11

Retrieving Data from Tables

Sybase IQ Version 11.2.x

The Sybase IQ SELECT command supports the same syntax as the Transact-SQL select command, except for the following unsupported features: - compute clause - holdlock clause - for browse option - text/image datatypes - Transact-SQL extensions to the group by and having clauses

The FROM ClauseThe FROM clause species the tables from which you want to get data. The table expression in the FROM clause includes a table name, for which you may specify a correlation name. The FROM clause is always required in a SELECT statement. Here is an example that retrieves data from the au_lname column in the authors table:SELECT au_lname FROM authors au_lname ----------------------------------------White Green Carson O'Leary Straight Smith Bennet Dull Gringlesby Locksley Greene Blotchet-Halls Yokomoto del Castillo DeFrance

2-12

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

Stringer MacFeather Karsen Panteley Hunter McBadden Ringer Ringer (23 rows affected)

The FROM clause may contain more than one table reference. For example:IQ SET ROWCOUNT 23 SELECT titles.pubdate, publishers.pub_name FROM titles, publishers pubdate ---------------------Jun 12 1986 12:00AM Jun 12 1986 12:00AM Jun 12 1986 12:00AM Jun 9 1988 12:00AM Jun 9 1988 12:00AM Jun 9 1988 12:00AM Jun 30 1985 12:00AM Jun 30 1985 12:00AM Jun 30 1985 12:00AM Jun 22 1987 12:00AM Jun 22 1987 12:00AM Jun 22 1987 12:00AM Jun 9 1989 12:00AM Jun 9 1989 12:00AM Jun 9 1989 12:00AM Jun 18 1985 12:00AM Jun 18 1985 12:00AM Jun 18 1985 12:00AM Feb 20 1997 5:03PM Feb 20 1997 5:03PM Feb 20 1997 5:03PM Jun 30 1986 12:00AM Jun 30 1986 12:00AM (23 rows affected) pub_name ----------------------New Age Books Binnet & Hardley Algodata Infosystems New Age Books Binnet & Hardley Algodata Infosystems New Age Books Binnet & Hardley Algodata Infosystems New Age Books Binnet & Hardley Algodata Infosystems New Age Books Binnet & Hardley Algodata Infosystems New Age Books Binnet & Hardley Algodata Infosystems New Age Books Binnet & Hardley Algodata Infosystems New Age Books Binnet & Hardley

You can reference a maximum of 16 tables in a FROM clause. This total includes each of multiple references to the same table in a self-join.

Sybase IQ Query Guide

2-13

Retrieving Data from Tables

Sybase IQ Version 11.2.x

For information about self-joins, see Chapter 4, Retrieving Data from Multiple Tables.

The WHERE ClauseThe WHERE clause in a SELECT statement species search conditions for the data you want to display. If the WHERE clause is omitted, all table rows qualify for the selection. A WHERE clause consists of one or more search conditions (predicates) connected by the logical operators: AND, OR, and NOT. The following example shows a SELECT statement with a single search condition in the WHERE clause. The statement retrieves the rows from the authors table for authors who live in California, and projects the values for these rows for the au_fname, au_lname, and au_id columns:SELECT au_fname, au_lname, au_id FROM authors WHERE state = 'CA' au_fname -------------Johnson Marjorie Cheryl Michael Dick Abraham Ann Burt Chastity Akiko Dirk Stearns Livia Sheryl Heather (15 rows affected) au_lname ------------------White Green Carson O'Leary Straight Bennet Dull Gringlesby Locksley Yokomoto Stringer MacFeather Karsen Hunter McBadden au_id -----------172-32-1176 213-46-8915 238-95-7766 267-41-2394 274-80-9391 409-56-7008 427-17-2319 472-27-2349 486-29-1786 672-71-3249 724-08-9931 724-80-9391 756-30-7391 846-92-7186 893-72-1158

Search conditions are described in Search Conditions on page 2-22. The WHERE clause can include column names; constants; logical operators; comparison operators; the predicates LIKE, IS NULL, BETWEEN, IN, and EXISTS; subqueries, join predicates, and nonaggregate functions.

2-14

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

WHERE clause qualiers are shown in Table 2-2. Table 2-2: WHERE clause qualiers QualiersComparison operators Ranges Lists Character matches Unknown values Logical operators State conditions Some outer join specications

Examples(=,,etc.) BETWEEN, NOT BETWEEN IN, NOT IN LIKE, NOT LIKE IS NULL, IS NOT NULL AND, OR, NOT EXISTS, NOT EXISTS (=*, *=) See Chapter 4, Retrieving Data from Multiple Tables, for details

You must enclose character strings in quotation marks when you input or search for them. The following WHERE clause uses two search conditions to nd all authors with surnames that begin with W and who live in California:SELECT au_id, au_lname FROM authors WHERE state = "CA" AND au_lname LIKE "W%" au_id ----------172-32-1176 au_lname -----------------------------------White

(1 row affected)

To enable you to retrieve data from multiple tables, the WHERE search condition can include join predicates. You can connect join predicates and the additional search criteria with the keyword AND, as follows:IQ SET ROWCOUNT 23 SELECT title, total_sales, qty FROM titles, salesdetail WHERE titles.title_id = salesdetail.title_id AND (discount < 70 OR qty > 30)

Sybase IQ Query Guide

2-15

Retrieving Data from Tables

Sybase IQ Version 11.2.x

title -----------------------------------Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Sushi,Anyone? Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Sushi,Anyone? Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Prolonged Data Deprivation: Four Case Studies Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Life Without Fear Life Without Fear Life Without Fear The Gourmet Microwave But Is It User Friendly? You Can Combat Computer Stress! The Busy Executive's Database Guide Straight Talk About Computers Emotional Security: A New Algorithm Sushi, Anyone? The Busy Executive's Database Guide But Is It User Friendly? The Busy Executive's Database Guide Straight Talk About Computers Emotional Security: A New Algorithm But Is It User Friendly? (23 rows affected)

total_sales ----------375 4095 375 4095 375 4072 375 111 111 111 22246 8780 18722 4095 4095 3336 4095 4095 8780 4095 4095 3336 8780

qty ---75 75 50 80 85 90 40 30 50 31 69 1000 500 200 150 125 1000 1000 750 200 100 200 300

Join indexes are not required, but can speed queries. For more information about joins, see Chapter 4, Retrieving Data from Multiple Tables. Here are a few rules for using WHERE in Sybase IQ: Expressions in a WHERE clause cannot include an aggregate function Subqueries in a WHERE clause can only retrieve a single row, unless it appears in an IN or EXISTS predicate Expressions used in the WHERE or HAVING clause must be join compatible with items in subquery select lists In this release, you can only use a subquery inside WHERE and/or HAVING clauses

2-16

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

Compliance with Transact-SQL and SQL-92 The WHERE clause used in Sybase IQ supports the same syntax as the SQL-92 standard WHERE clause, except for the following unsupported features: - SQL-92 row value constructors. - Sybase IQ does not support some, any, or all, but does supportEXISTS.

- Sybase IQ does not support match, is true, is false, or is unknown predicates, but does support IS NULL. - Subqueries are not supported in certain areas. Support is described in Using Subqueries on page 3-1. - Predicates do not support expressions in the IN clause. For more information, see IN on page 2-28. The Sybase IQ SELECT command supports the same syntax and semantics as the Transact-SQL select command, except for the following: - Subqueries can only retrieve a single row, to comply with the SQL-92 standard, except in IN and EXISTS subqueries. - LIKE does not support the Transact-SQL extensions to treatment of blanks with respect to wildcards, extended regular expression support, or the Transact-SQL extension to search for DATETIME values. The Sybase IQ LIKE predicate is SQL-92 compliant.

The GROUP BY ClauseGROUP BY species the groups into which the result table is divided and returns a single row of information for each group. You can group by a single column or a list of columns. Aggregate functions in select lists always operate on groups. If there is no GROUP BY clause, a single group is returned. (For more information about aggregate functions, see Chapter 3, Using Subqueries and Functions.)

Here is an example of the GROUP BY clause in a query that counts the number of authors in each state:SELECT state, COUNT(*) FROM authors GROUP BY state

Sybase IQ Query Guide

2-17

Retrieving Data from Tables

Sybase IQ Version 11.2.x

state ----CA IN KS MD MI OR TN UT

COUNT(*) --------15.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 2.000000

(8