0% found this document useful (2 votes)
1K views

Iq Query

Information in this publication pertains to Sybase IQ Version 11.2.x of the database management software. The software described herein is furnished under a license agreement. It may be used or copied only in accordance with the terms of that agreement.

Uploaded by

Shyam Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (2 votes)
1K views

Iq Query

Information in this publication pertains to Sybase IQ Version 11.2.x of the database management software. The software described herein is furnished under a license agreement. It may be used or copied only in accordance with the terms of that agreement.

Uploaded by

Shyam Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 172

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 Orders
To 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 Trademarks
Sybase, 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 Rights
Use, 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 Contents
About This Book
Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Started
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Queries
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1

Sybase IQ Query Guide

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 Functions


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Tables


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Figures
Figure 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

List of Figures

List of Tables
Table 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 Book


The Sybase IQ Query Guide is a guide to data retrieval using Sybase IQ.

Audience
This 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 Book


This 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 Documents
Other 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 Information


Use 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 Web


The 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.

Conventions
Formatting SQL Statements
SQL 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 Conventions


The conventions for syntax statements in this manual are as follows.
Table 1: Syntax statement conventions Key
command or COMMAND

Denition
Command 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 UNIX


UNIX 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 Help


Help 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

1
Introduction

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 Support


Decision 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 IQ
Sybase 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 Overview
Sybase 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 Overview
Sybase 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 About
Installing 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

Read
Sybase 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 IQ
Most users run Sybase IQ through a graphical front-end application that connects through Sybase IQ Open Server.

Connecting Through a Client Application


You 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 isql


If 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

Description
Character set to use if catalog server default is not us_english

Status
Optional. 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 Description
Maximum 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.

Status
Optional.

-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 Indexspace


To 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 Indexspace


Your 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 Conventions


The 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/Topic
CASE expression

Description
Conditional 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/Topic


IQ CREATE [UNIQUE] INDEX index_name ON table_name (column_name) indextype

Description
Adds 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/Topic


IQ RESTORE

Description
Restores 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/Topic


SHUTDOWN

Description
Passes 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 Source


Any 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.

Identiers
Certain 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 Syntax


In 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

or
customer.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 Session


Sybase 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 Value
AGGREGATIONCUTOFF precision_# SES (PUBLIC), SVR (SA)

Value Description
Species 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 Value
10

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 Value


ARITHIGNORE {ON | OFF}

Value Description
Returns 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 Value
OFF

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 Value


IQ {ON | OFF | ONLY}

Value Description
IQ 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 Value
ON

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 Value


NUMERIC_TRUNCATION {ON | OFF}

Value Description
Species 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 Value
ON

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

2
Introduction

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 Queries
Queries 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 Queries
Sybase 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 Security
You 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 Columns


Datatypes 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 Character
CHAR (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 numeric
DECIMAL [(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 numeric
FLOAT (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 Category


REAL (precision)

Range
Machine-dependent

Maximum Precision
7

Bytes of Storage
>= 4 bytes

Date/time
DATE 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 Rules


Here 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).)

NULLs
The 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 Notation


Sybase 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 Expressions


When 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 Datatypes
The 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 Conversions


The 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 Tables


This 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 Expressions
Queries 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 Statement


The 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 Names
If 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 Tables


You 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 Clause


The 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 Clause


The 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 Qualiers
Comparison 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 support
EXISTS.

- 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 Clause


GROUP 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 rows affected)

The example below joins the salesdetail table to the titles table by title_id. It then groups the results according to stor_id so that one group summarizes all the rows for store 5023, another groups all the rows for store 6380, and so on, and shows the sum of all the titles each store has purchased.
SELECT salesdetail.stor_id, SUM(titles.price) FROM salesdetail, titles WHERE titles.title_id = salesdetail.title_id GROUP BY salesdetail.stor_id stor_id ------7067 5023 7066 8042 6380 7896 7131 SUM(price) ----------163.690000 662.500000 115.800000 238.550000 92.830000 97.730000 108.790000

(7 rows affected)

Here are a few rules for using GROUP BY: The GROUP BY clause usually includes column names, even column names that are not in the select list. Expressions are not allowed in GROUP BY clause except for the DATEPART function. With GROUP BY, NULLs are considered equal and are treated as a single group. NULL values for a column name are grouped together. Ungrouped references in the select list of a statement with GROUP BY are invalid in SQL-92. Sybase IQ allows non-aggregate,

2-18

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

ungrouped column references, but has different semantics for them than Transact-SQL. For example, in the following statement, Transact-SQL extends the ANSI standard by allowing the output to include the title_id column, which is not a grouped column:
IQ PASS select type, title_id, avg(price), avg(advance) from titles group by type
type -----------business business business business mod_cook mod_cook UNDECIDED popular_comp popular_comp popular_comp psychology psychology psychology psychology psychology trad_cook trad_cook trad_cook title_id --------BU1032 BU1111 BU2075 BU7832 MC2222 MC3021 MC3026 PC1035 PC8888 PC9999 PS1372 PS2091 PS2106 PS3333 PS7777 TC3218 TC4203 TC7777 ------------------------ -------------------13.73 6,281.25 13.73 6,281.25 13.73 6,281.25 13.73 6,281.25 11.49 7,500.00 11.49 7,500.00 NULL NULL 21.48 7,500.00 21.48 7,500.00 21.48 7,500.00 13.50 4,255.00 13.50 4,255.00 13.50 4,255.00 13.50 4,255.00 13.50 4,255.00 15.96 6,333.33 15.96 6,333.33 15.96 6,333.33

(18 rows affected)

Transact-SQL returns the data from the title_id column of each row. Sybase IQ also allows title_id, but returns different output for it:
SELECT type, title_id, avg(price), avg(advance) FROM titles GROUP BY type type ---------UNDECIDED business mod_cook popular_comp psychology trad_cook title_id --------MC3026 BU1032 MC2222 PC1035 PS1372 TC3218 AVG(price) -----------NULL 13.730000 11.490000 21.475000 13.504000 15.963333 AVG(advance) -----------NULL 6281.250000 7500.000000 7500.000000 4255.000000 6333.333333

(6 rows affected)

Sybase IQ Query Guide

2-19

Retrieving Data from Tables

Sybase IQ Version 11.2.x

Sybase IQ returns the data from the title_id column of an arbitrary row.
Note If you group on multiple columns in a GROUP BY clause, list the columns in descending order by number of unique values. This changes the output of the GROUP BY, but may improve query performance.

Compliance with Transact-SQL and SQL-92 The GROUP BY clause used in Sybase IQ complies with the SQL-92 standard GROUP BY clause, except for the following: - Sybase IQ does not support the collate clause - Sybase IQ does not support ungrouped reference semantics Sybase IQ does not support Transact-SQL extended group by semantics. Sybase IQ does not support the group by [all] Transact-SQL extension. Unlike Transact-SQL, a Sybase IQ query with GROUP BY returns one row per group. This complies with the SQL-92 standard.

The HAVING Clause


The HAVING clause lters the groups you retrieve in the GROUP BY clause based on the specied search condition. This is similar to the way the WHERE clause restricts the rows you retrieve with SELECT. The following example shows the average price of all titles each store has purchased, excluding stores whose lowest-priced product is less than $10.00.
SELECT salesdetail.ord_num, AVG(titles.price) FROM salesdetail, titles WHERE salesdetail.title_id = titles.title_id GROUP BY salesdetail.ord_num HAVING MIN(titles.price) > 10.00

2-20

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

ord_num ------------------GH-542-NAD-713-9F9 13-J-9 BA52498 ZZ-999-ZZZ-999-0A0 Asoap432 (5 rows affected)

AVG(price) ---------18.296667 15.970000 19.990000 18.382500 15.963333

Here are a few rules for using HAVING: Column references in the HAVING clause must either be aggregate functions or be grouped or be an outer reference. HAVING operates on a group of rows and WHERE operates on a single row. Unlike the WHERE clause, the HAVING clause can include aggregate functions and cannot include join predicates. ]In queries that process hundreds of thousands of groups, the HAVING clause degrades performance signicantly. This problem may affect front-end clients. Compliance with Transact-SQL and SQL-92 The Sybase IQ HAVING clause complies with the SQL-92 standard, except for the following: - Sybase IQ does not support SQL-92 row value constructors - Sybase IQ does not support some, any, or all, but does support
EXISTS

- Sybase IQ does not support match, is true, is false, or is unknown conditions, but does support IS NULL The Sybase IQ HAVING clause differs from the Transact-SQL having clause as follows: - The LIKE predicate in Sybase IQ does not support the TransactSQL extensions to treatment of blanks with respect to wildcards, and extended regular expression support or the Transact-SQL extension to search for DATETIME values. The Sybase IQ LIKE predicate is SQL-92 compliant. - The Sybase IQ HAVING clause cannot reference non-grouped expressions, although they can be in the select list. (A TransactSQL extension allows having to include columns or expressions that are not in the select list and not in the group by clause.)

Sybase IQ Query Guide

2-21

Retrieving Data from Tables

Sybase IQ Version 11.2.x

Search Conditions
A search condition is a single predicate or multiple predicates that may be combined with the logical operators (AND, OR and NOT) to lter the rows or groups returned by the corresponding FROM or GROUP BY clause. Search conditions help you dene your SELECT criteria. Search conditions have the following syntax:
predicate = {[NOT] search_condition | search_condition AND search_condition | search_condition OR search_condition}

This section describes search conditions available as part of the SELECT statement and the associated clauses. Use logical operators to create logical (or Boolean) expressions, which return true, false, or unknown values. AND joins two conditions and returns results when both conditions are true. OR joins two conditions and returns results when either of the conditions is true. When more than one logical operator is used in a statement, AND operators bind with higher precedence than OR operators. When you combine logical expressions in the predicate, column values are evaluated as follows:

Figure 2-4: Truth table for combined logical expressions

For example, the result of True AND Unknown is Unknown. A NULL value evaluates in any predicate except IS NULL as an Unknown operand.
Note Operands in AND or OR logical expressions return the same result if their order is reversed. This is only true when the statement contains a single AND or OR expression, not when both AND and OR logical expressions are in the same statement. OR has higher precedence than AND.

2-22

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

For example, this search condition nds all the instances where store 5023 purchased title_id BU2075 and all the instances where any store purchased title_id TC4203:
WHERE stor_id = 5023 AND title_id = 'BU2075' OR title_id = 'TC4203'

You can change the order of execution with parentheses. This search condition nds all the instances where store 5023 purchased title_id BU2075 or title_id TC4203:
WHERE stor_id = 5023 AND (title_id = 'BU2075' OR title_id = 'TC4203') NOT negates any predicate.

You can specify NOT in two different places: to negate the entire search condition, or to negate a predicate within it. For example:
WHERE NOT last_name NOT LIKE "Jones"

In this example, the rst NOT negates the search condition (last_name NOT LIKE Jones) and the second negates only the local predicate (like Jones). Putting NOT in either location has the same effect. Compare the following two examples:
SELECT stor_id, ord_num, SUM(qty) FROM salesdetail GROUP BY stor_id HAVING SUM(qty) NOT BETWEEN 10 AND 25 stor_id -------5023 6380 7066 7067 7131 7896 8042 ord_num ------------------ZD-123-DFG-752-9G8 234518 BA52498 NB-3.142 Asoap432 234518 12-F-9 SUM(qty) ------------82674.000000 2430.000000 2430.000000 2900.000000 2097.000000 1182.000000 3733.000000

(7 rows affected) SELECT stor_id, ord_num, SUM(qty) FROM salesdetail GROUP BY stor_id HAVING NOT SUM(qty) BETWEEN 10 AND 25

Sybase IQ Query Guide

2-23

Retrieving Data from Tables

Sybase IQ Version 11.2.x

stor_id -------5023 6380 7066 7067 7131 7896 8042

ord_num ------------------ZD-123-DFG-752-9G8 234518 BA52498 NB-3.142 Asoap432 234518 12-F-9

SUM(qty) ------------82674.000000 2430.000000 2430.000000 2900.000000 2097.000000 1182.000000 3733.000000

(7 rows affected)

Putting NOT in both locations negates NOT, and is the same as if you did not specify it at all. Compliance with Transact-SQL and SQL-92 Sybase IQ does not support the following SQL-92 standard search conditions: some, any, all, match, is true, is false, is unknown.

Predicates
A predicate (or conditional expression) denes a search condition that SQL evaluates as true, false, or unknown. This section describes the predicates that you can specify in search conditions of SELECT statements. Predicates in search conditions have the following syntax:
{comparison_predicate | between_predicate | in_predicate | like_predicate | null_predicate | exists_predicate}

Join predicates and their syntax are described in Chapter 4, Retrieving Data from Multiple Tables. Compliance with Transact-SQL and SQL-92 Sybase IQ does not support the SQL-92 quantied comparison predicate (all, some, or any), unique predicate, match predicate, or overlaps predicate. In Sybase IQ, the order of predicate evaluation is not dened. As a result, for the following SELECT statement, Sybase IQ returns a 'divide by zero' error, but Transact-SQL returns output.

2-24

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

SELECT DISTINCT t_time FROM types_null GROUP BY DATEPART(SECOND, t_time) HAVING DATEPART(SECOND, t_time) + DATEPART(MINUTE, t_datetime) / DATEPART(HOUR, t_time) != 100 AND DATEPART(HOUR, t_time) != 0 AND t_time > "23:50:00" Msg 268566579, Level 14, State 5: Server 'PATR_REGRESGATE': -- An error occurred while processing your request: Sybase IQ: Attempt to divide by zero ('DATEPART(hour,all_types.dbo.types_null.t_time)' yields a zero value). -- File: dfe_ArithmeticExpression.cxx, Line: 216, O/S err: 0 -- Class: db_sqlexception (4098/51)

Value Expressions
Most predicates contain at least one value expression. A value expression is a symbol or string that calculates a value. For predicates that contain value expressions, the syntax variable value_ expression can stand for any of the following: Column name Constant Arithmetic expression Character string DATE or DATETIME value CAST, DATEPART, or SUBSTRING function Aggregate function NULL Some predicates do not support all of these value expressions. See Chapter 3, Using Subqueries and Functions, for restrictions on allowed value expressions. Compliance with Transact-SQL and SQL-92 Sybase IQ does not support the following SQL-92 value expressions in predicates or in the select clause: concatenation and bit strings,

Sybase IQ Query Guide

2-25

Retrieving Data from Tables

Sybase IQ Version 11.2.x

time zones, timestamps, time arithmetic (interval, etc.), default, user, or case. (Time and date manipulation is partially addressed by the Transact-SQL and Sybase IQ DATEPART function.)

Comparison Predicates
A comparison predicate compares two expressions that may be value expressions or subqueries. Here is the syntax for a comparison predicate:
{value_expression | subquery | NULL} comparison_operator {value_expression | subquery | NULL}

In this syntax: value_expression is described in the preceding section. subquery is a query expression enclosed within parentheses, as described in Chapter 3, Using Subqueries and Functions. A subquery can be used on either side of the comparison operator, but not on both sides. comparison_operator is the symbol you use to perform comparisons. Each comparison predicate includes at least one comparison operator. NULL means that the column has no explicit value. NULL is not the same as zero or blank. NULL is not considered greater than, less than, or equal to any other value, including another NULL. The following table shows valid comparison operators in Sybase IQ syntax.
Table 2-3: Comparison operators Operator
= <> != < !< <= >

Meaning
Equal to Not equal to Not equal to Less than Not less than Less than or equal to Greater than

2-26

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

Table 2-3: Comparison operators (continued) Operator


!> >=

Meaning
Not greater than Greater than or equal to

Here are a few additional notes on comparisons: Trailing blanks are ignored. (The shortest operand is conceptually blank padded.) In comparing dates, < means earlier and > means later. For example, the following search condition nds all purchases made after 12/31/94:
WHERE purchase_date > '1994-12-31'

When used with NULL, these operators return results: - = NULL returns all rows that contain NULL - != or <> returns all rows that do not contain NULL These operators never return values when used with NULL: <, <=, !<, >, >=, !>. Each value_expression or subquery compared by the comparison operator must have a degree of 1. In other words, it can return potentially many rows consisting of only one column each. Sybase IQ does not support 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

Compliance with Transact-SQL and SQL-92 The following comparison operators are Transact-SQL extensions that Sybase IQ supports: != (not equal to), !> (not less than), !> (not greater than).

Sybase IQ Query Guide

2-27

Retrieving Data from Tables

Sybase IQ Version 11.2.x

BETWEEN The BETWEEN predicate species an inclusive range, in which Sybase IQ searches for the upper and lower values as well as the values they bracket.
BETWEEN has the following syntax:

value_expression [NOT] BETWEEN value_expression AND value_expression

For example, the following search condition nds information about all titles that were published between June 1, 1985 and June 1, 1987, inclusive:
SELECT title_id, city, total_sales, pubdate FROM titles t1, publishers t2 WHERE t1.pub_id = t2.pub_id AND t1.pubdate BETWEEN '1985-06-01' AND '1987-06-01'
title_id --------BU1032 BU2075 MC3021 PC1035 TC4203 city ----------Berkeley Boston Washington Berkeley Washington total_sales -----------4095 18722 22246 8780 15096 pubdate -------------------Jun 12 1986 12:00:00:000AM Jun 30 1985 12:00:00:000AM Jun 18 1985 12:00:00:000AM Jun 30 1986 12:00:00:000AM Jun 12 1985 12:00:00:000AM

(5 rows affected)

IN
IN selects values that match any one of a list of constants or match some value returned by a subquery. IN has the following syntax:

value_expression [NOT] IN ({constant [, constant]... | subquery})

The value expressions in an IN search condition can only be constants or column names. You cannot specify other types of expressions such as functions. For example, the following search condition nds all the purchases that were made on 11/30/94 or 6/10/94:
WHERE purchase_date IN ('1994-11-30','1994-06-10')

This query nds all the products that are priced at $10.99 or $12.99:
SELECT * FROM titles WHERE price IN

2-28

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

(10.99,12.99)

The Sybase IQ limit on the number of values in an IN list is 16380 values. LIKE Use LIKE when searching for a matching pattern in a column. LIKE is valid for CHAR and V ARCHAR columns.
LIKE has the following syntax:

character_value_expression [NOT] LIKE 'match_string' [ESCAPE escape_character]

In this syntax: character_value_expression stands for any column or expression with CHAR or V ARCHAR data type. match_string is a CHAR or V ARCHAR string that represents a column name or expression. It may include wildcards. escape_character species the character that you are using as an escape character so that you can use wildcards in the match string. For example, the following example selects the authors whose names begin with S:
SELECT au_lname FROM authors WHERE au_lname LIKE 'S%' au_lname ----------------------------------------Straight Smith Stringer (3 rows affected) Note The Sybase IQ LIKE predicate is ANSI-compliant, not Transact-SQL compliant. LIKE does not pad the matched column with blanks, or search for DATETIME values.

Sybase IQ Query Guide

2-29

Retrieving Data from Tables

Sybase IQ Version 11.2.x

Wildcards for LIKE Predicates Sybase IQ provides two wildcard characters that you can use in LIKE clauses to match character strings. In the Sybase IQ syntax convention, match_string is a string of characters and wildcards enclosed in single or double quotation marks. The wildcards are shown in the following table.
Table 2-4: Wildcards Wildcard
% (percent sign) _ (underscore)

Meaning
Any string of zero or more characters Any single character

The column data can be matched to constants, variables, or other columns that contain these wildcard symbols. When using constants, enclose the match strings and character string in quotation marks. Here are a few examples of wildcard characters: LIKE St.%searches for every name that begins with the letters St (St. George). LIKE %ensearches for every name that ends with en (Cohen, Griffen). LIKE %en%searches for every name that has the letters en in it (Bennet, Green, Cohen). LIKE _ancysearches for every ve-letter name ending with ancy (Nancy).
LIKE predicate evaluation in Sybase IQ complies with SQL-92, but not

Transact-SQL. For example, if a column is dened as xed character datatype with length 7, then the following predicate will never evaluate to TRUE:
column LIKE 'xxxx'

Even if xxxx is inserted into this column, the spaces are padded to make it xed length of 7, so that the string xxxx followed by three spaces is stored. Transact-SQL, however, returns rows that stored xxxx followed by three spaces for the LIKE predicate in the example when the column is also dened as NULL allowed. Blanks are treated like any other characters in LIKE searches. This means that if the column you search contains trailing blanks, you

2-30

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

must include those blanks in your match string or use a trailing % wildcard character. For example, suppose that you have a 30-character column that includes rst and last name. The following search condition would nd all the customers with the last name Smith. Without the trailing % wildcard, no matches are found.
WHERE name LIKE '%Smith%'

Wildcards as Literals in LIKE Predicates If you want to use a wildcard as a literal character in a LIKE match string, precede the wildcard with an escape character. You specify which character you are using as an escape with the ESCAPE keyword after the match string. When you specify the escape character, you must enclose it in single or double quotation marks. Here is an example:
WHERE product_code LIKE 'pa/_12%' ESCAPE '/'

The search condition above nds all the product codes that begin with pa_12 and end in any number of any characters. The _ character is treated as a literal instead of as a wildcard. The % character, which is not directly preceded by a /, is treated as a literal. Wildcards used without LIKE have no special meaning; they are treated as regular characters. To search for the escape character, put it in the match string twice, for example:
WHERE product_code LIKE 'pa//12' ESCAPE '/'

IS NULL Use the IS NULL predicate to search for NULL values in a column (or all values except NULL values). The IS NULL predicate is valid only if the column has been dened to allow NULLs in the IQ CREATE INDEXSET statement (NULLs allowed is the default).
IS NULL has the following syntax:

value_expression IS [NOT] NULL

For example, the following search condition nds all the customers whose birth date is unknown:
WHERE birthdate IS NULL

Sybase IQ Query Guide

2-31

Retrieving Data from Tables

Sybase IQ Version 11.2.x

Here is a more complex example:


IQ SET ROWCOUNT 18 SELECT DISTINCT title_id, price, pub_name, pubdate FROM titles, publishers WHERE titles.pub_id = publishers.pub_id AND pubdate IS NOT NULL
title_id -------BU1032 BU1111 BU2075 BU7832 MC2222 MC3021 MC3026 PC1035 PC8888 PC9999 PS1372 PS2091 PS2106 PS3333 PS7777 TC3218 TC4203 TC7777 price --------19.990000 11.950000 2.990000 19.990000 19.990000 2.990000 NULL 22.950000 20.000000 NULL 21.590000 10.950000 7.000000 19.990000 7.990000 20.950000 11.950000 14.990000 pub_name -------------------Algodata Infosystems Algodata Infosystems New Age Books Algodata Infosystems Binnet & Hardley Binnet & Hardley Binnet & Hardley Algodata Infosystems Algodata Infosystems Algodata Infosystems Binnet & Hardley New Age Books New Age Books New Age Books New Age Books Binnet & Hardley Binnet & Hardley Binnet & Hardley pubdate ------------------Jun 12 1986 12:00AM Jun 9 1988 12:00AM Jun 30 1985 12:00AM Jun 22 1987 12:00AM Jun 9 1989 12:00AM Jun 18 1985 12:00AM Feb 20 1997 5:03PM Jun 30 1986 12:00AM Jun 12 1987 12:00AM Feb 20 1997 5:03PM Oct 21 1990 12:00AM Jun 15 1989 12:00AM Oct 5 1990 12:00AM Jun 12 1988 12:00AM Jun 12 1988 12:00AM Oct 21 1990 12:00AM Jun 12 1985 12:00AM Jun 12 1987 12:00AM

(18 rows affected)

In general, the result of comparing NULL values is Unknown, which means neither True nor False. The exception is EXISTS (subquery) which treats NULL as False, so a NOT EXISTS (subquery) will give True if the subquery selects NULL. When you use NULLs with SELECT DISTINCT and GROUP BY clauses: SELECT DISTINCT treats NULLs as equal; only one NULL column is selected. GROUP BY treats NULLs as equal, treating them as a single group. Comparisons treat NULLs as Unknown. Aggregates remove any NULLs encountered, except COUNT(*). These are ANSI semantics.

2-32

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

Compliance with Transact-SQL and SQL-92 Sybase IQ also supports the Transact-SQL syntax that allows use of NULL values with comparison operators. When used with NULL, these operators return results: - = NULL returns all rows that contain NULL. - != NULL or <> NULL returns all rows that do not contain NULL. These operators never return values when used with NULL: <,
<=, !<, >, >=, !>.

EXISTS
EXISTS tests for the existence of some result from the query expression (subquery).

It has the following syntax:


EXISTS (query_expression) EXISTS is not preceded by an expression. If the NOT option is used, the WHERE or HAVING clause of the outer query is satised, when no rows are returned by the query expression. Because EXISTS tests only for

the existence of a condition, not for a particular matching value, the asterisk (*) is almost always used in the query expression select list. For example, the following query nds the number of titles sold per order for those titles with more than 2000 copies sold.
IQ SET ROWCOUNT 23 SELECT DISTINCT pub_id, qty FROM titles t1, salesdetail t2 WHERE EXISTS (SELECT title_id FROM salesdetail t2 WHERE t1.title_id = t2.title_id AND t1.total_sales > 2000) pub_id -----1389 0736 0877 1389 0736 0877 1389 0736 0877 qty --75 75 75 50 50 50 80 80 80

Sybase IQ Query Guide

2-33

Retrieving Data from Tables

Sybase IQ Version 11.2.x

1389 0736 0877 1389 0736 0877 1389 0736 0877 1389 0736 0877 1389 0736

85 85 85 90 90 90 40 40 40 30 30 30 31 31

(23 rows affected)

Arithmetic Expressions and Operators


An arithmetic expression can include a combination of column references, functions (which usually reference a column name), and constants, joined by arithmetic operators. Valid datatypes for columns in arithmetic expressions are: FLOAT, REAL, DECIMAL, NUMERIC, INT, SMALLINT, TINYINT, and UINT. The following table shows the Sybase IQ arithmetic operators.
Table 2-5: Arithmetic operators Symbol
/ * +

Operation
Division Multiplication Subtraction Addition

When there is more than one arithmetic operator in an expression, Sybase IQ calculates division and multiplication rst, followed by subtraction and addition. When all arithmetic operators in an expression have the same level of precedence, the order of execution is left to right. Expressions within parentheses take precedence over all other operations. If parentheses are nested, the innermost expression is executed rst.

2-34

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

The following query uses an arithmetic expression to calculate the prots returned by titles that earned over $500. It then displays the title, order number, and quantity sold of each of these titles.
SELECT titles.title,salesdetail.ord_num,SUM(qty) FROM titles, salesdetail WHERE titles.title_id = salesdetail.title_id GROUP BY titles.title_id HAVING SUM((price*qty) - advance) > 500
title --------------------------------------The Busy Executive's Database Guide Cooking with Computers: Surreptitious Balance Sheets Straight Talk About Computers Silicon Valley Gastronomic Treats But Is It User Friendly? Secrets of Silicon Valley Computer Phobic and Non-Phobic Individuals: Behavior Variations Is Anger the Enemy? Prolonged Data Deprivation: Four Case Studies Fifty Years in Buckingham Palace Kitchens Sushi,Anyone? (11 rows affected) ord_num -----------------234518 Asoap432 NB-3.142 ZZ-999-ZZZ-999-0A0 12-F-9 NB-3.142 ZZ-999-ZZZ-999-0A0 NB-3.142 ZD-123-DFG-752-9G8 13-E-7 BA71224 SUM(qty) ----------4095.000000 3876.000000 4095.000000 2032.000000 8780.000000 4095.000000 375.000000 2045.000000 4072.000000 15096.000000 4095.000000

The CASE Expression


CASE is a conditional expression that you can use in DELETE, 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. CASE expressions can be used anywhere a value expression can be used For example:
SELECT au_lname, postalcode, CASE postal_code WHEN "94705" THEN "Berkeley Author" WHEN "94609" THEN "Oakland Author" WHEN "97330" THEN "Corvallis Author" ELSE "Private" END FROM authors

In this example, CASE compares the values for the postal_code column with several expressions specied after the WHEN keyword. If a match is found, the result is the expression after the THEN keyword. Otherwise, the result becomes the value you specify after the ELSE Sybase IQ Query Guide 2-35

Retrieving Data from Tables

Sybase IQ Version 11.2.x

keyword. If you omit ELSE in your CASE expressions, Sybase IQ will return a NULL. This next example shows a CASE expression that uses search conditions after the WHEN keyword:
IQ DELETE FROM INDEXSET FOR titles WHERE title_id = CASE WHEN type = "business" THEN title_id WHEN total_sales < 4000 THEN title_id WHEN price > 39.99 THEN title_id END

The search conditions can include one or more expressions connected by arithmetic operators that returns TRUE, FALSE, or NULL. The datatype of CASE expression is determined by applying the set operation result datatype rules to the result of the case expression. That is, if a query produces a variety of different datatypes, the result is assigned the datatype that is closest to the top of the datatype hierarchy table (see Datatypes for Columns on page 2-2). Sybase IQ provides a shorthand version of CASE called NULLIF that compares the values of two expressions. If the rst expression equals the second expression, NULLIF returns a NULL value. Otherwise, it will return the rst expression. For example:
SELECT title, NULLIF(type, "UNDECIDED") FROM titles

The above example is equivalent to the following:


SELECT title, CASE WHEN type = "UNDECIDED" THEN NULL ELSE type END FROM titles

Sybase IQ also provides another shorthand version of CASE called COALESCE. It searches a list of expressions for the rst occurrence of a non-NULL value and returns the rst one found. If none are found, it returns a NULL value. For example:
SELECT stor_id, discount, COALESCE (lowqty, highqty) FROM discounts

The above example is equivalent to the following:

2-36

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

SELECT stor_id, discount, CASE WHEN lowqty IS NOT NULL THEN lowqty WHEN highqty IS NOT NULL THEN highqty ELSE NULL END FROM discounts

Here are some rules when using CASE expressions: Sybase IQ does not permit nested CASE expressions. You cannot include a subquery inside a CASE expression. You cannot specify a CASE expression in a GROUP BY or ORDER BY clause. You cannot use CASE with a query if its GROUP BY clause references a column that is not part of the select_list. For example, the following is not allowed:
SELECT type, CASE WHEN type = "business" THEN sum(total_sales) ELSE max(total_sales) END FROM titles GROUP BY type, price

Compliance with Transact-SQL and SQL-92 The CASE expression used in Sybase IQ complies with the SQL-92 standard case expression.

The ORDER BY Clause


ORDER BY sorts the results of your query expression by column. The sorted column(s) must be in the select list. You can sort by column name or a select list number.

The select list number species the ordinal column number in the select list, starting at 1. For example, the following command sorts the output by the title identication number because title_id is the rst column in the select list:
SELECT title_id, pubdate FROM titles ORDER BY 1

Sybase IQ Query Guide

2-37

Retrieving Data from Tables

Sybase IQ Version 11.2.x

title_id -------BU1032 BU1111 BU2075 BU7832 MC2222 MC3021 MC3026 PC1035 PC8888 PC9999 PS1372 PS2091 PS2106 PS3333 PS7777 TC3218 TC4203 TC7777

pubdate ------------------Jun 12 1986 12:00AM Jun 9 1988 12:00AM Jun 30 1985 12:00AM Jun 22 1987 12:00AM Jun 9 1989 12:00AM Jun 18 1985 12:00AM Feb 20 1997 5:03PM Jun 30 1986 12:00AM Jun 12 1987 12:00AM Feb 20 1997 5:03PM Oct 21 1990 12:00AM Jun 15 1989 12:00AM Oct 5 1990 12:00AM Jun 12 1988 12:00AM Jun 12 1988 12:00AM Oct 21 1990 12:00AM Jun 12 1985 12:00AM Jun 12 1987 12:00AM

(18 rows affected)

The following example retrieves the identication numbers of books with over 500 copies sold and organizes them by publication date:
SELECT pubdate,title_id FROM titles WHERE total_sales > 500 ORDER BY pubdate pubdate ------------------Jun 12 1985 12:00AM Jun 18 1985 12:00AM Jun 30 1985 12:00AM Jun 12 1986 12:00AM Jun 30 1986 12:00AM Jun 12 1987 12:00AM Jun 12 1987 12:00AM Jun 22 1987 12:00AM Jun 9 1988 12:00AM Jun 12 1988 12:00AM Jun 12 1988 12:00AM Jun 9 1989 12:00AM Jun 15 1989 12:00AM (13 rows affected) title_id --------TC4203 MC3021 BU2075 BU1032 PC1035 TC7777 PC8888 BU7832 BU1111 PS3333 PS7777 MC2222 PS2091

2-38

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

Each sort can either be ascending (ASC) or descending (DESC). ASC is the default. The following query sorts the results from the most expensive to the least expensive titles:
SELECT title_id, price FROM titles ORDER BY price DESC title_id -------PC1035 PS1372 TC3218 PC8888 BU1032 BU7832 MC2222 PS3333 TC7777 BU1111 TC4203 PS2091 PS7777 PS2106 BU2075 MC3021 MC3026 PC9999 price --------22.950000 21.590000 20.950000 20.000000 19.990000 19.990000 19.990000 19.990000 14.990000 11.950000 11.950000 10.950000 7.990000 7.000000 2.990000 2.990000 NULL NULL

(18 rows affected)

If the value you want to order by is an argument of a function or part of an arithmetic expression in the select list, you must use the select_list_number instead of a column name. In the following example, the name prot is assigned to the arithmetic expression, but the user cannot order by prot.
SELECT (price-advance) AS profit FROM titles ORDER BY 1

Sybase IQ Query Guide

2-39

Retrieving Data from Tables

Sybase IQ Version 11.2.x

profit ------------NULL NULL -14997.010000 -10122.010000 -7985.010000 -7980.000000 -6979.050000 -6978.410000 -6977.050000 -5993.000000 -4988.050000 -4980.010000 -4980.010000 -3992.010000 -3988.050000 -2264.050000 -1980.010000 19.990000 (18 rows affected)

With more complex queries, you may want to sort by two columns, as shown in the following example:
IQ SET ROWCOUNT 23 SELECT pub_id, title, qty FROM titles, salesdetail WHERE titles.title_id = salesdetail.title_id ORDER BY qty, pub_id pub_id -----1389 0736 0736 0736 1389 0736 0877 0736 0736 0877 0877 0877 0877 title ------------------------------------------------But Is It User Friendly? You Can Combat Computer Stress! Life Without Fear Life Without Fear But Is It User Friendly? You Can Combat Computer Stress! Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean You Can Combat Computer Stress! Life Without Fear Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Fifty Years in Buckingham Palace Kitchens The Gourmet Microwave Onions, Leeks, and Garlic: Cooking Secrets of the qty ---25 30 30 31 34 35 40 42 50 50 53 69

2-40

Using Queries

Sybase IQ Version 11.2.x

Retrieving Data from Tables

0877 0877 0877 0736 1389 1389 1389 0736 0877 1389

Mediterranean Sushi, Anyone? Sushi, Anyone? Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Prolonged Data Deprivation: Four Case Studies The Busy Executive's Database Guide Straight Talk About Computers Secrets of Silicon Valley Emotional Security: A New Algorithm Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean But Is It User Friendly?

75 75 80 85 90 94 100 105 125 125 133

(23 rows affected) Note Sybase IQ does not return query rows in the same order every time. A SELECT statement without ORDER BY may return the same rows in a different order the next time you run it.

Compliance with Transact-SQL and SQL-92 The ORDER BY clause used in Sybase IQ complies with the SQL-92 standard order by clause, requiring that the items in the ORDER BY clause be in the select list. Transact-SQL allows you to order by items that are not in the select list.

Sybase IQ Query Guide

2-41

Retrieving Data from Tables

Sybase IQ Version 11.2.x

2-42

Using Queries

3
Introduction Using Subqueries

Using Subqueries and Functions

3.

This chapter provides details on more advanced data retrieval features of Sybase IQ. It covers the following topics: Using Subqueries 3-1 Using Built-in Functions 3-5

A subquery, or nested select, is a query expression nested within the WHERE and/or HAVING clause of another SELECT statement. A subquery is always enclosed in parentheses. The SELECT statement containing the subquery is called the outer query. The outer query uses the results of the subquery. Subqueries may themselves contain subqueries. A subquery has the full SELECT syntax and semantics, except for the restrictions described below. (See The SELECT Statement on page 2-9 for the full SELECT syntax.) In the subquery syntax: Subqueries cannot include the ORDER BY clause. subquery_select_list is a restricted select list for use with subqueries. The following restrictions apply to the subquery select list: - If the subquery is introduced via an IN predicate or a comparison operator, the degree is one. The subquery select list must consist of only one select list item (that is, one column reference, one aggregate function, one arithmetic expression, and so on). - Expressions used in the WHERE or HAVING clause must be join compatible with items in subquery select lists. For additional restrictions, see Chapter 2, Using Queries. The following rules apply to subqueries: A subquery can be used inside scalar expressions, but returns only one row.

Sybase IQ Query Guide

3-1

Using Subqueries

Sybase IQ Version 11.2.x

A subquery that is part of a comparison predicate in a WHERE clause can only produce a single row. (This behavior is compatible with the SQL-92 standards.) The aggregate function in the subquery must reference a column in a table declared in the same subquery. (Sybase IQ does not support outer references inside aggregate functions.) Sybase IQ supports a subquery only on the right hand side of a predicate, except in a comparison predicate. Sybase IQ allows a single subquery on either side (but not both) of a comparison predicate. For example, the following query selects all the books from the titles table for which there is no record of purchases in the salesdetail table.
SELECT title_id FROM titles WHERE title_id NOT IN (SELECT title_id FROM salesdetail) title_id -------MC3026 PC9999 (2 rows affected)

There are two kinds of subqueries: non-correlated and correlated. A non-correlated subquery does not depend on values from its outer query. It can be evaluated independently and is executed just once, no matter how many rows are returned by the outer query. For example, the following example tries to answer the question, Which titles sold the most copies? The subquery yields the highest total sales of any title, which then becomes the comparison value for the main query, to nd which other titles, if any, matched that number of sales.
SELECT t.title_id, t.pubdate, t.total_sales FROM titles t WHERE total_sales = (SELECT MAX(total_sales) FROM titles)

3-2

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Subqueries

title_id -------MC3021

pubdate ------------------Jun 18 1985 12:00am

total_sales ----------22246

(1 row affected)

A correlated subquery depends on the outer query for its values. It contains an outer reference, also called a correlated reference, a reference to a table specied in the outer query containing the subquery. Theoretically, a correlated subquery is executed repeatedly, once for each row selected by the outer query. In practice, however, the Sybase IQ query engine recognizes some instances where it is not necessary, and acts accordingly. The following example uses a correlated subquery to select employees who have higher salaries than their managers. The outer references are e.mgr_id and e.salary named in the last two lines of the subquery.
SELECT e.first_name, e.last_name, e.dept_code FROM employees e WHERE EXISTS (SELECT m.salary FROM employees m WHERE e.mgr_id = m.emp_id AND e.salary > m.salary) ORDER BY e.last_name

The following correlated subquery uses an EXISTS predicate, which is true if the subquery that follows returns at least one row. In this query, the outer reference is titles.title_id.
SELECT title, price, total_sales, pubdate FROM titles WHERE EXISTS (SELECT ord_num FROM salesdetail WHERE salesdetail.title_id = titles.title_id)
title --------------------------The Busy Executive's Database Guide Cooking with Computers: Surreptitious Balance Sheets You Can Combat Computer Stress! Straight Talk About Computers Silicon Valley Gastronomic price --------19.990000 11.950000 total_sales ----------4095 3876 pubdate ------------------Jun 12 1986 12:00AM Jun 9 1988 12:00AM

2.990000 19.990000 19.990000

18722 4095 2032

Jun 30 1985 12:00AM Jun 22 1987 12:00AM Jun 9 1989 12:00AM

Sybase IQ Query Guide

3-3

Using Subqueries

Sybase IQ Version 11.2.x

Treats The Gourmet Microwave But Is It User Friendly? Secrets of Silicon Valley Computer Phobic and Non-Phobic Individuals: Behavior Variations Is Anger the Enemy? Life Without Fear Prolonged Data Deprivation: Four Case Studies Emotional Security: A New Algorithm Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Fifty Years in Buckingham Palace Kitchens Sushi,Anyone? (16 rows affected)

2.990000 22.950000 20.000000 21.590000

22246 8780 4095 375

Jun Jun Jun Oct

18 30 12 21

1985 1986 1987 1990

12:00AM 12:00AM 12:00AM 12:00AM

10.950000 7.000000 19.990000 7.990000 20.950000

2045 111 4072 3336 375

Jun 15 1989 12:00AM Oct 5 1990 12:00AM Jun 12 1988 12:00AM Jun 12 1988 12:00AM Oct 21 1990 12:00AM

11.950000 14.990000

15096 4095

Jun 12 1985 12:00AM Jun 12 1987 12:00AM

The following query nds the orders for books priced higher than the average price of all books sold.
IQ SET ROWCOUNT 23 SELECT salesdetail.ord_num, titles.pubdate FROM salesdetail, titles WHERE titles.title_id = salesdetail.title_id AND titles.price > (SELECT AVG(price) FROM titles) ord_num -------------------234518 234518 Asoap432 Asoap432 XS-135-DER-432-8J2 91-A-7 91-A-7 BS-345-DSE-860-1F2 AX-532-FED-452-2Z7 AX-532-FED-452-2Z7 NF-123-ADS-642-9G3 NF-123-ADS-642-9G3 NF-123-ADS-642-9G3 Fsoap867 pubdate --------------------Oct 21 1990 12:00AM Jun 12 1987 12:00AM Oct 21 1990 12:00AM Jun 12 1987 12:00AM Oct 21 1990 12:00AM Jun 12 1988 12:00AM Oct 21 1990 12:00AM Jun 30 1986 12:00AM Jun 12 1986 12:00AM Jun 22 1987 12:00AM Jun 12 1987 12:00AM Jun 12 1986 12:00AM Jun 30 1986 12:00AM Jun 12 1986 12:00AM

3-4

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

BA52498 BA71224 BA71224 NB-3.142 NB-3.142 ZZ-999-ZZZ-999-0A0 XS-135-DER-432-8J2 ZD-123-DFG-752-9G8 AX-532-FED-452-2Z7 (23 rows affected)

Jun Jun Jun Jun Jun Oct Jun Jun Jun

22 30 12 12 22 21 22 22 12

1987 1986 1987 1988 1987 1990 1987 1987 1987

12:00AM 12:00AM 12:00AM 12:00AM 12:00AM 12:00AM 12:00AM 12:00AM 12:00AM

You can nest subqueries to multiple levels. The following three-level nested subquery nds the employees that make more than their managers manager:
SELECT e.first_name, e.last_name, e.dept_code FROM employees e WHERE EXISTS (SELECT m.salary FROM employees m WHERE e.mgr_id = m.emp_id AND EXISTS (SELECT m2.salary FROM employees m2 WHERE m.mgr_id = m2.emp_id AND e.salary > m2.salary)) ORDER BY e.last_name

The outer references are e.mgr_id and e.salary named in the last two lines of the subquery. (This example builds on the rst correlated subquery example in this chapter.)
Note Queries that include correlated subqueries can often be formulated as joins, in which case they will usually run faster. See Sybase IQ Administration Guide for more information.

Using Built-in Functions


Sybase IQ provides several built-in functions that you can use in queries. This section provides an overview of the Sybase IQ functions: Aggregate functions

Sybase IQ Query Guide

3-5

Using Built-in Functions

Sybase IQ Version 11.2.x

CAST function CONVERT function DATEADD function DATEDIFF function DATEPART function ROUND function String functions SUSER_ID function SUSER_NAME function

Aggregate Functions
Aggregate functions return summary values, such as averages or sums, on groups of rows. Typically, each function operates on a set of values in one column or on an expression. You can apply aggregate functions in two ways: To all the rows in a table, to produce a single value (scalar aggregate). For example, the following returns the sum of all the prices in the titles table:
SELECT SUM(price) FROM titles SUM(price) ---------236.260000 (1 row affected)

To all the rows that have the same value in specied columns (using the GROUP BY clause), in which case the aggregate function produces a value for each group (vector aggregates). For example, the following divides the titles table into groups by publisher, and returns a sum for each group of titles with the same pub_id:
SELECT SUM(price) FROM titles GROUP BY pub_id

3-6

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

SUM(price) ---------48.920000 92.460000 94.880000 (3 rows affected)

Table 3-1 describes the Sybase IQ aggregate functions.


Table 3-1: Sybase IQ aggregate functions Aggregate Function Syntax
AVG([ALL | DISTINCT] argument)

Meaning
Returns the average value of argument. NULL values are not included. AVG is valid for integer and oating point datatypes. Returns the number of rows selected. Rows with NULL values in the specied argument are not included. Returns the number of rows selected, regardless of whether arguments contain NULL values. Returns the maximum value of argument. NULL values are not included. MAX is valid for integer and number type elds, character, oating point, and date/time columns. With character columns, MAX nds the highest value in the selected rows. Returns the minimum value of argument. NULL values are not included. MIN is valid for integer and number type elds, character, oating point, and date/time columns. With character columns, MIN nds the lowest value in the selected rows. Returns the sum of the values in argument. NULL values are not included. SUM is valid for integer and oating point arguments. Default. Tells the function to include all values (except nulls) including duplicates. For example, ALL average of 1, 1, 1, and 3 is 1.5, because all values, including duplicate 1s, are used in average calculation. Tells the function to include only distinct values. For example, DISTINCT average of 1, 1, 1, and 3 is 2, because only a single 1 is used in average calculation.

COUNT([ALL | DISTINCT] argument) COUNT(*) MAX(argument)

MIN(argument)

SUM([ALL | DISTINCT] argument)

ALL

DISTINCT

In the preceding table, argument can be a value expression. In this chapter, the section about each function describes restrictions on value expressions that include that function. See Chapter 2, Using Queries, for general information about value expressions. Sybase IQ Query Guide 3-7

Using Built-in Functions

Sybase IQ Version 11.2.x

Sybase IQ returns an error if you specify a column name with a datatype that is not accepted by that function. The aggregate functions can be used in a select list or, if the select statement includes a GROUP BY, in the HAVING clause. If an aggregate is used in HAVING without GROUP BY, then the rows of the table form a single group that either passes or fails the HAVING test.
Note Sybase IQ does not support outer references inside aggregate functions in a subquery.

When you use aggregate functions against an empty table, syntax and semantics comply with SQL-92, as follows: If you specify a GROUP BY clause, Sybase IQ returns 0 rows. In other cases (for example, aggregation in the select list or HAVING clause), Sybase IQ returns one row with NULLs (or cardinality for COUNT), applies the HAVING clause to that row, and then returns the results. The result can be one row or zero rows if the HAVING clause eliminates the single row. When issuing queries that project an aggregate without a GROUP BY clause, Sybase IQ and SQL Server behave differently. Sybase IQ returns one row, but SQL Server returns all rows, performing the aggregate calculation based on the WHERE clause. For example:
SELECT dept,last,AVG(rate) FROM t1 WHERE div = 10 dept ------10 last -------Tenny AVG(rate) ----------12.120000

(1 row affected) IQ PASS SELECT dept,last,AVG(rate) FROM t1 WHERE div = 10 dept ----------10 20 30 40 last -------- ---------------------------Tenny 12.1200000000000 Power 12.1200000000000 Bello 12.1200000000000 Chapman 12.1200000000000

(4 rows affected)

3-8

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

Only COUNT(*) includes NULL values. (COUNT(*) operates on the existence of a row, not the columns in it.) For example, if you are doing an average on a column and there are NULL values in that column, those values are not included in the average calculation. However, if you call a function with a NULL argument, which could be the case if there were a NULL group, the function automatically returns a NULL. This example tells how many authors in the authors table live in California:
SELECT COUNT(state) FROM authors WHERE authors.state = 'CA' COUNT(state) -----------15.000000 (1 row affected)

This example tells how many rows there are in the salesdetail table:
SELECT COUNT(*) FROM salesdetail COUNT(*) -----------116.000000 (1 row affected)

This example counts how many titles have records in the titles table but not in the salesdetail table, in other words, how many books have not yet sold:
SELECT COUNT(*) FROM titles t1 WHERE t1.title_id NOT IN (SELECT t2.title_id FROM salesdetail t2) COUNT(*) ------------2.000000 (1 row affected)

This example gives the largest price amount, the smallest price amount, the average price amount, and the sum of all the price amounts in the title table. Any rows with a NULL value in the price column are not included.

Sybase IQ Query Guide

3-9

Using Built-in Functions

Sybase IQ Version 11.2.x

SELECT MIN(price), MAX(price), AVG(price), SUM(price) FROM titles MIN(price) ---------2.990000 MAX(price) ---------22.950000 AVG(price) ---------14.766250 SUM(price) ---------236.260000

(1 row affected)

Compliance with Transact-SQL and SQL-92 Unlike Transact-SQL, Sybase IQ and SQL-92 do not allow nested aggregates as the argument to aggregate functions.

CAST Function
Use the CAST function to convert one datatype to another. Here is the syntax for CAST.
CAST (value expression AS data_type[,"datestyle"])

Datatypes are described in Datatypes for Columns on page 2-2. datestyle is the output format you want for date/time columns that you convert to character data. If you do not specify a style, the default output format for the datatype to which you are converting is used. Style characters are shown in Table 3-2, Table 3-3, and Table 3-4.
CAST is useful for constructs like the UNION statement, which requires

that items in the select list match. For example, if you have one table that has a column of dates dened as CHAR and another table that has a column of dates dened as DATE, you can CAST one of these columns to have the same datatype as the other before combining these tables in a UNION statement. The following sample query casts a column as INT so that it lines up with the quantity column during a UNION.
SELECT l_partkey, l_quantity FROM lineitem WHERE l_quantity=22345678 UNION SELECT ps_partkey, CAST(NULL as int) FROM partsupp WHERE ps_suppkey=2

3-10

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

In addition, DATE and DATETIME columns can convert to CHAR or V ARCHAR style formats. They can consist of one or more of the following: Style characters that identify how to format specic portions of the converted data. Most of the style characters are specic to the type of data being converted. Punctuation characters that appear in the output as literal characters. Literal strings that specify literals you want to output. Style Characters The output width of each portion of the data is controlled by how many style characters you specify. For example, NNN species a three-character output for month name. CCCC species a fourcharacter output for the year, including century. Therefore, the following CAST function:
SELECT CAST (pubdate as CHAR(30),"NNN CCCC") FROM titles

yields results like this:


CAST(pubdate) ---------------Jun 1986 Jun 1988 Jun 1985 Jun 1987 Jun 1989 Jun 1985 Feb 1997 Jun 1986 Jun 1987 Feb 1997 Oct 1990 Jun 1989 Oct 1990 Jun 1988 Jun 1988 Oct 1990 Jun 1985 Jun 1987
(18 rows affected)

Sybase IQ Query Guide

3-11

Using Built-in Functions

Sybase IQ Version 11.2.x

Note All alphanumeric characters are reserved as style characters.

The next section discusses the style characters used in a Sybase IQ CAST. General Style Characters The number of characters determines how wide the section will be (except for v which means variable width).
Table 3-2: General style characters Character
q Q v

Meaning
Single quotation mark character (). Double quotation mark character (). Variable width style character which acts as a qualier to the preceding, adjacent style character. Use this option to output the full width of whatever value the style character represents, subject to overall maximum width constraints. For example, Wv outputs the name of the day using the number of characters in each day name. This means the output width varies between rows depending on what day is being output. For example, Monday has fewer characters than Thursday.

Table 3-3: DATE style characters Character


DD JJJ WWW

Meaning
Number of day of month; pad to two digits with zero (01-31). Number of day of year (Julian date); pad to three digits with zero (001-366). Name of day (Sunday, Monday, etc.). Width is determined by the number of Ws you specify, or full name if you use Wv (subject to overall maximum width constraints). Number of month; pad to two digits with zero (01-12).

MM

3-12

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

Table 3-3: DATE style characters (continued) Character


NNN

Meaning
Name of month (January, February, etc.). Width is number of Ns you specify, or full name if you use Nv (subject to overall maximum width constraints). Number of year without century (91,92, etc.); pad to two digits with zero (01, 02, etc.). Number of year with century (1992, 1993, etc.).

YY CCCC

Table 3-4: Time style characters Character


HH hh mm ss

Meaning
Hour based on a 24-hour clock; pad to two digits with zero (00-23). Hour based on a 12-hour clock; pad to two digits with zero (01-12). Minutes; pad to two digits with zero (00-59). Seconds; whole seconds pad to two digits with zero (00-59). If you specify more than two s's, the third s is used for a decimal point, and the rest are used for fractional seconds. However, be aware that Sybase IQ stores only four decimal places for fractional seconds, so you see trailing zeros if you specify more than four places for output. AM or PM designation. AM or PM designation.

pp aa

Punctuation Characters Punctuation characters are dened as any non-alphanumeric characters, such as /, :, and a blank space. The only exceptions to this are single () and double () quotation marks, which are reserved for literal strings and to delimit the entire style specication. For example, the following CAST function:
SELECT CAST (pubdate as CHAR(10),"MM/CCCC") FROM titles

yields results like this:

Sybase IQ Query Guide

3-13

Using Built-in Functions

Sybase IQ Version 11.2.x

CAST(pudate) ---------------06/1986 06/1988 06/1985 06/1987 06/1989 06/1985 02/1997 06/1986 06/1987 02/1997 10/1990 06/1989 10/1990 06/1988 06/1988 10/1990 06/1985 06/1987 (18 rows affected)

Literal Strings Delimit a literal string with either single or double quotation marks, whichever you do not use to delimit the entire style specication. For example, if you use double quotation marks to delimit the style specication, as is shown in the syntax and in all these examples, use single quotation marks to delimit literal strings within the style specication. For example, the following CAST function:
SELECT CAST (pubdate as CHAR(10),"'Year:' CCCC") FROM titles

yields results like this:

3-14

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

CAST(pubdate) ----------------Year: 1986 Year: 1988 Year: 1985 Year: 1987 Year: 1989 Year: 1985 Year: 1997 Year: 1986 Year: 1987 Year: 1997 Year: 1990 Year: 1989 Year: 1990 Year: 1988 Year: 1988 Year: 1990 Year: 1985 Year: 1987 (18 rows affected)

If you want to output a single quotation mark as part of a literal string, use the q style character. Here is an example:
SELECT CAST (pubdate as CHAR(30),"DD NNN qYY") FROM titles

which returns this output:


CAST(pubdate) ----------------12 Jun 86 09 Jun 88 30 Jun 85 22 Jun 87 09 Jun 89 18 Jun 85 20 Feb 97 30 Jun 86 12 Jun 87 20 Feb 97

Sybase IQ Query Guide

3-15

Using Built-in Functions

Sybase IQ Version 11.2.x

21 15 05 12 12 21 12 12

Oct Jun Oct Jun Jun Oct Jun Jun

90 89 90 88 88 90 85 87

(18 rows affected)

If you want to output a double quotation mark as part of a literal string, use the Q style character. Here is an example:
SELECT CAST (pubdate as CHAR(30), "DD NNN QYY") FROM titles

which returns this output:


CAST(pubdate) ----------------12 Jun "86 09 Jun "88 30 Jun "85 22 Jun "87 09 Jun "89 18 Jun "85 20 Feb "97 30 Jun "86 12 Jun "87 20 Feb "97 21 Oct "90 15 Jun "89 05 Oct "90 12 Jun "88 12 Jun "88 21 Oct "90 12 Jun "85 12 Jun "87 (18 rows affected)

General CAST Formatting Rules If you control the width of an output eld by specifying a xed number of style characters, numeric values are right-justied and character values are left-justied. For example, the following CAST function:

3-16

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

SELECT CAST (pubdate as CHAR(30), "NNNNNNNNNN CCCC") FROM titles

returns this output:


CAST(pubdate) ------------------June 1986 June 1988 June 1985 June 1987 June 1989 June 1985 February 1997 June 1986 June 1987 February 1997 October 1990 June 1989 October 1990 June 1988 June 1988 October 1990 June 1985 June 1987 (18 rows affected)

If you use the v style character on an output eld, no column justication is done. For example, the following CAST function:
SELECT CAST (pubdate as CHAR(30), "Wv, Nv DD, CCCC") FROM titles

returns this output:


CAST(pubdate) ------------------------Thursday, June 12, 1986 Thursday, June 09, 1988 Sunday, June 30, 1985 Monday, June 22, 1987 Friday, June 09, 1989 Tuesday, June 18, 1985 Thursday, February 20, 1997 Monday, June 30, 1986 Friday, June 12, 1987 Thursday, February 20, 1997

Sybase IQ Query Guide

3-17

Using Built-in Functions

Sybase IQ Version 11.2.x

Sunday, October 21, 1990 Thursday, June 15, 1989 Friday, October 05, 1990 Sunday, June 12, 1988 Sunday, June 12, 1988 Sunday, October 21, 1990 Wednesday, June 12, 1985 Friday, June 12, 1987 (18 rows affected)

If the style string you specify is longer than the width dened for the converted column, the output is truncated. For example, if you try to format seven characters into a CHAR (6) column, the results are truncated.
SELECT CAST (pubdate as CHAR(6), "NNNNNNNNNN CCCC") FROM titles

returns this output:


CAST(pubdate) ---------------June June June June June June Februa June June Februa Octobe June Octobe June June Octobe June June (18 rows affected)

3-18

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

Note You cannot use CAST with input les or with a SQL Server database. To convert data inside a SQL Server database, use the SQL Server convert function.

Compliance with Transact-SQL and SQL-92 You cannot use the SQL Server convert function on Sybase IQ objects.

CONVERT Function
The CONVERT function is similar to the CAST function. It can change expressions from one datatype to another and specify new display formats for date/time information. You can use it in the select list, in the where clause, and anywhere else an expression is allowed. Here is the syntax:
CONVERT (datatype [(length) | (precision[, scale])], expression[, style])

The datatype argument is a Sybase IQ datatype (for example, CHAR(10) or INT) into which the expression is to be converted. The length argument is an optional parameter used with CHAR or VARCHAR datatypes. If you do not supply a length, Sybase IQ truncates the data to 30 characters. The maximum allowable length for character data is 255. The precision argument is the number of signicant digits in an exact or approximate numeric datatype. If you do not supply a precision, Sybase IQ uses the default precision of 18. The scale argument is the number of digits to the right of the decimal point in an exact numeric datatype. If you do not supply a scale, Sybase IQ uses the default scale of 0. The expression argument is the value to be converted from one datatype or date format to another. The style argument is the display format to use for the converted data. When converting date/time data to a character type, use the style numbers in the following table to specify the display format.

Sybase IQ Query Guide

3-19

Using Built-in Functions

Sybase IQ Version 11.2.x

Values in the leftmost column display 2-digit years (yy). For 4-digit years (yyyy), add 100 or use the value in the middle column.
Table 3-5: Display formats for date/time information Without Century (yy)
1 2 3 4 5 6 7 8 10 11 12

With Century (yyyy)


0 or 100 101 102 103 104 105 106 107 108 9 or 109 110 111 112

Output
mon dd yyyy hh:miAM (or PM) mm/dd/yy yy.mm.dd dd/mm/yy dd.mm.yy dd-mm-yy dd mon yy mon dd, yy hh:mm:ss mon dd yyyy hh:mi:ss:mmmAM (or PM) mm-dd-yy yy/mm/dd yymmdd

The following is an example of the CONVERT function:


SELECT CONVERT(VARCHAR(12), pubdate, 3) FROM titles CONVERT(pubdate) ---------------12/06/86 09/06/88 30/06/85 22/06/87 09/06/89 18/06/85 20/02/97 30/06/86 12/06/87 20/02/97

3-20

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

21/10/90 15/06/89 05/10/90 12/06/88 12/06/88 21/10/90 12/06/85 12/06/87 (18 rows affected)

The following rules affect using CONVERT: Character data can be converted to a non-character typesuch as a date/time, exact numeric, or approximate numeric typeif it consists entirely of characters that are valid for the new type. Leading blanks are ignored. Syntax errors are generated when the data includes unacceptable characters, such as commas or decimal points in integer data. Exact and approximate numeric data can be converted to a character type. If the new type is too short to accommodate the entire string, an insufcient space error is generated. For example, the following conversion fails because it tries to store a 5-character string in a 1-character type:
SELECT CONVERT(CHAR(1), 12.34)

When converting approximate numeric data to a character type, the new type should be at least 25 characters long. Data that is recognizable as a date can be converted to DATETIME. Incorrect month names lead to syntax errors. Dates that fall outside the acceptable range for the datatype lead to arithmetic overow errors. When an explicit conversion results in a loss of scale, the results are truncated without warning. For example, when you explicitly convert a FLOAT, NUMERIC, or DECIMAL type to an INTEGER with no scale specied, Sybase IQ assumes you really want the result to be an integer and truncates all numbers to the right of the decimal point. Compliance with Transact-SQL and SQL-92 The CONVERT function is a Transact-SQL extension to the SQL-92 standard.

Sybase IQ Query Guide

3-21

Using Built-in Functions

Sybase IQ Version 11.2.x

DATEADD Function
The DATEADD function is used to add an interval to Sybase IQ DATE values. It has three arguments and returns a DATE value. Here is the syntax:
DATEADD(datepart, integer_expression, date_expression)

The rst argument to the DATEADD function may be any of the date parts listed in Table 3-6 with the exception of dayofyear and weekday. The second argument to the DATEADD function is any expression which evaluates to an integer or is convertible to an integer. The third argument to the DATEADD function is a character string in one of the acceptable datatype formats or an expression that evaluates to a valid date format (DATE or DATETIME). The DATEADD function is not an ANSI SQL-92 standard feature. It is one of the SQL extensions in Transact-SQL. You can use the DATEADD function in the select list, in the WHERE clause, and anywhere an expression can be used. The following example shows DATEADD used in a select list. It displays the new publication dates of all the books in the titles table slip 21 days.
SELECT DATEADD(DAY, 21, pubdate) FROM titles DATEADD(day,21,titles.pubdate) -----------------------------Jul 3 1986 12:00AM Jun 30 1988 12:00AM Jul 21 1985 12:00AM Jul 13 1987 12:00AM Jun 30 1989 12:00AM Jul 9 1985 12:00AM Mar 13 1997 5:03PM Jul 21 1986 12:00AM Jul 3 1987 12:00AM Mar 13 1997 5:03PM

3-22

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

Nov 11 1990 12:00AM Jul 6 1989 12:00AM Oct 26 1990 12:00AM Jul 3 1988 12:00AM Jul 3 1988 12:00AM Nov 11 1990 12:00AM Jul 3 1985 12:00AM Jul 3 1987 12:00AM (18 rows affected)

The following rules affect using DATEADD: Any date argument is converted to datetime for the calculation. DATEADD returns a date of the same type as the date_expression argument. DATEADD preserves the day of month, that is, after the addition, the resulting date will have the same day of month as the original date. The exception occurs when the day of month in the original date is greater than the number of days in the month of the resulting date. In this case, the new day of month will be the last day of the resulting month. DATEADD preserves time of day of the original date unless datepart is hour, minute, or second. Compliance with Transact-SQL and SQL-92 The DATEADD function is a Transact-SQL extension to the SQL-92 standard.

DATEDIFF Function
The DATEDIFF function is used to return a specied number of date parts between two specied dates. Here is the syntax:
DATEDIFF(datepart, date_expression 1, date_expression 2)

The rst argument to the DATEDIFF function may be any of the date parts listed in Table 3-6 with the exception of dayofyear and weekday. The second and third arguments to the DATEDIFF function are each a character string in one of the acceptable datatype formats or an expression that evaluates to a valid date format (DATE or DATETIME).

Sybase IQ Query Guide

3-23

Using Built-in Functions

Sybase IQ Version 11.2.x

The DATEDIFF function is not an ANSI SQL-92 standard feature. It is one of the SQL extensions in Transact-SQL. You can use the DATEDIFF function in the select list, in the WHERE clause, and anywhere an expression can be used. The following example shows DATEDIFF used in a select list. It displays the difference in years between February 28, 1997 and the publication date for each book in the titles table:
SELECT DATEDIFF(YY, pubdate, 1997-02-28) FROM titles DATEDIFF -------(yy,titles.pubdate,"19 ---------------------11 9 12 10 8 12 0 11 10 0 7 8 7 9 9 7 12 10

(18 rows affected)

The following rules affect using DATEDIFF: DATEDIFF returns a value of datatype INT and causes errors if the result is greater than 2,147,483,647. For seconds, this is 68 years, 19 days, 3:14:07 hours. Sybase IQ generates an error message when this difference is exceeded. DATEDIFF results are always truncated, hot rounded, when the result is not an even multiple of the date part. For example, using hour as the date part, the difference between 4:00AM and 5:50AM is 1. When you use day as the date part, DATEDIFF counts the number of midnights between the two times specied. For example, the difference between January 1, 1997, 23:00 and January 2, 1997, 3-24 Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

01:00 is 1; the difference between January 1, 1997, 00:00 and January 1, 1997, 23:59 is 0. The month datepart counts the number of rst-of-the-months between two dates. For example, the difference between January 25 and February 2 is 1, while the difference between January 1 and January 31 is 0. Compliance with Transact-SQL and SQL-92 The DATEDIFF function is a Transact-SQL extension to the SQL-92 standard.

DATEPART Function
The DATEPART function is used to manipulate Sybase IQ DATE values. It has two arguments and returns an integer value for the specied part of a DATE or DATETIME value. Here is the syntax:
DATEPART(datepart, value_expression)

The rst argument to the DATEPART function may be any of the date parts listed in the following table.
Table 3-6: Date parts and values Date Part
year

Abbreviation
yy

Values
1752 - 9999 (2079 for DATETIME)

Notes
If year is given with two digits, <50 is the next century (25 is 2025) and >=50 is this century (50 is 1950). Counts number of rst-of-themonths between two dates. For example, difference between January 25 and February 2 is 1, while difference between January 1 and January 31 is 0. Counts number of midnights between two times specied. For example, difference between January 1, 1992, 23:00 and January 2, 1992, 01:00 is 1; difference between January 1, 1992 00:00 and January 1, 1992, 23:59 is 0.

month

mm

1 - 12

day

dd

1 - 31

Sybase IQ Query Guide

3-25

Using Built-in Functions

Sybase IQ Version 11.2.x

Table 3-6: Date parts and values (continued) Date Part


dayofyear weekday hour minute second

Abbreviation
dy dw hh mi ss

Values
1 - 366 1 - 7 (Sun.-Sat.) 0 - 23 0 - 59 0 - 59

Notes

The second argument to the DATEPART function is a column name or a non-select expression (such as CAST) that evaluates to a DATE or DATETIME datatype. The DATEPART function is not an ANSI SQL-92 standard feature. It is one of the SQL extensions in Transact-SQL. You can use the DATEPART function: In subqueries In select lists (either by itself or as part of an arithmetic expression) In the GROUP BY, HAVING, or WHERE clause of a query With comparison operators With the BETWEEN predicate The following example shows a DATEPART used in a select list:
SELECT DATEPART(month, pubdate) FROM titles DATEPART(month,pubdate) ----------------------6 6 6 6 6 6 2 6 6 2

3-26

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

10 6 10 6 6 10 6 6 (18 rows affected)

This example shows DATEPART used in an aggregate function:


SELECT MAX(DATEPART(YEAR, titles.pubdate)) FROM titles WHERE titles.pubdate > "1940-01-01" MAX(pubdate) -----------1997 (1 row affected)

Here is an example of a WHERE clause that compares the result of a DATEPART:


SELECT pubdate FROM titles WHERE DATEPART(YEAR,pubdate) = 1985 pubdate -------------------------Jun 30 1985 12:00AM Jun 18 1985 12:00AM Jun 12 1985 12:00AM (3 rows affected)

You can also use a DATEPART function in an arithmetic expression:


IQ SET ROWCOUNT 18 SELECT title_id, (DATEPART(MONTH, pubdate) + 2) AS distrib_month FROM titles

Sybase IQ Query Guide

3-27

Using Built-in Functions

Sybase IQ Version 11.2.x

title_id -------BU1032 BU1111 BU2075 BU7832 MC2222 MC3021 MC3026 PC1035 PC8888 PC9999 PS1372 PS2091 PS2106 PS3333 PS7777 TC3218 TC4203 TC7777

distrib_month ------------8.000000 8.000000 8.000000 8.000000 8.000000 8.000000 4.000000 8.000000 8.000000 4.000000 12.000000 8.000000 12.000000 8.000000 8.000000 12.000000 8.000000 8.000000

(18 rows affected)

Columns specied as arguments to the DATEPART function (such as pubdate in these examples) must have a DATE or DATETIME datatype. The following rules affect using DATEPART: If smalldatetime values are used, they are converted to DATETIME values internally for the calculation. Seconds in smalldatetime values are automatically set to zero for the purpose of the difference calculation. Use the DATETIME datatype only for dates after January 1, 1753. DATETIME values must be enclosed in single or double quotes. Use CHAR, NCHAR, V ARCHAR or NV ARCHAR for earlier dates. Sybase IQ recognizes a wide variety of date formats. See Datatypes for Columns on page 2-2 for information about datatypes and date formats. Sybase IQ automatically converts between character and DATETIME values when necessary (for example, when you compare a character value to a DATETIME value). The date part weekday returns a corresponding number for each day of the week (Defaults for us_english are: Sunday=1, Monday=2, and so on).

3-28

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

Since smalldatetime is accurate only to the minute, when a smalldatetime value is used with DATEPART, seconds are always zero. Compliance with Transact-SQL and SQL-92 The DATEPART function is a Transact-SQL extension to the SQL-92 standard. Sybase IQ does not support the Transact-SQL date parts quarter, millisecond, or week.

ROUND Function
The ROUND function is used to round a numeric expression (up or down) so that it has the specied number of signicant digits. Here is the syntax:
ROUND(numval_expression, integer_expression)

The rst argument to the ROUND function may be any expression which evaluates to INT, UINT, SMALLINT, TINYINT, FLOAT, or REAL. The second argument to the ROUND function is any expression which evaluates to an integer or is convertible to an integer. A positive integer determines the number of signicant digits to the right of the decimal point; a negative integer, the number of signicant digits to the left of the decimal point. The ROUND function is not an ANSI SQL-92 standard feature. It is one of the SQL extensions in Transact-SQL. You can use the ROUND function in the select list, in the WHERE clause, and anywhere an expression can be used. The following example shows ROUND used in a select list. It displays the prices in the titles table rounded to the nearest dollar:
SELECT ROUND(price, 0) FROM titles

Sybase IQ Query Guide

3-29

Using Built-in Functions

Sybase IQ Version 11.2.x

ROUND(titles.price,0) --------------------20.000000 12.000000 3.000000 20.000000 20.000000 3.000000 NULL 23.000000 20.000000 NULL 22.000000 11.000000 7.000000 20.000000 8.000000 21.000000 12.000000 15.000000 (18 row affected)

The next example uses ROUND to display the number of total sales for each title in the titles table to the nearest hundred:
SELECT ROUND(total_sales, -2) FROM titles ROUND(titles.total_sales,-2) ---------------------------4100.000000 3900.000000 18700.000000 4100.000000 2000.000000 22200.000000 NULL 8800.000000 4100.000000 NULL

3-30

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

400.000000 2000.000000 100.000000 4100.000000 3300.000000 400.000000 15100.000000 4100.000000 (18 row affected)

Compliance with Transact-SQL and SQL-92 The ROUND function is a Transact-SQL extension to the SQL-92 standard.

String Functions
These functions operate on character strings and expressions. String functions can be nested, and they can be used anywhere an expression is allowed. When you use constants with a string function, you must enclose them in single or double quotes. The syntax for the string functions uses this general form:
function_name(arguments)

The number and types of arguments will vary from one function to another. The following chart lists the arguments used in string functions. If a function takes more than one argument of the same type, the arguments are numbered (for example, char_expr1, char_expr2).
Table 3-7: Arguments used in string functions Argument Type
char_expr

Can Be Replaced By
A character-type column name, variable, or constant expression of CHAR or V ARCHAR type. Constant expressions must be enclosed in quotation marks. Any integer (tinyint, smallint, or int) column name, variable, or constant expression. Maximum size ranges are noted, as they apply.

integer_expr

Sybase IQ Query Guide

3-31

Using Built-in Functions

Sybase IQ Version 11.2.x

Table 3-7: Arguments used in string functions (continued) Argument Type


start

Can Be Replaced By
Species character position at which substring begins, with rst character in column in position 1. If starting position is beyond width of column, and there is no length specied, no characters are returned. If starting position is beyond width of column, and length is specied, blanks are returned for length. A negative or zero value in the starting position evaluates as the NULL value. A char_expr, integer_expr, or other numeric expression. Constant character data is enclosed by quotation marks, while numeric data is not. Species length of substring. Maximum length allowed is 255 characters. If length is beyond width of column, the specied number of characters is returned right padded with blanks. If no length is specied, substring continues to the end of column.

string_expr

length

Each function also accepts arguments that can be implicitly converted to the specied type. For example, functions that accept approximate numeric expressions also accept integer expressions. Sybase IQ automatically converts the argument to the desired type. The following table lists function names, arguments, and results.
Table 3-8: Function names, arguments, and results Function
DIFFERENCE

Argument
(char_expr1, char_expr2)

Result
Returns an integer representing the difference between two SOUNDEX values. See SOUNDEX, below. Returns the leftmost number of characters (dened by integer_expr) from a character expression (dened by char_expr). Return value has the same datatype as the character expression. Returns the length in bytes of the character expression. Converts uppercase to lowercase, returning a character value.

LEFT

(char_expr, integer_expr)

LENGTH or DATALENGTH LOWER or LCASE

(char_expr) (char_expr)

3-32

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

Table 3-8: Function names, arguments, and results (continued) Function


LTRIM

Argument
(char_expr)

Result
Removes leading blanks from the character expression. Only values equivalent to the space character in the current character set are removed. Returns the rightmost number of characters (dened by integer_expr) from a character expression (dened by char_expr). Return value has the same datatype as the character expression. Removes trailing blanks. Only values equivalent to the space character in the current character set are removed. Returns an integer between 0 and 100 representing (in percentage) the similarity between the two strings. Returns a four-character soundex code for character strings that are composed of a contiguous sequence of valid single-byte roman letters. Concatenates two or more string expressions into a single string. If a string_expr contains numeric data, Sybase IQ converts the data to a character string before any concatenation. The total string length cannot exceed 255 characters. Returns part of a character string. start species the character position at which the substring begins. length species the number of characters in the substring. Removes leading and trailing blanks. Only values equivalent to the space character in the current character set are removed Converts lowercase to uppercase, returning a character value.

RIGHT

(char_expr, integer_expr)

RTRIM

(char_expr)

SIMILAR

(char_expr1, char_expr2)

SOUNDEX

(char_expr)

STRING

(string_expr1 [, string_expr2, ... string_exprN])

SUBSTRING

(char_expr, start, length)

TRIM

(char_expr)

UPPER or UCASE

(char_expr)

The following are some examples of using string functions: This command displays the last name and rst initial of each author:
SELECT au_lname, SUBSTRING(au_fname, 1,1) FROM authors

Sybase IQ Query Guide

3-33

Using Built-in Functions

Sybase IQ Version 11.2.x

au_lname --------White Green Carson O'Leary Straight Smith Bennet Dull Gringles Locksley Greene Blotchet-Halls Yokomoto del Castillo DeFrance Stringer MacFeather Karsen Panteley Hunter McBadden Ringer Ringer

SUBSTRING(au_fname) ------------------J M C M D M A A B C M R A I M D S L S S H A A

(23 rows affected)

These commands show sample results of the RIGHT and LEFT string functions using literals:
SELECT RIGHT("abcde", 3) RIGHT("abcde") -------------cde SELECT LEFT("abcdef", 2) LEFT("abcdef") -------------ab

The following rules affect string functions: Sybase IQ does not support addition operations or any concatenation operations on string operands. You can nest string functions. However you cannot nest the STRING function with another STRING function. Heres an example of nested string functions:

3-34

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

SELECT SUBSTRING(UPPER(au_lname), 1, 3) FROM authors SUBSTRING(UPPER(au_lname)) -------------------------WHI GRE CAR O'L STR SMI BEN DUL GRI LOC GRE BLO YOK DEL DEF STR MAC KAR PAN HUN MCB RIN RIN (23 rows affected)

The LENGTH and RIGHT functions can return different results for the same data depending on the datatype of the character expression. For example, columns with VARCHAR(10) and CHAR(10) data may contain the value abcdefgh, but when you ask for the 4 rightmost characters, the VARCHAR(10) column returns "efgh" and the CHAR(10) column returns "gh". The SOUNDEX function converts an alpha string to a four-digit code for use in locating similar-sounding words or names. All vowels are ignored unless they constitute the rst letter of the string. For example, these two strings return the same value:
SELECT SOUNDEX ("smith"), SOUNDEX ("smythe") SOUNDEX ("smith") ----------------S530 (1 row affected) SOUNDEX ("smythe") -----------------S530

Sybase IQ Query Guide

3-35

Using Built-in Functions

Sybase IQ Version 11.2.x

The DIFFERENCE function compares two strings using soundex codes and evaluates the similarity between them, returning a value from 0 to 4. The best match is 4. The string values must be a contiguous sequence of valid single-byte roman letters.
SELECT DIFFERENCE("smithers", "smothers") DIFFERENCE("smithers", "smothers") ---------------------------------4 (1 row affected) SELECT DIFFERENCE("smothers", "brothers") DIFFERENCE("smothers", "brothers") ---------------------------------2 (1 row affected)

The SIMILAR function compares the character sequence (byte by byte) between two strings and evaluates the similarity between them, returning a percentage value. A high percentage indicates a good or perfect match. For example:
SELECT SIMILAR("smith", "smythe") SIMILAR("smith", "smythe") ---------------------------------72 (1 row affected)

Compliance with Transact-SQL and SQL-92 The string functions comply with both Transact-SQL and SQL-92 syntax.

SUSER_ID and SUSER_NAME Functions


You can use SUSER_ID and SUSER_NAME to determine the ID number and login name of the server user, respectively. The functions require this syntax:
SUSER_ID ([server_user_name]) SUSER_NAME ([server_user_id])

3-36

Using Subqueries and Functions

Sybase IQ Version 11.2.x

Using Built-in Functions

In the preceding syntax: server_user_id is the ID number of the server user or any expression that evaluates to the appropriate type. These IDs are stored in syslogins. If you dont specify one, SUSER_NAME will return the login name of the current user. server_user_name is the server name of the user (login name) or any expression that evaluates to the appropriate type. If you dont specify one, SUSER_ID will return the ID number of the current user from syslogins. For example, the following command displays the name and number for the server user sandy whose server user id is 3:
SELECT SUSER_NAME(3), ---------------------sandy SUSER_ID(sandy) ----------------3

In the following example, a System Administrator whose login name is mary issues the commands without arguments:
SELECT SUSER_NAME(), -------------------mary SUSER_ID() ---------4

Compliance with Transact-SQL and SQL-92 The SUSER_ID and SUSER_NAME functions comply with both Transact-SQL and SQL-92 syntax.

Sybase IQ Query Guide

3-37

Using Built-in Functions

Sybase IQ Version 11.2.x

3-38

Using Subqueries and Functions

4
Introduction Join Operations

Retrieving Data from Multiple Tables

4.

This chapter provides details about queries that let you view data from multiple tables. It covers the following topics: Join Operations 4-1 Predened vs. Ad Hoc Joins 4-17 Union Operations 4-26 Views 4-29

A join is a process of comparing the data in specied columns and using the comparison results to form a new table from the rows that qualify. The join operation has a jargon all its own. The word join is used as a verb and a noun, referring to the operation itself, to the query, or to its results. A query that includes a join is called a join query. A join query is basically a SELECT statement that contains more than one table reference in the FROM clause. The join predicate is a comparison between two columns or column expressions from two logically different tables. The comparison is usually for equalityvalues that match exactlybut other types of joins can be specied. However, if a join is to have meaningful results, the columns being compared must have similar types of data. For example, the following query lists the number of copies per order of a particular title (IQ SET ROWCOUNT limits output to rst fteen rows):
IQ SET ROWCOUNT 15 SELECT title, stor_id, qty FROM salesdetail, titles WHERE titles.title_id = salesdetail.title_id

Sybase IQ Query Guide

4-1

Join Operations

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 (15 rows affected)

stor_id -------7896 7896 7131 7131 5023 8042 8042 8042 8042 8042 8042 5023 5023 5023 5023

qty ---75 75 50 80 85 90 40 30 50 31 69 1000 500 200 150

The query compares the title_id columns in each row of the titles table with the title_id column of each row in the salesdetail table. It then selects the title from each row in the titles table and the stor_id and qty from each row in the salesdetail table where the title_id columns in the two tables match.
Note Currently Sybase IQ supports joins in the same indexspace or associated main and preallocated private indexspaces.

Join Predicates
The join predicate in your query provides the names of columns to be joined and species the join relationship. The WHERE clause may include other search conditions besides the join predicate, of course. The join predicate usually contains a join operator, but it may be any of the predicates described in Chapter 2, Using Queries.

4-2

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Join Operations

Using Join Operators Any predicate that includes more than one table is a join operator. You can use any of the operators in Table 2-3: Comparison operators, or the special relational operators in Table 4-1: Outer join operators. Using Other Predicates as Join Conditions As already stated, other types of predicates may also be used as join conditions, such as the LIKE predicate. The following example shows a join condition that uses the LIKE predicate to nd the authors that live in the same city as one of the publishers:
SELECT au_lname, au_fname, authors.city, pub_name, publishers.city FROM authors, publishers WHERE authors.city LIKE publishers.city
au_lname --------Carson Bennet au_fname --------Cheryl Abraham city --------Berkeley Berkeley pub_name --------------------Algodata Infosystems Algodata Infosystems city ------------Berkeley Berkeley

(2 rows affected)

How Joins Are Processed


Knowing how joins are processed helps to understand them and to interpret unexpected results from incorrectly stated joins. This section describes the processing of joins. Conceptually speaking, the rst step in processing a join is to form the Cartesian product of the two tablesall the possible combinations of the rows from each of the tables. (Sybase IQ almost always uses a faster way of processing joins, but the Cartesian product is a helpful model for understanding joins.) The number of rows in a Cartesian product of two tables is equal to the number of rows in the rst table times the number of rows in the second table. You can produce a Cartesian product with any query that includes more than one table in the FROM clause, and no WHERE clause. The join predicate species the columns to be matched and the basis on which to match them. It may also include other restrictions. Once the Cartesian product has been formed, the rows that do not satisfy the join predicate are eliminated.

Sybase IQ Query Guide

4-3

Join Operations

Sybase IQ Version 11.2.x

Equijoins
An equijoin is a join in which the columns being joined are compared for equality, and all the columns in the tables being joined are included in the results. Although most data warehousing applications, which manipulate large amounts of data, rarely use equijoins, understanding equijoins is a good foundation for using other types of joins. The following query is an example of an equijoin:
SELECT * FROM stores, publishers WHERE stores.state = publishers.state
stor_id payterms -------7066 Net 30 7067 Net 30 7896 Net 60 20435 Net 60 stor_name IQ_ROWID pub_id --------- -----Barnum's 1.000000 1389 News & Brews 2.000000 1389 stor_address city state ctry postalcode pub_name city state IQ_ROWID -------------------------------------------567 Pasadena Ave. Tustin CA USA 92789 Algodata Infosystems Berkeley CA 3.000000 577 First St. Los Gatos CA USA 96745 Algodata Infosystems Berkeley CA 3.000000

Fricative Bookshop 89 Madison St. Fremont CA USA 90019 6.000000 1389 Algodata Infosystems Berkeley CA 3.000000 Walden Expressway 7 0736 Concord MA USA 01776 New Age Books Boston MA

(4 rows affected)

The display shows a total of four rows with fourteen columns each. Columns that match, such as state, appear twice, once for stores and once for publishers. Because of the length of the rows, each takes up multiple horizontal lines in the display. The column headers, which display the table name above each column name, also take up multiple lines. The display, which has been edited for readability, shows three lines of column name headers.

Joins Not Based on Equality


The condition for joining the values in two columns need not be equality. You can specify ad hoc joins using other comparison operators: not equal (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). Sybase IQ also provides the operators !> and !< which are equivalent to <= and >=, respectively.

4-4

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Join Operations

In fact, any predicate referencing columns from two logically different tables may serve as the join condition. This example selects values from rows where the title_ids are not equal:
SELECT titles.title_id, stor_id, AVG(price), SUM(total_sales) FROM titles, salesdetail WHERE titles.title_id != salesdetail.title_id AND ord_num LIKE '%7%'
title_id -------BU1032 stor_id ------8042 AVG(price) ---------14.9644655 SUM(total_sales) ---------------3754323.000000

(1 row affected)

Note Trailing blanks are ignored in comparisons. In comparing dates, < means earlier and > means later.

The combination of predicates determines whether a row meets the join criteria. For example, when two predicates are joined by the logical operator AND, both must be true in order for a row to meet the join criteria. When more than one logical operator is used in a statement, AND operators are handled before OR operators. However, you can change the order of execution with parentheses.

Joins with Additional Conditions


The WHERE clause of a join query can include selection criteria as well as specifying the join condition. For example, to retrieve the names and publishers of all the books for which advances greater than $7500 were paid, the statement is:
SELECT title, pub_name, advance FROM titles, publishers WHERE titles.pub_id = publishers.pub_id AND advance > 7500

Sybase IQ Query Guide

4-5

Join Operations

Sybase IQ Version 11.2.x

title ----------------------------You Can Combat Computer Stress! The Gourmet Microwave (2 rows affected)

pub_name ------------------New Age Books Binnet & Hardley

advance -----------10125.000000 15000.000000

Notice that the columns being joined do not need to appear in the select list and therefore do not show up in the results. As many selection criteria as desired can be included in a join statement. The order of the selection criteria and the join condition is not important.

Self-Joins and Correlation Names


The query below involves a join of the authors table with itself, so the authors table appears in two roles. To distinguish these roles, you can temporarily and arbitrarily give the authors table two different correlation namessuch as au1 and au2in the FROM clause. These correlation names are used to qualify the column names in the rest of the query. Here is an example of a self-join statement:
SELECT au1.au_fname, au1.au_lname, au2.au_fname, au2.au_lname FROM authors au1, authors au2 WHERE au1.city = "Oakland" AND au2.city = "Oakland" AND au1.state = "CA" and au2.state = "CA" AND au1.postalcode = au2.postalcode au_fname ---------Marjorie Dick au_lname ---------Green Straight au_fname ---------Marjorie Livia au_lname ---------Green Karsen

(2 rows affected)

To eliminate the rows in the results where the authors match themselves, and to eliminate rows that are identical except that the order of the authors is reversed, you can make this addition to the self-join query:

4-6

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Join Operations

SELECT au1.au_fname, au1.au_lname, au2.au_fname, au2.au_lname FROM authors au1, authors au2 WHERE au1.city = "Oakland" AND au2.city = "Oakland" AND au1.state = "CA" AND au2.state = "CA" AND au1.postalcode = au2.postalcode AND au1.au_id < au2.au_id au_fname ---------Dick Dick au_lname ---------Straight Straight au_fname ---------Livia Dirk au_lname ---------Karsen Stringer

(2 rows affected)

It is now clear that Dick Straight, Dirk Stringer, and Livia Karsen all have the same postal code. The not-equal join can be used to restrict the rows returned by a selfjoin. In the following example, the titles table is joined to itself, using the t1 and t2 correlation names. A not-equal join and a self-join are used to nd the categories in which there are two or more inexpensive (less than $15) books of different prices.
SELECT DISTINCT t1.type, t1.price FROM titles t1, titles t2 WHERE t1.price < 15 AND t2.price < 15 AND t1.type = t2.type AND t1.price != t2.price type -----------business business price --------11.950000 2.990000

(2 rows affected) Note The expression not column_name = column_name is equivalent to column_name != column_name.

The following example uses a not-equal join combined with a selfjoin. It nds all the rows in the titleauthor table where there are two or more rows with the same title_id but different au_id numbers (that is, books which have more than one author).

Sybase IQ Query Guide

4-7

Join Operations

Sybase IQ Version 11.2.x

SELECT DISTINCT t1.au_id, t1.title_id FROM titleauthor t1, titleauthor t2 WHERE t1.title_id = t2.title_id AND t1.au_id != t2.au_id ORDER BY t1.title_id au_id -----------213-46-8915 409-56-7008 title_id -------BU1032 BU1032

(2 rows affected)

Joining More Than Two Tables


You can join more than two tables, if you like. When there is more than one join operator in the same statement, the join expressions are usually connected with AND, as in the earlier examples, to create a multield key. However, you may connect them with OR instead, to cause a kind of logical union. The following example joins the stores, salesdetail, and titles tables and then groups stores by postal code to determine buying habits by geographic area.
SELECT stores.postalcode, SUM(salesdetail.qty), titles.type FROM stores, salesdetail, titles WHERE stores.stor_id = salesdetail.stor_id AND salesdetail.title_id = titles.title_id GROUP BY stores.postalcode postalcode ----------01776 89076 SUM(qty) ------------82674.000000 3733.000000 type ----------business business

(2 rows affected)

Because the query draws on information contained in three separate tables, stores, salesdetail, and titles, you need a join to retrieve the requested information. You can take advantage of Sybase IQ proprietary indexes in multiple table joins. See Predened vs. Ad Hoc Joins on page 4-17.

4-8

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Join Operations

Joining Tables in Main and Private Indexspaces


For every user session, you have a main indexspace and a private indexspace. If you do not create a private indexspace, Sybase IQ creates it automatically. In this case, the private indexspace is temporary (used for internal operations) and deleted upon the next USE command or exit from Sybase IQ. You may explicitly dene and allocate space for a private indexspace with IQ CREATE INDEXSPACE, thus making the indexspace permanent. If you have preallocated such a private indexspace, you can initiate SQL commands to include joins between tables in the main and private indexspaces. You can join tables across these indexspaces in any statement that supports ad hoc joins (including the SELECT statement and the INSERT...SELECT statement). For example, if you wish to nd all the rows with common id_nums in main and private indexsets maintab and privtab, you could use the following command to join these indexsets. In this example, the names of the indexsets in the main indexspace main_space and the preallocated private indexset priv_space are fully qualied:
SELECT main_space..maintab.id_num, main_space..maintab.name, priv_space..privtab.name FROM main_space..maintab, priv_space..privtab WHERE main_space..maintab.id_num = priv_space..privtab.id_num

Types of Joins
Sybase IQ supports inner, right outer, and left outer joins: An inner join includes only those rows from the two tables being joined which fulll the join conditions. The result is the values in the joined table(s) that match. A right outer join includes all the inner join rows, plus all nonmatching rows, from the right-hand table in the join (the columns in the joined table from the left-hand table for those rows are set to NULL). A left outer join includes all the inner join rows, plus all nonmatching rows, from the left-hand table in the join (the columns in the joined table from the right-hand table for those rows are set to NULL).

Sybase IQ Query Guide

4-9

Join Operations

Sybase IQ Version 11.2.x

Inner Joins
An inner join includes only those rows from the two tables being joined that fulll the join equality condition. The result is the values in the joined table(s) that match. The following example excludes each title without a matching salesdetail row (IQ SET ROWCOUNT limits output to rst ten rows):
IQ SET ROWCOUNT 10 SELECT ord_num, qty, price, total_sales FROM titles, salesdetail WHERE salesdetail.title_id = titles.title_id ord_num ------------------234518 234518 Asoap432 Asoap432 XS-135-DER-432-8J2 91-A-7 91-A-7 91-A-7 91-V-7 55-V-7 (10 rows affected) qty ----75 75 50 80 85 90 40 30 50 31 price ---------20.950000 14.990000 20.950000 14.990000 20.950000 19.990000 20.950000 7.000000 7.000000 7.000000 total_sales -----------375 4095 375 4095 375 4072 375 111 111 111

Outer Joins An outer join lets you include rows in a join that do not match the criteria for a join query. An equijoin gives you only the rows that

4-10

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Join Operations

match, while an outer join gives you the matched rows plus certain unmatched rows.)
Table 4-1: Outer join operators Operator *= Meaning
left outer equal to

Syntax/Description
indexset1.column1 *= indexset2.column1 An inner join (=) plus any rows from the rst table that did not appear in the result, extended with NULLs where there is no match.

=*

right outer equal to

indexset1.column1 =* indexset2.column1 An inner join (=) plus any rows from the second table that did not appear in the result, extended with NULLs where there is no match.

Any statement that contains the join operators is compliant with Transact-SQL. The join operators are an extension of the SQL-92 standard. Recall that the query for authors who live in the same city as a publisher returns two names, Abraham Bennett and Cheryl Carson. To include all the authors in the results, regardless of whether a publisher is located in the same city, use an outer join. Heres what the query and the results of the outer join look like (IQ SET ROWCOUNT limits output to rst six rows):
IQ SET ROWCOUNT 6 SELECT au_fname, au_lname, pub_name FROM authors, publishers WHERE authors.city *= publishers.city au_fname --------Cheryl Abraham Innes Reginald Burt Michel au_lname --------------Carson Bennet del Castillo Blotchet-Halls Gringlesby DeFrance pub_name -------------------Algodata Infosystems Algodata Infosystems NULL NULL NULL NULL

(6 rows affected)

The comparison operator *= distinguishes the outer join from an ordinary join. This left outer join tells Sybase IQ to include all the

Sybase IQ Query Guide

4-11

Join Operations

Sybase IQ Version 11.2.x

rows in the authors table in the results, whether or not there is a match on the city column in the publishers table. Notice that in the results, there is no matching data for most of the authors listed, so these rows contain NULL values in the pub_name column. The right outer join is specied with the comparison operator =*, which indicates that all the rows in the second table are to be included in the results, regardless of whether there is matching data in the rst table. Substituting this operator in the outer join query shown earlier gives this result:
SELECT au_fname, au_lname, pub_name FROM authors, publishers WHERE authors.city =* publishers.city au_fname --------Cheryl Abraham NULL NULL au_lname --------------Carson Bennet NULL NULL pub_name -------------------Algodata Infosystems Algodata Infosystems New Age Books Binnet & Hardley

(4 rows affected)

An outer join can be further restricted by comparing it to a constant. This means that you can zoom in on precisely the value or values you really want to see and use the outer join to list the rows that didnt make the cut. Let us look at the equijoin rst and then compare it to the outer join. For example, if you wanted to nd out which titles had sold more than 500 copies from any store, use this query:
SELECT DISTINCT salesdetail.stor_id, title FROM sales, titles, salesdetail WHERE qty > 500 AND salesdetail.stor_id = sales.stor_id AND salesdetail.title_id = titles.title_id

4-12

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Join Operations

stor_id ------5023 5023 5023 5023 5023 5023 5023 7067 5023 5023 5023 5023 5023 5023

title ----------------------------------------------------But Is It User Friendly? Sushi, Anyone? The Busy Executive's Database Guide Is Anger the Enemy? Emotional Security: A New Algorithm Straight Talk About Computers Fifty Years in Buckingham Palace Kitchens Fifty Years in Buckingham Palace Kitchens Prolonged Data Deprivation: Four Case Studies The Gourmet Microwave Secrets of Silicon Valley You Can Combat Computer Stress! Silicon Valley Gastronomic Treats Cooking with Computers: Surreptitious Balance Sheets

(14 rows affected)

To show, in addition, the titles that didnt sell more than 500 copies in any store, you would use an outer join query:
SELECT DISTINCT salesdetail.stor_id, title FROM titles, salesdetail WHERE qty > 500 AND salesdetail.title_id =* titles.title_id stor_id ------5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 7067 5023 NULL NULL NULL

title ------------------------------------------------

The Busy Executive's Database Guide Cooking with Computers: Surreptitious Balance Sheets You Can Combat Computer Stress! Straight Talk About Computers Silicon Valley Gastronomic Treats The Gourmet Microwave But Is It User Friendly? Secrets of Silicon Valley Is Anger the Enemy? Prolonged Data Deprivation: Four Case Studies Emotional Security: A New Algorithm Fifty Years in Buckingham Palace Kitchens Fifty Years in Buckingham Palace Kitchens Sushi, Anyone? The Psychology of Computer Cooking Net Etiquette Computer Phobic and Non-Phobic Individuals: Behavior Variations NULL Life Without Fear NULL Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean (19 rows affected)

Sybase IQ Query Guide

4-13

Join Operations

Sybase IQ Version 11.2.x

Outer Join Restrictions In Sybase IQ, a table cannot participate in both an outer join clause and in a regular join clause. The following query is passed to the catalog database because the salesdetail table is asked to do double duty:
SELECT DISTINCT sales.stor_id, stor_name, title FROM sales, titles, salesdetail WHERE qty > 500 AND salesdetail.title_id =* titles.title_id AND sales.stor_id = salesdetail.stor_id AND sales.stor_id = stores.stor_id

If you issue an IQ SET QUERYINFO ON command before issuing this query, you will see the following Sybase IQ error:
Sybase IQ: The indexset 'pubs2.dbo.salesdetail' may not be both member of an inner join and inner member of an outer join.

To nd out the name of the store that sold more than 500 copies of some book, you would have to use a second query. If you submit a query with an outer join and a qualication on a column from the inner table of the outer join, the results may be other than what you expect. The qualication in the query does not restrict the number of rows returned, but rather affects which rows contain the NULL value. For rows that do not meet the qualication, a NULL value appears in those rows of the inner table columns. Sybase IQ has the same outer join processing restrictions as System 11 SQL Server. See the SQL Server documentation for more details.

NULLs in Joins
If there are NULL values in the columns of tables being joined, the NULL values can never match each other. Also, the result of a join of NULL with any other value is NULL. Since NULL values represent unknown or inapplicable values, Sybase IQ cannot match one unknown value with another. If the join column in a row contains a NULL value, that row is not part of the inner join. This complies with how NULL values are treated in Transact-SQL and SQL-92. The following rules apply to NULL values: An arithmetic expression that contains a NULL value evaluates to NULL

4-14

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Join Operations

Any comparison operator that contains a NULL value (in WHERE and HAVING clauses) evaluates to unknown, which means neither true or false For more information about how NULL values are evaluated, see Chapter 2, Using Queries. For data that you insert explicitly via IQ INSERT INTO JOINED INDEXSET, Sybase IQ enforces no NULLs if you specied no NULLs in the original table. However, when executing outer joins, Sybase IQ must allow a column to contain NULLs. It is only by using an outer join that you can detect the presence of NULL values in a column from one of the tables being joined. The following examples shows two tables, each of which has a NULL in the column that is part of a join. A left outer join displays the NULL in the rst table. The results show that it may be hard to distinguish a NULL in the data from a NULL that represents a failure to join. If you see NULL columns in the results and you know that no columns returned NULL data, this indicates an outer join. table 1:
a --------1 NULL 4 b -----one three join4

table 2:
c --------NULL 4 d -----two four

The following is the left outer join: SELECT * FROM t1, t2 WHERE a *= c a ------1 NULL 4 b -----one three join4 c ----NULL NULL 4 d -----NULL NULL four

Sybase IQ Query Guide

4-15

Join Operations

Sybase IQ Version 11.2.x

This example uses NULLs in a join to match NULL discounts with all salesdetail rows (IQ SET ROWCOUNT limits output to rst six rows):
IQ SET ROWCOUNT 19 SELECT discounttype, ord_num, qty FROM salesdetail, discounts WHERE salesdetail.stor_id = discounts.stor_id OR discounts.stor_id IS NULL discounttype -------------------Initial Customer Volume Discount Huge Volume Discount Initial Customer Volume Discount Huge Volume Discount Initial Customer Volume Discount Huge Volume Discount Initial Customer Volume Discount Huge Volume Discount Initial Customer Volume Discount Huge Volume Discount Initial Customer Volume Discount Hige Volume Discount Customer Discount (19 rows affected) ord_num -------234518 234518 234518 234518 234518 234518 Asoap432 Asoap432 Asoap432 Asoap432 Asoap432 Asoap432 XS-135-DER-432-8J2 XS-135-DER-432-8J2 XS-135-DER-432-8J2 91-A-7 91-A-7 91-A-7 91-A-7 qty ---75 75 75 75 75 75 50 50 50 80 80 80 85 85 85 90 90 90 90

Compliance with Transact-SQL and SQL-92 Sybase IQ joins comply with the SQL-92 standard except for the following unsupported features: - Joined table keywords cross, natural, inner, outer, left, right and full - The collate clause for grouping columns - except [all] and intersect [all] clauses in non-join query expressions Sybase IQ outer join support complies with Transact-SQL. Neither product supports full outer joins

4-16

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Predefined vs. Ad Hoc Joins

Predened vs. Ad Hoc Joins


Join indexes are Sybase IQ proprietary indexes used to join two or more tables, known as joined indexsets. If join indexes have been dened on the appropriate columns, the join is predened. If joined indexsets do not exist or are not usable for some reason, the join is ad hoc.There is no difference in the syntax of the join query, but an ad hoc join will generally run much more slowly than a predened join. If performance is critical and you regularly need to perform queries that join multiple tables, you should avoid excessive ad hoc joining by asking your System Administrator to create joined indexsets to cover that particular type of query. Sybase IQ supports joins between the main and private indexspaces for a user session. Such joins are only possible in statements that support ad hoc joins. Sybase IQ does not support creation of a joined indexset based on indexsets between the main and private indexspaces, although ad hoc queries may take advantage of joined indexsets (within either the private or main indexspaces) to satisfy a subset of the join condition. For information about creating joined indexsets, see Sybase IQ Administration Guide. If a joined indexset does not exist for one or more of the tables you wish to reference in a query, you cannot create a predened join on those tables, but you can submit an ad hoc join. This lets you query data that cannot be indexed. If there is a joined indexset for a subset of tables in the FROM clause, it will be used in combination with the ad hoc join with the rest of the tables. For example, you can create joined indexsets for certain outer joins, but not for others. You can create a joined indexset for an outer join query that references two tables in the FROM clause, as in this example:
SELECT DISTINCT salesdetail.stor_id, title FROM titles, salesdetail WHERE qty > 500 AND salesdetail.title_id =* titles.title_id

Sybase IQ Query Guide

4-17

Predefined vs. Ad Hoc Joins

Sybase IQ Version 11.2.x

stor_id ------5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 7067 5023 NULL NULL NULL

title -----------------------------------------------The Busy Executive's Database Guide Cooking with Computers: Surreptitious Balance Sheets You Can Combat Computer Stress! Straight Talk About Computers Silicon Valley Gastronomic Treats The Gourmet Microwave But Is It User Friendly? Secrets of Silicon Valley Is Anger the Enemy? Prolonged Data Deprivation: Four Case Studies Emotional Security: A New Algorithm Fifty Years in Buckingham Palace Kitchens Fifty Years in Buckingham Palace Kitchens Sushi, Anyone? The Psychology of Computer Cooking Net Etiquette Computer Phobic and Non-Phobic Individuals: Behavior Variations NULL Life Without Fear NULL Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean (19 rows affected)

If the outer join query references three or more tables in the FROM clause, as shown in the following example, the query must be processed ad hoc:
SELECT DISTINCT salesdetail.stor_id, title,pub_name FROM publishers, titles, salesdetail WHERE qty > 500 AND publishers.pub_id = titles.pub_id AND salesdetail.title_id =* titles.title_id stor_id ------NULL title pub_name ----------------------------------------------------Computer Phobic and Non-Phobic Individuals: Behavior Variations Binnet & Hardley Life Without Fear New Age Books Net Etiquette Algodata Infosystems Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Binnet & Hardley The Psychology of Computer Cooking

NULL NULL NULL

NULL

4-18

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Predefined vs. Ad Hoc Joins

5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 5023 7067

Binnet & Hardley But Is It User Friendly? Algodata Infosystems Cooking with Computers: Surreptitious Balance Sheets Algodata Infosystems Emotional Security: A New Algorithm New Age Books Fifty Years in Buckingham Palace Kitchens Binnet & Hardley Is Anger the Enemy? New Age Books Prolonged Data Deprivation: Four Case Studies New Age Books Secrets of Silicon Valley Algodata Infosystems Silicon Valley Gastronomic Treats Binnet & Hardley Straight Talk About Computers Algodata Infosystems Sushi, Anyone? Binnet & Hardley The Busy Executive's Database Guide Algodata Infosystems The Gourmet Microwave Binnet & Hardley You Can Combat Computer Stress! New Age Books Fifty Years in Buckingham Palace Kitchens Binnet & Hardley

(19 rows affected)

Joins not based on equality are always processed ad hoc. No join index will support queries like the following:
SELECT * FROM a,b WHERE a_i1 = b_i1 AND a_i2 < b_i2 SELECT * FROM a,b WHERE 2 * a_i1 + 1 = b_i1 + 2 AND a_i2 < b_i2 SELECT * FROM a,b WHERE a_i2 < b_i2 + 20

Joins like the following can be either predened or ad hoc:


SELECT * FROM a,b WHERE a_i1 = b_i1 SELECT * FROM a,b WHERE a_i1 = b_i1 AND b_vc1 LIKE 'd%'

Sybase IQ Query Guide

4-19

Predefined vs. Ad Hoc Joins

Sybase IQ Version 11.2.x

Joined Indexsets vs. Views


A joined indexset always predenes a join while a view may also predene a join. They differ in that a view denes the join ad hoc. When processing a joined indexset for a query, Sybase recommends always rst creating the joined indexset then creating a view for the joined indexset. The view name can be specied in place of the individual table names in the FROM clause. The advantage to using a view in this case is twofold: the view aids the optimizer in nding the joined indexset and allows the user to submit queries involving less typing (the view name is shorter than the list of table names in the joined indexset). The following example creates a joined indexset sale_index involving three tables (sales, salesdetail, and stores):
IQ CREATE JOINED INDEXSET sale_index FOR salesdetail(stor_id) = sales(stor_id) MANY >> ONE, sales(stor_id) = stores(stor_id) MANY >> ONE

Sybase recommends that you create the following view after creating this joined indexset:
CREATE VIEW sale_view AS SELECT * FROM sales, salesdetail, stores WHERE salesdetail.stor_id = sales.stor_id AND sales.stor_id = stores.stor_id

The view name sale_view can now be used in place of the lengthy SELECT statement used to dene the view.

Improving Query Performance


In general, for the fastest query processing, you should avoid the following whenever possible: Using RW (Read/Write) access to an indexspace instead of RO (Read/Only) Arithmetic expressions used outside the select list Functions other than DATEPART used outside the select list DISTINCT used with SUBSTRING, CAST, or DATEPART in the select list Correlated subqueries Predicates in the WHERE or HAVING clauses that have two elds as operands rather than one eld and one constant

4-20

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Predefined vs. Ad Hoc Joins

Predicates like any of the following:


expr1 BETWEEN expr2 AND expr3

where expr1 is not a simple column or expr2 or expr3 are not both constants.
expr1 LIKE pattern1

where expr1 is not a simple column, or pattern1 and expr1 are not both string constants.
expr1 IN ({constant [,constant]... | subquery})

where expr1 is not a simple column.


substr(expr1, expr2, expr3)

where expr1 is not a simple column, or expr2 and expr3 are not both integer constants.
CAST(expr as datatype)

whenever expr as datatype is not a plain column or NULL. Arithmetic expressions as arguments to any kind of function Ad hoc joins For more information about improving performance, see Sybase IQ Administration Guide.

Optimizing Ad Hoc Joins


Ad hoc joins may process slowly if your System Administrator does not observe the following recommendations: Create a FASTPROJECTION index on all columns to be selected. Create a LOWFAST or HIGHGROUP index (in addition to the FASTPROJECTION index) on all columns that may be referenced in: - WHERE clauses of ad hoc join queries - HAVING clause conditions of ad hoc join queries outside of aggregate functions Make sure DEFAULTBUFFERS and DEFAULTPRIVATEBUFFERS are sufcient. See Sybase IQ Administration Guide for more details about creating indexes and for suggested DEFAULTBUFFERS and DEFAULTPRIVATEBUFFERS values.

Sybase IQ Query Guide

4-21

Predefined vs. Ad Hoc Joins

Sybase IQ Version 11.2.x

Sybase IQ provides a cost-based query optimizer to generate the optimal (fastest) join execution plan automatically. When the optimizer is off, the join order is determined by the order of tables in the FROM clause of the SELECT statement. (The leftmost table will become the outer table of the topmost join.) The join order optimizer is enabled by default. Sybase recommends that it always remain enabled. However, any user may control its use by issuing the IQ SET JOINOPTIMIZATION ON | OFF command. However, for outer joins, the join order optimizer is used regardless of this setting. The join optimizer produces a join execution plan for each ad hoc query. The plan describes the order in which tables are joined, from the bottom up, until the nal result, a logical table. If a query runs longer than expected, issue the IQ SET QUERYINFO ON command. This command generates join order trace output for ad hoc queries for the duration of your session. You can send this trace output to Sybase Technical Support to diagnose problems in the join order. For more information about the IQ SET commands, see Sybase IQ Language Reference . Here is an example of trace output for an ad hoc query:
IQ SET QUERYINFO ON SET NOEXEC ON SELECT titles.title_id, total_sales FROM titles, publishers, salesdetail, sales, discounts, stores WHERE titles.pub_id = publishers.pub_id AND titles.title_id = salesdetail.title_id AND salesdetail.stor_id = sales.stor_id AND sales.stor_id = discounts.stor_id AND total_sales > 4000 AND date >= "Jan 01 1990" AND date < "Jan 01 1992" GROUP BY titles.title_id ORDER BY 2 DESC
The 'pubs2.dbo.salesjoin' Joined Indexset Index is in use for the 'pubs2.dbo.sales' indexset The current query has been passed to the data flow engine The 'pubs2.dbo.salesjoin' Joined Indexset Index is in use for the 'pubs2.dbo.sales' indexset *** Join optimizer has been invoked (Query Block Id #1). -- Query Plan: -- 1 #18: Order By

4-22

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Predefined vs. Ad Hoc Joins

--- 2 ---

Child Node 1: . #17: Group By

#17

Child Node 1:

#15

Extended GROUP BY Semantics In Use

-Non-Grouped Expression 1: pubs2.dbo.titles.total_sales -- 3 ---------- 4 ---------pubs2.dbo.publishers. -- pub_id) -- 5 -------. . . . #09: Join (Nested-Loop) Left Child Node: Right Child Node: Left Input Table Left Input Table #03 #07 1: 2: titles salesdetail discounts sales . . . . #15: Join (Cartesian Nested-Loop) Left Child Node: Right Child Node: Left Input Table Left Input Table Left Input Table Left Input Table Left Input Table #12 #14 1: 2: 3: 4: 5: discounts sales salesdetail publishers titles stores

Right Input Table 1: . #12: Join (Nested-Loop) Left Child Node: Right Child Node: Left Input Table Left Input Table Left Input Table Left Input Table

#09 #11 1: 2: 3: 4: salesdetail titles discounts sales publishers

Right Input Table 1: Condition 1:

(pubs2.dbo.titles.pub_id =

Right Input Table 1: Right Input Table 2: Condition 1:

Sybase IQ Query Guide

4-23

Predefined vs. Ad Hoc Joins

Sybase IQ Version 11.2.x

-pubs2.dbo.sales. -- stor_id) -- 6 ------pubs2.dbo. -- titles.title_id) -- 7 ---- 7 ----4000) -- 6 ------pubs2.dbo.sales. -- stor_id) -- 7 ---- 7 --. . . . . . . . . . . . . . . #07: . . . . . . . . . . . . . . . #03:

(pubs2.dbo.salesdetail.stor_id =

Join (Nested-Loop) Left Child Node: Right Child Node: Left Input Table #01 #02 1: salesdetail titles

Right Input Table 1: Condition 1:

(pubs2.dbo.salesdetail.title_id =

. #01:

Vertical Cursor Table Name: salesdetail 116

Table Cardinality: . #02: Vertical Cursor Table Name: titles

Table Cardinality: Condition 1:

18

(pubs2.dbo.titles.total_sales > Join (Nested-Loop) Left Child Node: Right Child Node: Left Input Table #05 #06 1: discounts sales

Right Input Table 1: Condition 1:

(pubs2.dbo.discounts.stor_id =

. #05:

Vertical Cursor Table Name: discounts 4

Table Cardinality: . #06: Vertical Cursor Table Name: sales

Table Cardinality:

30

4-24

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Predefined vs. Ad Hoc Joins

--1990') --1992') -- 5 ---- 4 --. . . #14: . . . . #11:

Condition 1: (pubs2.dbo.sales.date >= 'Jan 01 Condition 2: (pubs2.dbo.sales.date < 'Jan 01 Vertical Cursor Table Name: publishers 3

Table Cardinality: Vertical Cursor Table Name: stores 7

Table Cardinality:

The trace output in the preceding example describes the query execution plan in Figure 4-1.

Figure 4-1: Sample query execution plan

The rst line of the preceding output, the data ow engine message, displays only if you have SET QUERYINFO ON. This message simply indicates that some additional processing is required in addition to the proprietary indexes. The rest of the trace output in the example describes the query execution plan. The optimizer identies each select statement in the query with a Query Block identication number. (In a statement with a subquery, the outer query would be Query Block ID #1 and its subquery would be Query Block ID #2.)

Sybase IQ Query Guide

4-25

Union Operations

Sybase IQ Version 11.2.x

Union Operations
The UNION operator allows you to combine two or more queries into a single result set. See Query Expressions on page 2-8 for the syntax. By default, UNION eliminates duplicate rows as part of its processing. To keep duplicates in the query result, specify the ALL keyword. The following example shows two queries and the UNION ALL statement that combines their output:
SELECT title, total_sales, type FROM titles WHERE type = business
title -----------------------------------The Busy Executive's Database Guide Cooking with Computers: Surreptitious Balance Sheets You Can Combat Computer Stress! Straight Talk About Computers (4 rows affected) total_sales -----------4095 3876 18722 4095 type --------business business business business

SELECT title, total_sales, type FROM titles WHERE type = psychology


title ----------------------------------Computer Phobic and Non-Phobic Individuals: Behavior Variations Is Anger the Enemy? Life Without Fear Prolonged Data Deprivation: Four Case Studies Emotional Security: A New Algorithm (5 rows affected) total_sales ------------375 2045 111 4072 3336 type -------------psychology psychology psychology psychology psychology

SELECT title, total_sales, type FROM titles UNION ALL SELECT title, total_sales, type FROM titles WHERE type = psychology

4-26

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Union Operations

title -----------------------------------The Busy Executive's Database Guide Cooking with Computers: Surreptitious Balance Sheets You Can Combat Computer Stress! Straight Talk About Computers Computer Phobic and Non-Phobic Individuals: Behavior Variations Is Anger the Enemy? Life Without Fear Prolonged Data Deprivation: Four Case Studies Emotional Security: A New Algorithm (9 rows affected)

total_sales ----------4095 3876 18722 4095 375 2045 111 4072 3336

type -----------business business business business psychology psychology psychology psychology psychology

Note Eliminating duplicate rows from query results is a time-consuming process, especially if the result has a large number of rows. Therefore, if you know that a particular UNION will not produce duplicate rows, you should specify the UNION ALL operation because the query will execute faster.

The following rules affect the UNION operator: UNION evaluates left to right. The column names of the two (or more) queries combined by a UNION do not have to be identical, but all union operands must have the same number of columns and the column index datatypes in each table must match (for corresponding columns). The result columns produced by a UNION operation are named with the leftmost union names. (See preceding example.) You can use the UNION clause within an IQ INSERT INTO command that contains a SELECT statement. None of the UNION queries can be sorted with an ORDER BY clause, but the result of the union can. The ORDER BY clause is not part of a SELECT statement or a UNION operation and may be applied once to the query result according to the SQL-92 standard. The UNION operation can be used repeatedly to combine three or more sets of query results. Because UNION is a binary operation, you must add parentheses to an expression involving more than two queries to specify

Sybase IQ Query Guide

4-27

Union Operations

Sybase IQ Version 11.2.x

evaluation order and override the default left-to-right evaluation order. GROUP BY and HAVING clauses are permitted within individual queries and are not permitted on the result of the UNION, as specied by the ANSI standard. Eliminating duplicate rows from query results is timeconsuming. If you know that a particular UNION will not produce duplicate rows, specify the UNION ALL operation because the query will execute much more quickly.

Compliance with Transact-SQL and SQL-92


The Sybase IQ UNION operator complies with the SQL-92 standard except for the following unsupported features: - Sybase IQ does not support the into clause or the corresponding keyword of the SQL-92 standard UNION clause. The Sybase IQ UNION operator complies with Transact-SQL, except for the following unsupported features: - Sybase IQ does not support implicit datatype casting for corresponding columns in projection lists of two operands in a UNION. Therefore, corresponding columns must have identical attributes. (Sybase IQ currently does not support Transact-SQL extensions here.) - The following is a Sybase IQ extension: The use of UNION in the SELECT clause of an IQ INSERT INTO statement. You can use a CAST function to make the columns match. In the following example, salary is an integer column in emp_data but not in emp_prole. Specifying CAST(SALARY AS INT) in the second select list makes the following SQL statement valid:
SELECT name, age, salary FROM emp_data UNION SELECT name, age, CAST(SALARY AS int) FROM emp_profileSybase IQ

SQL Server allows mismatching datatypes in a UNION operation; Sybase IQ does not.

4-28

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Views

Views
A view is just another way of looking at the data in one or more tables. It lets you retrieve and display data from one or more tables. A view is made up of a list of columns and tables, as well as a SELECT statement that provides the criteria for the retrieval. A view can also contain references to other views and tables. Views allow you to see only the data you want to see. A view lets you: Create complex joins Derive columns Retrieve columns with matching values Provide less technical end users with a convenient way to encapsulate and access information As Figure 4-2 shows, a view can contain columns and rows from several different tables.

Figure 4-2: Illustration of a view

A view looks exactly like any other table. Sybase IQ lets you work with a view as you would any table, except that you cannot insert into a view. Sybase IQ views, like ad hoc joins, are for queries only. Views provide the following benets: Views allow you to focus on specic data. Irrelevant data can be left out of the view. Views allow you to do additional operations without having to respecify the selection of data, if you dene frequently used joins, projections, and/or selections as views. Views allow different users to see the same data in different ways, even when using the same data at the same time. This advantage

Sybase IQ Query Guide

4-29

Views

Sybase IQ Version 11.2.x

becomes apparent when different users with different skill levels share the same indexspace. Views provide a security mechanism by allowing you to limit access of the data required to only specied users. Views facilitate the use of prejoin conditions involving three or more tables. Sybase recommends always creating a view that mimics the prejoin conditions of the IQ CREATE JOINED INDEXSET commands, using the view in place of the joined indexset names in the FROM clause of a query.

View Security
Through a view, users can query only the data they can see. The rest of the database is neither visible nor accessible. The access of each user to the indexspace can be restricted to specied indexspace objects including views through the grant and revoke commands. If the view and all the tables and views from which it was derived are owned by the same user, the owner can grant permission to use the view while denying permission to access its underlying tables and views. This is a simple but effective security mechanism. The following rules govern view security: In order to create a view, a user must be granted create view command permission by the Database Owner and must have appropriate permissions on any tables or views referenced in the view denition. In order to query a view, a user must have select permission on that view. If the user has permission to select from the view, select permission on the columns or tables from which the view takes its columns is unnecessary. However, if the view is based on other views, select permission on those views is needed. For complete details about command and object permissions, see Sybase IQ Administration Guide.

Creating Views
Sybase IQ uses the Sybase SQL Server implementation for view creation create view and drop view commands are passed through to Sybase SQL Server.

4-30

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Views

Sybase IQ treats views just like any other Sybase SQL Server table. View names must be unique for each user among the already existing tables and views. The CREATE VIEW Command Here is the full syntax for creating a view in Sybase IQ:
create view [[indexspace.]owner.]view_name [(column_name [, column_name] ...)] as SELECT [DISTINCT] select_statement [with check option] Note This is not a Sybase IQ command, but a Sybase SQL Server command.

The columns in a view have by default the same names and always the same datatypes as the columns referred to in the select list of the SELECT statement. The select list can be *, a full or partial list of the column names in the base tables, or any other complex expression. To build views that do not contain duplicate rows, use the DISTINCT keyword with the SELECT statement. Sybase IQ views cannot be inserted/deleted, so the with check option has no functionality for Sybase IQ users. For example:
create view pricing as SELECT title_id, title, price FROM titles SELECT * FROM pricing pricing title_id -------BU1032 BU2075 BU7832 MC2222 MC3021 MC3026 PC1035 PC8888 PC9999 pricing title ------The Busy Executives Database Guide You Can Combat Computer Stress! Straight Talk About Computers Silicon Valley Gastronomic Treats The Gourmet Microwave The Psychology of Computer Cooking But Is It User Friendly? Secrets of Silicon Valley Net Etiquette pricing price ------19.9900 2.9900 19.9900 19.9900 2.9900 NULL 22.9500 20 NULL

(9 rows affected)

You must specify all view column names in the create clause, if: Sybase IQ Query Guide 4-31

Views

Sybase IQ Version 11.2.x

Any of the view columns are derived from an arithmetic expression, a built-in function, or a constant. Two or more of the views columns would otherwise have the same name. This usually happens because the view denition includes a join and the columns being joined have the same name. You want to give a column in the view a different name from the column from which it is derived. Whether or not you rename a view column, it inherits the datatype of the select list item from which it is derived. The following example renames the pub_name column to publisher in the pub_view view:
CREATE VIEW pub_view (publisher, city, state) AS (SELECT pub_name, city, state FROM publishers)

Dening Views
The SELECT statement in the create view statement denes the view. You can create views using a SELECT statement of any complexity. You can also include both main and private indexspace indexsets. There are a few restrictions on the SELECT statements in a view denition: You must have permission to select from objects referenced in the SELECT statement of a view you are creating. You cannot include UNION clauses. You cannot include ORDER BY clauses. Since the view denition resides in the attached SQL Server database, you can only use syntax that is valid to both Sybase IQ and Transact-SQL. For example, you cannot include functions that are supported only by Sybase IQ such as CAST (use the CONVERT function instead).

Dropping Views
To delete a view from the database, use the drop view command. The syntax is:
drop view [[indexspace.]owner.]view_name [, [[indexspace.]owner.]view_name]...

4-32

Retrieving Data from Multiple Tables

Sybase IQ Version 11.2.x

Views

Note This is not a Sybase IQ command, but a Sybase SQL Server command.

As the syntax indicates, you can drop more than one view at a time. A view can only be dropped by the owner. If a view depends on a table (or view) that has been dropped, Sybase IQ displays an error message if anyone tries to use the view. In the following example, the view pricing2 depends on the view pricing:
CREATE VIEW pricing2 AS SELECT * FROM pricing go DROP VIEW pricing go SELECT * FROM pricing2 go

Running this example will produce an error indicating that there is no table with the name pricing. If you create a new table (or view) with the same name and schema to replace the one that has been dropped, the view again becomes usable.

Sybase IQ Query Guide

4-33

Views

Sybase IQ Version 11.2.x

4-34

Retrieving Data from Multiple Tables

Glossary
ad hoc query A query that is not preplanned and for which no explicit tuning is performed. In a client/server environment, a typical application has predened queries and production reports where the only user-dened variables are parameters such as dates. Ad hoc queries imply the ability to query on any eld in the database so that the database executes the queries in a similar way to any standard queries designed into the application. Typically, ad hoc queries increase the likelihood of table scans because of the implicit inability to pre-build appropriate indexes to reduce query processing. In Sybase IQ there is no query specic tuning other than the selection of index types based on data characteristics and the creation of joined indexsets if the table relationships are static. Therefore, against Sybase IQ, all queries are essentially ad hoc. aggregate function A built-in function that generates a single summary value from all the rows within a column, or a group of values, when used with GROUP BY. Supported functions are AVG, SUM, MIN, MAX, and COUNT. For details about each function, see Sybase IQ Language Reference. argument A value supplied to a function or procedure that is required to evaluate the function or procedure. attached database A database to which you may connect your Sybase IQ indexspace to retrieve data. A user can only have one attached database at a time. If no attached database is specied, then the underlying database is used. The attached database may be a non-Sybase database such as Oracle, Informix, DB2, or a non-relational data source. bitmap A list of bits (either 1 or 0). Bitmaps can reside in memory or be stored on disk. bitmap index An index where bitmaps represent the presence of a given value for a eld as true or false (0 or 1).

Sybase IQ Query Guide

Glossary-1

Sybase IQ Version 11.2.x

block The basic unit of measure of data manipulation. At the operating system level, a block is the preferred unit for performing disk I/O activity because it affords the greatest efciency for data transfer. buffer A region of memory used to hold data read from and written to the database. See also chunks. buffer manager A part of Sybase IQ that allocates disk space and manages in-memory copies of data that resides on disk. If there are insufcient buffers to accommodate a computation, the buffer manager acts like a paging system, swapping out old buffers and making them eligible for use in current computations. cardinality The number of rows in a table, or when describing a column or an index, the number of unique values that the column or index has. casting An operation used in the projection of a SELECT statement to convert one datatype to another. It can also be used to obtain a variety of date/time formats when you convert DATE or DATETIME columns to CHAR or V ARCHAR. catalog All information required to manage the Sybase IQ indexes. This information, which includes system tables and stored procedures, resides in a SQL Server release 11 or later database and can be viewed as an extension of the SQL Server catalog. See also joined indexset. chunks A multiblock region of memory or disk. Each time a chunk of data is read from disk, a buffer is created to hold the data in memory. See also buffer. correlation name 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 in a self-join.

Glossary-2

Sybase IQ Version 11.2.x

data warehouse The concept of pulling together information from a variety of sources, at regular intervals to get an integrated view of business activities. Data can reside on different server machines and be stored in any variety of relational formats and legacy systems. decision support system (DSS) A software package designed to allow an organization to analyze collected data and test alternative decisions through repeated queries. derived table The values retrieved from the tables when Sybase IQ evaluates the query expression. See also virtual table. equijoin A join based on equality. expression A column name, a constant, an aggregate function, or a subquery. An expression can be arithmetic, relational, logical, or a character string. extents See segment. FASTPROJECTION (FP) index A Sybase IQ index for columns used only in a projection (the SELECT list) or ad hoc join elds. In general, you should create an FP index on every column. le format A number that identies the release of the le where the database resides. The le format is displayed by the IQ STATUS command. See also SQL catalog table format number. at le A le made up of records of one record type that contains no embedded structure information for managing relationships between records. A at le may be used as the data source for a Sybase IQ indexspace. full-width insert An insert operation into all the columns in a table in the same insert statement. See also partial-width insert.

Sybase IQ Query Guide

Glossary-3

Sybase IQ Version 11.2.x

HIGHGROUP (HG) index A Sybase IQ index ideal for GROUP BY, COUNT(DISTINCT) and SELECT DISTINCT statements when data has more than 1000 unique values. HIGHNONGROUP (HNG) index A Sybase IQ index that makes equality comparisons and SUM and AVG calculations very fast when data has more than 1000 unique values. Nonequality comparisons can also be done. identier A string of characters used to identify a database object, such as table name or column name. index The representation of the data within Sybase IQ. There are ve index types: FASTPROJECTION, HIGHGROUP, HIGHNONGROUP, LOWFAST, and LOWDISK. The choice of index depends on the characteristics of the data being indexed. indexset The set of Sybase IQ indexes for a particular table within the database. Data for the indexes is usually inserted one table at a time (full-width insert), although partialwidth inserts are also allowed. See also partial-width insert. indexspace The space used to house Sybase IQ indexes for a particular database. An indexspace requires an underlying SQL Server database, but is stored outside SQL Server in the le system or on raw partitions (UNIX only). inner join A join that includes only those rows from the two tables being joined that fulll the join condition. The result is the values in the join column(s) that match. inner query See subquery. isql An interactive SQL client application to SQL Server. join A basic operation in a relational system. A join links the rows of two or more tables by comparing the values in specied columns.

Glossary-4

Sybase IQ Version 11.2.x

join eld A join eld is the eld on which two tables are joined. A join eld requires at least one index. Join eld always occur in pairs: one for each table involved in the join. join predicate A condition clause in a query that references two or more distinct items of the FROM list and the basis on which to match them. join query A query that includes a join. joined indexset An internal table that is a set of Sybase IQ indexes prejoined by Sybase IQ for faster query processing. It represents a full outer join of two or more tables. left outer join A join that includes all the inner join rows plus any other nonmatching rows from the rst named table in the join (the columns in the joined indexset from the second named table for those rows are set to NULL). logical expression An expression that evaluates to true (1), false (0), or unknown (NULL). LOWDISK (LD) index A variation of the LOWFAST (LF) index that takes up less disk space. LOWFAST (LF) index The fastest Sybase IQ indexideal for columns that have a very low number of unique values. This index also facilitates join index processing. It is one of the two indexes allowed for columns used in join relationships. master database A database that controls the operation of SQL Server and Sybase IQ. The master database is created in the system catalog when SQL Server is installed, and enhanced when Sybase IQ is installed. model database A database that provides templates for user databases created with Transact-SQL or indexspaces created with Sybase IQ. The model database is created in the system catalog when SQL Server is installed, and enhanced when Sybase IQ is installed.

Sybase IQ Query Guide

Glossary-5

Sybase IQ Version 11.2.x

NULL Having no explicit value. NULL is not the same as zero or blank. NULL is not considered greater than, less than, or equal to any other value, including another NULL. outer join A join that returns both columns that match and columns that dont match the search criteria. See also left outer join, right outer join. partial-width insert An insert operation into a subset of the columns in an indexset. See also full-width insert. passthrough statement A statement that cannot be processed by Sybase IQ, such as a query that references a column that is not indexed. Such queries are sent to the attached database (if any) to be executed there. If there is no attached database, the query is passed to the underlying database. See also attached database, underlying database. precision A number that indicates the minimum width for data output. The maximum number for precision varies by data type. 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. predened join A join where join indexes have been predened on the appropriate columns. See also ad hoc query. projection An operation that retrieves a subset of the columns in one or more tables dened by a select list. right outer join A join operation that includes all the inner join rows plus any other non-matching rows from the second named table in the join (the columns in the joined indexset from the rst named table for those rows are set to NULL). scale Indicates how many decimal places there are in the data for input and display. Regardless of the scale, the values are stored in Sybase IQ as integers.

Glossary-6

Sybase IQ Version 11.2.x

segment An operating system le that contains data for a particular indexspace. You can use segments to spread indexspaces across operating system les and locate them on different volumes and le systems. selection An operation that retrieves a subset of the rows in one or more tables. select list See projection. self-join A join used for comparing values within a single table. Since this operation involves a join of a table with itself, you have to provide two temporary table names (aliases). These are then used to qualify the column names in the rest of the query. set of rows Rows being inserted into a table by either one full-width insert or divided among multiple partial-width inserts. SQL catalog table format A number that identies the release of the SQL catalog table for the current Sybase IQ indexspace. This number is displayed by the IQ STATUS command. STARTRECID An option on the INSERT and INSERT INTO JOIN commands that species the Sybase IQ record identication number of the row at which to start an insert. stored procedure A collection of SQL statements and optional control-ow statements that control DDL operations for Sybase IQ and SQL Server. System tables can only be altered using stored procedures. Stored procedures are stored in the system catalog. subquery A SELECT statement that is nested inside another SELECT, INSERT, or DELETE statement. system catalog The collection of system tables that describe the organization of the tables that actually hold the data, and stored procedures used to manage the system tables. The system catalog contains the master and model databases. Sybase IQ Query Guide Glossary-7

Sybase IQ Version 11.2.x

system table A table in the master database that contains data used to manage Sybase IQ objects.The system tables are organized in the master database and model database. TMPDIR A system environment variable that indicates where you want to store temporary, private indexspace les for Sybase IQ. top table The last table joined in a multitable join or joined indexset. Also called top join table. underlying database A database that contains the data denitions for tables and columns used by a Sybase IQ indexspace. Each indexspace must have an underlying SQL Server database with the same name, although the indexspace contains only the indexed subset of data in the underlying database. The underlying database is also used as the source of table and column information when no attached database is specied (and a at le is not used as the data source). vertical insert See partial-width insert. virtual table A table that doesnt physically exist, but is constructed as needed. wildcard Special characters used with the LIKE keyword that can stand for zero or more characters in pattern matching. Valid wildcard characters are % (percent sign), which stands for any string of zero or more characters, and _ (underscore), which stands for any single character.

Glossary-8

Index
Symbols
!< (not less than) 2-26 != (not equal to) as comparison operator 2-26 () (parentheses) in SQL statements xvi * (asterisk) in query expression select list 2-33 *= (left outer equal to) 4-11 , (comma) in SQL statements xvi ... (ellipsis) in SQL statements xvi, xviii < (less than) 2-26 <= (less than or equal to) 2-26 <> (not equal to) 2-26 = (equal to) as comparison operator 2-26 =* (right outer equal to) 4-11 [ ] (square brackets) in SQL statements xvi {} (curly braces) xvi
SUM 3-7 alias syntax 1-12 ALL predicate in aggregate function 3-7 all predicate in WHERE clause 2-17 Alphanumeric characters 3-12 AND operator 2-15, 2-22 ANSINULL option, IQ SET 1-14 any predicate 2-17 Application front-end 1-7 Architecture open 1-3 Arguments string functions 3-31 ARITH_OVERFLOW option, IQ SET 1-14, 1-15 OFF 1-15 ON 1-15 ARITHABORT option, IQ SET 1-14 ARITHIGNORE option, IQ SET 1-15 Arithmetic using functions 3-9 Arithmetic expressions denition 2-34 ORDER BY clause 2-39 precedence 2-34 Arithmetic operators 2-34 Ascending order sorting results in 2-39 ASC keyword 2-39 Attached databases opening 1-7 AVG function 3-7

A
Abbreviations for date parts 3-25 Ad hoc queries 2-1 Aggregate functions against empty tables 3-8 ALL predicate 3-7 AVG 3-7 COUNT 3-7 COUNT(*) 3-7 denition 3-6 DISTINCT option 3-7 in GROUP BY clause 2-17 in subqueries 3-2 MAX 3-7 MIN 3-7 restrictions 2-16

B
BETWEEN predicate 2-28

Bit strings 2-25 Blanks in comparisons 2-27

Sybase IQ Query Guide

Index-1

Sybase IQ Version 11.2.x

removing leading with LTRIM function 3-33 removing trailing with RTRIM function 3-33 Boolean expressions. See Logical expressions Built-in functions. See Functions

COALESCE expression 2-36

Codes
SOUNDEX 3-33 collate clause 2-20, 4-16

C
Calculations in queries 2-26 null values in 3-9 Cardinality of table rows 2-8 Cartesian products 4-3 CASE expression 2-35 SQL92 compliance 2-37 case expression 2-26 Case sensitivity xvii CAST function 3-10 formatting rules 3-16 punctuation characters in 3-13 Casting 3-10 Catalogs denition 1-3 Characters alphanumeric 3-12 general style 3-12 punctuation 3-13 reserving 3-12 style 3-11 Character strings searching 2-15 CHAR datatype 2-3 Clauses FROM 1-8, 2-12 GROUP BY 1-8, 2-17 HAVING 1-8, 2-20 LIKE 2-30 ORDER BY 1-10, 2-37 WHERE 1-11, 2-14 Client application connecting to Sybase IQ 1-5

Columns oating point 3-7 integer 3-7 marking unknown values 2-5 sorting by 2-37 Comma (,) in SQL statements xvi Command line parameters isql utility 1-5 Commands exit 1-7 go 1-6 IQ BACKUP 1-8 IQ DBCC 1-9 IQ RESTORE 1-10 quit (isql) 1-7 Command terminator (isql) 1-6 Comparing dates 2-27 Comparing values DIFFERENCE string function 3-36 Comparison operators list of 2-26 trailing blanks and 2-27 Transact-SQL extensions supported 2-24, 2-27 used with NULL 2-27 Comparison predicates 2-26 compute clause (Transact-SQL) 2-12 Concatenation 2-25 Conditional expressions. See Predicates Connecting to Sybase IQ 1-5 Constants in string functions 3-31 Conventions Transact-SQL syntax xvi used in manuals xv Conversions explicit datatype 2-7 implicit datatype 2-7 lowercase to uppercase 3-33

Index-2

Sybase IQ Version 11.2.x

unsupported datatype 2-7 uppercase to lowercase 3-32 CONVERT function 3-19 Converting column datatypes 2-7, 3-10, 3-11 Correlated subqueries 3-3 Correlation names denition 2-10 in FROM clause 2-12 table name 4-6 corresponding keyword 4-28 COUNT(*) function 3-7 null values in 3-9 COUNT function 3-7 create view command 4-30, 4-31 Creating indexspaces 1-7 queries 2-8 Sybase IQ objects 1-4 user accounts 1-4 cross keyword 4-16 Curly braces ({}) in SQL statements xvi

D
Databases attached, opening 1-7 naming 2-2 qualifying object names 2-10 DATALENGTH string function 3-32 Data output width 3-16 Datatypes CHAR 2-3 compatibility 2-7 converting 3-11 DATE 2-4 DATETIME 2-4 denition 2-2 explicit conversions 2-7 implicit conversions 2-7 INT 2-3 INTEGER 2-3 matching 2-7

precision 2-4 REAL 2-4 rules for using 2-5 scale 2-4 SMALLINT 2-3 storage 2-5 Sybase IQ 2-7 V ARCHAR 2-3 Data warehousing 1-1 DATEADD function 3-22 purpose of 3-22 where used 3-22 DATE datatype 2-4 DATEDIFF function 3-23 purpose of 3-23 where used 3-24 DATEPART function 3-25 purpose of 3-25 where used 3-26 Date parts abbreviation names and values 3-25 Dates comparing 2-27 earliest allowed 3-28 pre-1753 datatypes for 3-28 DATETIME datatype and LIKE predicate 2-17 DATETIME datatype 2-4 day date part 3-25 dayofyear date part 3-26 dd. See day date part 3-25 Decision Support Systems (DSS) 1-1 default expression 2-26 Degree denition 2-8 in comparison predicate 2-27 subquery in IN predicate 3-1 Delimiters literal strings 3-14 Descending order sorting results in 2-39 DESC keyword 2-39 DIFFERENCE string function 3-32 DISTINCT option

Sybase IQ Query Guide

Index-3

Sybase IQ Version 11.2.x

aggregate functions 3-7 Dropping leading or trailing blanks 3-33 drop view command 4-32 Duplicate rows 4-6 dw. See weekday date part 3-26 dy. See dayofyear date part 3-26

E
Ellipsis (...) in SQL statements xvi, xviii E notation 2-5 Equijoins 4-4 Escape characters 2-31 ESCAPE keyword 2-31 except clause 4-16 EXISTS predicate 2-33 subqueries and 2-16 exit command (isql) 1-7 Explicit conversions 2-7 Expressions CASE 2-35 GROUP BY clause 2-18 scalar 3-1

COUNT 3-7 COUNT(*) 3-7 DATEADD 3-22 DATEDIFF 3-23 DATEPART 3-25 in ORDER BY clause 2-39 MAX 3-7 MIN 3-7 ROUND 3-29

set. See Aggregate functions SUM 3-7 SUSER_ID 3-36 SUSER_NAME 3-36 using with SELECT 3-5

G
go command 1-6 grant command 4-30 GROUP BY clause 1-8, 2-17

aggregate functions 2-17 performance 2-20 purpose 2-17 restrictions 2-18 SQL92 compliance 2-20, 2-41 Transact-SQL compliance 2-20

F
Filler characters 2-5 Filtering groups retrieved 2-20 Flat les as data source 1-2 Floating point data 3-7 for browse option (Transact-SQL) 2-12 FROM clause 1-8, 2-12 multiple table references in 2-13 Front-end application invoking Sybase IQ through 1-7 full keyword 4-16 Functions aggregate 3-6 AVG 3-7 CAST 3-10 CONVERT 3-19

H
HAVING clause 1-8, 2-20

expressions in 2-21 restrictions 2-21 SQL92 compliance 2-21 Transact-SQL compliance 2-21 Help xix hh. See hour date part 3-26 holdlock clause (Transact-SQL) 2-12 hour date part 3-26

I
Identier denition 1-11 Identiers 2-10

Index-4

Sybase IQ Version 11.2.x

Implicit conversions 2-7 Indexes and queries 2-1 for joins. See Join indexes parallel building 1-2 sources of data for 1-4 Indexsets 1-3 See also Tables denition 1-3 Indexspaces automatically connecting to 1-7 closing 1-7 connecting to default 1-7 corresponding to database 1-7 creating 1-7 default 1-7 denition 1-3 multiple user access 1-7 naming 2-2 privileges for populating 1-7 INFOMESSAGES option, IQ SET 1-15 Inner joins denition 4-9, 4-10 inner keyword 4-16 IN predicate 2-28 degree of subquery 3-1 subqueries 2-16 Installing Sybase IQ 1-4 Sybase IQ Open Server 1-4 INT datatype Sybase IQ 2-3 Integer columns 3-7 INTEGER datatype Sybase IQ 2-3 intersect clause 4-16 Invoking Sybase IQ 1-7 IQ ADD SEGMENT command 1-8 IQ ALTER INDEXSET command 1-8 IQ BACKUP command 1-8 IQ CLOSE command 1-7 IQ CLOSE INDEXSPACE command 1-8 IQ CREATE INDEX command 1-9

IQ CREATE INDEXSET command 1-9 IQ CREATE INDEXSPACE command 1-9 IQ CREATE INDEXSPACE TEMPLATE

command 1-9
IQ CREATE JOINED INDEXSET command 1-9 IQ DBCC command 1-9 IQ DELETE FROM INDEXSET command 1-9 IQ DROP INDEX command 1-9 IQ DROP INDEXSET command 1-9 IQ DROP INDEXSPACE command 1-9 IQ DROP SEGMENT command 1-9 IQ INSERT INTO command 1-9 IQ INSERT INTO JOINED INDEXSET

command 1-9
IQ option, IQ SET 1-16 ON 1-16 IQ PASS command 1-9 IQ RESTORE command 1-10 IQ SET (Query Processing) command

keywords and options 1-14


IQ SET command 1-10

syntax 1-13
IQ SET JOINOPTIMIZATIONcommand 4-22 IQ SET QUERYINFO ON command 4-14 IQ SHOW INDEXSET command 1-10 IQ SHOW INDEXSET INDEXES command 1-10 IQ SHOW INDEXSET JOINED INDEXSETS

command 1-10
IQ SHOW INDEXSPACE command 1-10 IQ SHOW INDEXSPACE INDEXES

command 1-10
IQ SHOW INDEXSPACE JOINED INDEXSETS

command 1-10
IQ SHOW SET VALUES command 1-10 IQ SHOW SIZE command 1-10 IQ STATUS command 1-10 is false predicate 2-17 IS NULL predicate 2-31 isql options -J 1-5 -l 1-6 -P 1-6 -S 1-6 -U 1-6

Sybase IQ Query Guide

Index-5

Sybase IQ Version 11.2.x

-w 1-6 isql utility

command line parameters 1-5 exit command 1-7 exiting 1-7 go command 1-6 issuing commands to Sybase IQ 1-6 maximum statement size 1-6 purpose 1-5 quit command 1-7 terminating commands 1-6 is true predicate 2-17 is unknown predicate 2-17

outer 4-10 overview 4-1 predened 4-17 processing 4-3 right outer 4-9 selection criteria for 4-5 standards compliance 4-11 types of 4-9

K
KEEPOPENIQLOG option, IQ SET 1-16 Kernel threads 1-2

J
Joined indexsets denition 4-17 vs. Views 4-20 Join indexes 2-16 Join operations 4-1 JOINOPTIMIZATION option, IQ SET 1-16, 4-22 JOINORDERLEFTDEEP option, IQ SET 1-16 Join predicates 4-5 denition 4-1 with other search conditions 2-15 Join queries 4-1 Joins ad hoc 4-17 optimizing 4-21 comparison operators 4-4 denition 4-1 equijoins 4-4 greater than 4-4 greater than or equal to 4-4 inner 4-9, 4-10 join order trace output 4-22 left outer 4-9 less than 4-4 less than or equal to 4-4 not equal 4-4 NULL in 4-14 operators for 4-3, 4-4 optimizing 4-21

L
LCASE string function 3-32

Leading blanks, removal with LTRIM function 3-33 left keyword 4-16 Left outer joins denition 4-9 LEFT string function 3-32 LENGTH string function 3-32 LIKE predicate 2-29 Literals dening 2-5 Literal strings 3-11, 3-14 See also Indexes 1-11 delimiters 3-14 Logical expressions 2-22 operand order 2-22 Logical operators execution priority 2-22 precedence 2-22 LOWER string function 3-32 LTRIM string function 3-33

M
match_string 2-30 match predicate 2-17 Match strings LIKE predicate 2-30

Index-6

Sybase IQ Version 11.2.x

MAX function 3-7 mi. See minute date part 3-26 millisecond date part 3-29 MIN function 3-7 minute date part 3-26 mm. See month date part 3-25

Modiers. See Predicates


month date part 3-25

Multi-threaded operations 1-2

N
Names nding similar-sounding 3-35 qualifying 1-13, 2-9 weekday numbers and 3-28 natural keyword 4-16 Nested selects. See Subqueries Nesting expressions precedence 2-34 NOEXEC option, IQ SET 1-16 Non-correlated subqueries 3-2 NOT operator 2-23 specifying twice 2-24 NULLIF expression 2-36 NULL values 2-5 aggregate functions 2-32 grouping 2-18 in comparisons 2-32 in functions 3-9 in joins 4-14 searching for 2-31 with GROUP BY 2-32 with SELECT DISTINCT 2-32 Numbers weekday names and 3-28 NUMERIC_TRUNCATION option, IQ SET 1-14, 1-17 ON 1-17

OLTP. See Online transaction processing Online transaction processing 1-2 Open architecture 1-3 Operators AND 2-22 arithmetic 2-34 NOT 2-24 OR 2-22 Optimizing ad hoc joins 4-21 Options syntax conventions for xvii Order of rows returned 2-41 weekday numeric 3-28 ORDER BY clause 1-10, 2-37 arithmetic expressions 2-39 function arguments 2-39 specifying sort order in 2-39 Order of execution logical operators 4-5 OR operator 2-22 Outer joins denition 4-10 restrictions on 4-14 outer keyword 4-16 Outer query 3-1 Outer references 3-3, 3-5 Output width of 3-16 overlaps predicate 2-24

P
Parallel index building 1-2 Parallel processing 1-2 Parentheses () and subqueries 3-1 in SQL statements xvi Pattern matching DIFFERENCE and SIMILAR string function 3-32 Permissions 2-2 Precedence logical operators 2-22

O
OFF 1-17

Sybase IQ Query Guide

Index-7

Sybase IQ Version 11.2.x

Precision denition 2-4 Predicates BETWEEN 2-28 comparison 2-26 denition 2-24 EXISTS 2-33 IN predicate 2-28 is false 2-17 IS NULL 2-31 is true 2-17 is unknown 2-17 join 4-1 LIKE 2-29 MATCH 2-17 negating 2-23 overlaps 2-24 quantied comparison 2-24 syntax 2-24 unique 2-24 Prejoins. See Joins, predened Privilege checks 2-2 Privileges for creating indexspaces 1-7 for populating indexspace 1-7 Products Cartesian 4-3 Projections denition 2-8 Punctuation characters 3-11 for casting 3-13

join 4-1 join order trace output 4-22 order of returned rows 2-41 outer 3-1 passing to server 2-1 prerequisite for running 2-1 privileges for 2-2 Query expressions 2-8 nested 3-1 syntax 2-8 uses 2-8 where used 2-9 QUERYINFO option, IQ SET command 4-22 Query performance improving 4-20 quit command (isql) 1-7 Quotation marks as string delimiters 2-15, 3-14

R
Read/Only mode 1-7 REAL datatypes 2-4 References outer 3-3 Resolving queries without Sybase SQL Server database 1-2 Retrieving similar-sounding words or names 3-35 revoke command 4-30 right keyword 4-16 Right outer joins denition 4-9 RIGHT string function 3-33 ROUND function 3-29 purpose of 3-29 where used 3-29 ROWCOUNT option, IQ SET 1-17 Rows order returned in 2-41 Rows, table duplicate 4-6

Q
Qualifying names 1-13, 2-9 Quantied comparison predicate 2-24 quarter date part 3-29 Queries ad hoc 2-1 calculations in 2-26 creating 2-8 denition 2-1 enabling optimizer for joins 4-22 increasing speed 2-16, 4-28

Index-8

Sybase IQ Version 11.2.x

Row value constructors 2-11 RTRIM string function 3-33

S
Scalar expressions subqueries and 3-1 Scale denition 2-4 Search conditions See also Predicates denition 2-22 SQL92 compliance 2-24 syntax 2-22 second date part 3-26 Security queries and 2-2 setting up 1-4 SELECT command 1-10, 2-9 alias syntax 1-12 and USE command 2-9 prerequisite for 2-9 query expression and 2-8 syntax 2-9 using functions with 3-5 Selections denition 2-8 Select list aggregate functions in 3-8 for subqueries 3-1 HAVING clause and 2-21 numbers 2-37 ORDER BY 2-41 Set functions. See Aggregate functions SHOWIQROWID option, IQ SET 1-17 SHUTDOWN command 1-11 Similar-sounding words. See SOUNDEX string function SIMILAR string function 3-33 SMALLINT datatype Sybase IQ 2-3 some predicate 2-17 Sorting query results 2-37 ascending order 2-39

by arithmetic expression 2-39 by function argument 2-39 descending order 2-39 SOUNDEX string function 3-33, 3-35 Spaces in comparisons 2-27 SQL commands issuing 1-6 SQL Server datatypes compatibility 2-7 Square brackets [ ] in SQL statements xvi ss. See second date part 3-26 Standards compliance 1-12, 1-13, 2-1, 3-22, 3-24, 3-26, 3-29, 4-11, 4-16, 4-27, 4-28 Stored procedures setting options within 1-13 String functions 3-31 Strings concatenation 2-25 literal 3-14 operations 3-34 STRING string function 3-33 Style characters 3-11 Subqueries 3-1 aggregate functions in 3-2 comparison predicates 2-26 correlated 3-3 denition 3-1 degree 2-27 degree in IN predicate 3-1 EXISTS predicate 2-33 IN predicate 2-28 nesting 3-5 non-correlated 3-2 parentheses and 3-1 select lists for 3-1 WHERE clause 2-16 SUBSTRING string function 3-33 SUM function 3-7 SUSER_ID function 3-36 SUSER_NAME function 3-36 Sybase IQ

Sybase IQ Query Guide

Index-9

Sybase IQ Version 11.2.x

architecture overview 1-2 commands list of 1-8 connecting to 1-5 documentation for 1-4 installing 1-4 invoking 1-6 Open Server 1-2 Sybase IQ datatypes 2-3 CHAR 2-3 DATE 2-4 DATETIME 2-4 INT 2-3 INTEGER 2-3 REAL 2-4 SMALLINT 2-3 V ARCHAR 2-3 Sybase IQ Open Server connecting to 1-5 installing 1-4 Sybase IQ SQL Statements 1-8 System tables querying 2-2

TRIM string function 3-33 Truncating output 3-18

U
UINT datatype 2-3 UNION operations corresponding clause 4-28 denition 2-8 into clause 4-28 mismatching datatypes in 4-28 query expression and 2-8 unique predicate 2-24 Unsupported datatype conversions 2-7 UPPER string function 3-33 us_english language weekdays setting 3-28 USE command 1-7, 1-11 and SELECT command 2-9 user expression 2-26

V
Value expressions denition 2-25 degree 2-27 Transact-SQL extensions supported 2-25 V ARCHAR datatype Sybase IQ 2-3 Variable width characters 3-12 Views creating 4-30 dening 4-32 dropping 4-32 illustration 4-29 security 4-30

T
Table expressions components 2-12 in FROM clause 2-12 Tables Cartesian product of 4-3 correlation names 4-6 joining more than two 4-8 location of stored data 1-3 multiple in FROM clause 2-13 names, in joins 4-6 qualifying names 2-9 Time arithmetic 2-26 Timestamps 2-26 Time zones 2-26 Trace output for joins 4-22 Triggers setting options within 1-13

W
week date part 3-29 weekday date part 3-26 WHERE clause 1-11, 2-14

restrictions 2-16

Index-10

Sybase IQ Version 11.2.x

SQL92 compliance 2-17 Transact-SQL compliance 2-17 Wildcards as literals 2-31 escape characters for 2-30 LIKE 2-30 wk. See week date part 3-29 Words, nding similar-sounding 3-35

Y
year date part 3-25 yy. See year date part 3-25

Sybase IQ Query Guide

Index-11

Sybase IQ Version 11.2.x

Index-12

You might also like