SQL Functions

Total Page:16

File Type:pdf, Size:1020Kb

SQL Functions SQLSQL BasicsBasics PartPart IIII JonathanJonathan MillerMiller LearningLearning SQLSQL SeriesSeries 1 ItemsItems ToTo bebe CoveredCovered Review of SQL Basics I Join Types Inner & Outer Joins Self-Joins Working With Multiple Queries UNION, INTERSECT, MINUS Subqueries & Correlated Subqueries EXISTS & NOT EXISTS Functions Group String Date Number Participants Questions & Answers (hopefully!) 2 ReviewReview ofof SQLSQL BasicsBasics II StructureStructure ofof aa SQLSQL StatementStatement SELECTSELECT column(scolumn(s)) FROMFROM table(stable(s)) WHEREWHERE condition(scondition(s)) ORDERORDER BYBY column(scolumn(s)) OptionalOptional ElementsElements 3 CartesianCartesian // SimpleSimple JoinJoin SELECT mo_id, poc, parameter_desc FROM monitors, parameters MONITORS PARAMETERS MO_ID SI_SI_ID PA_PARAMETER_CODE POC Parameter_Code Parameter_Desc 1 1 44201 1 44201 Ozone 2 1 42101 1 3 1 42101 2 42101 CO 4 2 81102 1 42401 SO2 5 2 44201 1 81102 PM10 6 3 42401 1 4 PrimaryPrimary && ForeignForeign KeysKeys PrimaryPrimary KeyKey (s)(s) ColumnsColumns onon aa TableTable thatthat UniquelyUniquely IdentifyIdentify aa RecordRecord onon thethe TableTable CanCan bebe composedcomposed ofof 11 oror moremore columnscolumns ForeignForeign KeyKey (s)(s) ColumnColumn onon aa tabletable thatthat referencesreferences thethe PrimaryPrimary KeyKey ofof anotheranother TableTable CanCan bebe composedcomposed ofof oneone oror moremore columnscolumns 5 InnerInner JoinJoin BetweenBetween 22 TablesTables SELECT mo_id, poc, parameter_desc FROM monitors, parameters WHERE pa_parameter_code = parameter_code MONITORS PARAMETERS MO_ID SI_SI_ID PA_PARAMETER_CODE POC Parameter_Code Parameter_Desc 1 1 44201 1 44201 Ozone 2 1 42101 1 3 1 42101 2 42101 CO 4 2 81102 1 42401 SO2 5 2 44201 1 81102 PM10 6 3 424016 1 JoiningJoining TablesTables TogetherTogether JoinsJoins BetweenBetween TablesTables areare UsuallyUsually BasedBased onon PrimaryPrimary // ForeignForeign KeysKeys MakeMake SureSure JoinsJoins BetweenBetween AllAll TablesTables inin thethe FROMFROM ClauseClause ExistExist ListList JoinsJoins BetweenBetween TablesTables BeforeBefore OtherOther SelectionSelection ElementsElements 7 AliasesAliases ““ShorthandShorthand”” forfor TableTable oror ColumnColumn ReferencesReferences SELECTSELECT AliasesAliases AppearAppear asas ColumnColumn HeadersHeaders inin thethe OutputOutput AliasesAliases CannotCannot bebe KeywordsKeywords (SELECT,(SELECT, FROM,FROM, WHERE,WHERE, etc)etc) 8 JoinJoin TypesTypes andand PuttingPutting MultipleMultiple SQLSQL SelectSelect StatementsStatements TogetherTogether QUALIFIER_ SITES RAW_DATA DETAILS MONITOR_ MONITORS PROTOCOLS 9 JoinJoin TypesTypes SimpleSimple Join:Join: No links made between multiple tables RESULT: Cartesian Product InnerInner JoinJoin TABLE1.Foreign Key = TABLE2.Primary Key RESULT: 1 record for each match between the 2 tables OuterOuter JoinJoin TABLE1.Foreign Key = TABLE2.Primary Key(+) RESULT: 1 record for each match between the 2 tables AND 1 record for each where the record only exists in TABLE1 10 jm1 OuterOuter JoinsJoins PlacePlace aa ““(+)(+)”” NextNext toto thethe ColumnColumn NameName inin thethe WHEREWHERE clauseclause ofof thethe SHORTER tabletable WhereWhere toto Use:Use: WhenWhen youyou havehave nullnull valuesvalues inin aa columncolumn thatthat youyou areare joiningjoining onon WhenWhen aa parentparent recordrecord maymay notnot havehave aa childchild recordrecord AA TableTable CanCan OnlyOnly BeBe OuterOuter JoinedJoined toto OneOne OtherOther TableTable withinwithin aa GivenGiven QueryQuery 11 OuterOuter JoinJoin ExamplesExamples 12 SelfSelf JoinsJoins Parent Record A Parent Record B Parent Record C Parent Record D 13 WhatWhat isis ItIt SpecialSpecial CaseCase ofof anan InnerInner JoinJoin UseUse WhenWhen YouYou needneed ““RowsRows”” ofof aa ChildChild RecordRecord toto AppearAppear asas ““ColumnsColumns”” SpecifySpecify thethe SameSame TableTable MultipleMultiple TimesTimes inin thethe ““FROMFROM”” ClauseClause GiveGive EachEach InstanceInstance anan AliasAlias InIn thethe ““WHEREWHERE”” Clause,Clause, SpecifySpecify thethe SpecificSpecific ValueValue DesiredDesired 14 SelfSelf JoinJoin ExampleExample 15 Union,Union, Intersection,Intersection, MinusMinus A B C 16 WhatWhat DoesDoes itit Do?Do? ProcessesProcesses thethe ResultsResults ofof SeparateSeparate QueriesQueries IntoInto aa SingleSingle ReturnReturn UNIONUNION:: EverythingEverything fromfrom QueryQuery 11 ++ EverythingEverything fromfrom QueryQuery 22 INTERSECTION:INTERSECTION: OnlyOnly recordsrecords wherewhere thethe resultsresults betweenbetween QueryQuery 11 andand QueryQuery 22 areare thethe samesame MINUS:MINUS: EverythingEverything fromfrom QueryQuery 11 –– MatchingMatching RecordsRecords fromfrom QueryQuery 22 17 WhatWhat WouldWould bebe Returned?Returned? 132 A 5 B 4 6 QUESTION: C ANSWER: 1. A UNION B 7 1, 2, 3, 4, 5, 6 2. A MINUS B 1, 4 3. A INTERSECT (B MINUS C) 2 4. C UNION (B INTERSECT A) 2, 4, 5, 6,18 7 RulesRules forfor TheseThese QueriesQueries EachEach QueryQuery MustMust ContainContain thethe samesame NumberNumber ofof andand TypeType ofof DataData ElementsElements Select arithmetic_mean From Annual_Summaries Union Select max_value From Summary_Maximums OnlyOnly UniqueUnique OccurrencesOccurrences ofof thethe RecordsRecords willwill bebe RetunedRetuned UnlessUnless youyou SpecifySpecify thethe ““ALLALL”” KeywordKeyword SELECT ALL arithmetic_mean FROM Annual_Summaries Union SELECT max_value FROM Summary_Maximums IfIf youyou wantwant thethe DataData Sorted,Sorted, MustMust bebe ReferencedReferenced byby ColumnColumn PositionPosition 19 UNION,UNION, INTERSECT,INTERSECT, MINUSMINUS ExamplesExamples 20 SubqueriesSubqueries && CorrelatedCorrelated SubqueriesSubqueries 21 SubqueriesSubqueries AA SubquerySubquery isis SimplySimply aa QueryQuery WithinWithin AnotherAnother QueryQuery Used as a Filtering Mechanism Additional Queries Appear in the WHERE Clause Can be Nested up to 16 Levels AA CorrelatedCorrelated SubquerySubquery isis aa SubquerySubquery WhenWhen thethe 22nd QueryQuery ReferencesReferences aa columncolumn FromFrom thethe PrimaryPrimary QueryQuery 22 SubquerySubquery ExamplesExamples 23 ExistsExists AndAnd NOTNOT EXISTSEXISTS 24 EXISTSEXISTS andand NOTNOT EXISTSEXISTS SpecialSpecial SubquerySubquery UsedUsed inin thethe WHEREWHERE ClauseClause LooksLooks forfor thethe ExistenceExistence ofof ANYANY RecordRecord inin thethe SubquerySubquery CanCan bebe MuchMuch FasterFaster thanthan UsingUsing anan ““ININ”” ClauseClause SinceSince itit OnlyOnly NeedsNeeds toto FindFind 11 RecordRecord toto SatisfySatisfy thethe ConditionCondition 25 EXISTSEXISTS andand NOTNOT EXISTSEXISTS ExampleExample 26 FunctionsFunctions 27 WhatWhat isis aa Function?Function? StoredStored SoftwareSoftware thatthat ManipulatesManipulates SubmittedSubmitted ElementsElements andand ReturnsReturns SomeSome ValueValue MayMay byby aa SQLSQL StandardStandard FunctionFunction (SUBSTR)(SUBSTR) CouldCould bebe ApplicationApplication SpecificSpecific (GET_METHOD)(GET_METHOD) GenerallyGenerally TwoTwo CategoriesCategories CreationCreation ofof NewNew ObjectsObjects FromFrom OldOld OnesOnes DescriptionsDescriptions ofof ObjectsObjects 28 FunctionFunction NotationNotation FUNCTION(parameterFUNCTION(parameter {{datatypedatatype},}, [optional[optional parameters])parameters]) DatatypesDatatypes VARCHAR2VARCHAR2 ((‘‘AppleApple’’,, ‘‘SampleSample TextText **’’,, ‘‘12341234’’)) NUMBERNUMBER (1,(1, 1.03,1.03, --15)15) DATEDATE –– WeWe’’llll talktalk aboutabout thisthis oneone laterlater…… 29 TypesTypes ofof FunctionsFunctions StringString FunctionsFunctions MathematicalMathematical FunctionsFunctions SingleSingle--ValueValue FunctionsFunctions GroupGroup--ValueValue FunctionsFunctions ListList FunctionsFunctions ConversionConversion // TransformationTransformation FunctionsFunctions DateDate FunctionsFunctions 30 WhereWhere CanCan II UseUse Functions?Functions? SELECTSELECT StatementStatement SELECTSELECT INITCAP(agency_descINITCAP(agency_desc)) FROMFROM agenciesagencies WHEREWHERE StatementStatement SELECT * FROM sites WHERE SUBSTR(lut_land_use_type, 1) = ‘MOBILE’ 31 DUALDUAL TableTable RealReal OracleOracle TableTable WithWith aa SingleSingle RowRow UsedUsed WhenWhen AllAll ElementsElements inin thethe SELECTSELECT andand WHEREWHERE ClausesClauses dodo notnot ReferenceReference AnyAny TablesTables SELECTSELECT ‘‘AA’’ FROMFROM DUALDUAL Result:Result: ““AA”” 32 CommonCommon StringString FunctionsFunctions |||| INITCAP(StringINITCAP(String)) INSTR(StringINSTR(String,, setset [,[, startstart [,[, occurrence]occurrence] ])]) LENGTH(StringLENGTH(String)) LOWER(StringLOWER(String)) // UPPER(StringUPPER(String)) LPAD(String, Length [, ‘set’]) / RPAD(String, Length [, ‘set’]) LTRIM(StringLTRIM(String [,[, ‘‘setset’’])]) // RTRIM(StringRTRIM(String [,[, ‘‘setset’’])]) SUBSTR(StringSUBSTR(String,, StartStart [,count])[,count]) 33 ConcatenateConcatenate (||)(||) GluesGlues twotwo StringsStrings TogetherTogether SELECTSELECT ‘‘GoGo’’ |||| ‘‘ WOLFPACKWOLFPACK’’ FROMFROM DUALDUAL Results:Results:““GoGo WOLFPACKWOLFPACK”” 34 INITCAP,INITCAP, UPPER,UPPER, LOWERLOWER Deals with the Capitalization of Strings INITCAP – Capitalizes first letter of a string as well as after spaces, periods. Lower case for all other letters UPPER – All Upper Case LOWER – All Lower Case SELECT INITCAP(‘gO woLFpack’), UPPER (‘gO woLFpack’), LOWER(‘gO woLFpack’) FROM dual RESULTS: “Go Wolfpack”, “GO WOLFPACK”, “go wolfpack”
Recommended publications
  • Embedded Database Logic
    Embedded Database Logic Lecture #15 Database Systems Andy Pavlo 15-445/15-645 Computer Science Fall 2018 AP Carnegie Mellon Univ. 2 ADMINISTRIVIA Project #3 is due Monday October 19th Project #4 is due Monday December 10th Homework #4 is due Monday November 12th CMU 15-445/645 (Fall 2018) 3 UPCOMING DATABASE EVENTS BlazingDB Tech Talk → Thursday October 25th @ 12pm → CIC - 4th floor (ISTC Panther Hollow Room) Brytlyt Tech Talk → Thursday November 1st @ 12pm → CIC - 4th floor (ISTC Panther Hollow Room) CMU 15-445/645 (Fall 2018) 4 OBSERVATION Until now, we have assumed that all of the logic for an application is located in the application itself. The application has a "conversation" with the DBMS to store/retrieve data. → Protocols: JDBC, ODBC CMU 15-445/645 (Fall 2018) 5 CONVERSATIONAL DATABASE API Application Parser Planner Optimizer BEGIN Query Execution SQL Program Logic SQL Program Logic ⋮ COMMIT CMU 15-445/645 (Fall 2018) 5 CONVERSATIONAL DATABASE API Application Parser Planner Optimizer BEGIN Query Execution SQL Program Logic SQL Program Logic ⋮ COMMIT CMU 15-445/645 (Fall 2018) 5 CONVERSATIONAL DATABASE API Application Parser Planner Optimizer BEGIN Query Execution SQL Program Logic SQL Program Logic ⋮ COMMIT CMU 15-445/645 (Fall 2018) 5 CONVERSATIONAL DATABASE API Application Parser Planner Optimizer BEGIN Query Execution SQL Program Logic SQL Program Logic ⋮ COMMIT CMU 15-445/645 (Fall 2018) 5 CONVERSATIONAL DATABASE API Application Parser Planner Optimizer BEGIN Query Execution SQL Program Logic SQL Program Logic ⋮ COMMIT CMU 15-445/645 (Fall 2018) 6 EMBEDDED DATABASE LOGIC Move application logic into the DBMS to avoid multiple network round-trips.
    [Show full text]
  • Aggregate Order by Clause
    Aggregate Order By Clause Dialectal Bud elucidated Tuesdays. Nealy vulgarizes his jockos resell unplausibly or instantly after Clarke hurrah and court-martial stalwartly, stanchable and jellied. Invertebrate and cannabic Benji often minstrels some relator some or reactivates needfully. The default order is ascending. Have exactly match this assigned stream aggregate functions, not work around with security software development platform on a calculation. We use cookies to ensure that we give you the best experience on our website. Result output occurs within the minimum time interval of timer resolution. It is not counted using a table as i have group as a query is faster count of getting your browser. Let us explore it further in the next section. If red is enabled, when business volume where data the sort reaches the specified number of bytes, the collected data is sorted and dumped into these temporary file. Kris has written hundreds of blog articles and many online courses. Divides the result set clock the complain of groups specified as an argument to the function. Threat and leaves only return data by order specified, a human agents. However, this method may not scale useful in situations where thousands of concurrent transactions are initiating updates to derive same data table. Did you need not performed using? If blue could step me first what is vexing you, anyone can try to explain it part. It returns all employees to database, and produces no statements require complex string manipulation and. Solve all tasks to sort to happen next lesson. Execute every following query access GROUP BY union to calculate these values.
    [Show full text]
  • Oracle Rdb™ SQL Reference Manual Volume 4
    Oracle Rdb™ SQL Reference Manual Volume 4 Release 7.3.2.0 for HP OpenVMS Industry Standard 64 for Integrity Servers and OpenVMS Alpha operating systems August 2016 ® SQL Reference Manual, Volume 4 Release 7.3.2.0 for HP OpenVMS Industry Standard 64 for Integrity Servers and OpenVMS Alpha operating systems Copyright © 1987, 2016 Oracle Corporation. All rights reserved. Primary Author: Rdb Engineering and Documentation group This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007).
    [Show full text]
  • SQL from Wikipedia, the Free Encyclopedia Jump To: Navigation
    SQL From Wikipedia, the free encyclopedia Jump to: navigation, search This article is about the database language. For the airport with IATA code SQL, see San Carlos Airport. SQL Paradigm Multi-paradigm Appeared in 1974 Designed by Donald D. Chamberlin Raymond F. Boyce Developer IBM Stable release SQL:2008 (2008) Typing discipline Static, strong Major implementations Many Dialects SQL-86, SQL-89, SQL-92, SQL:1999, SQL:2003, SQL:2008 Influenced by Datalog Influenced Agena, CQL, LINQ, Windows PowerShell OS Cross-platform SQL (officially pronounced /ˌɛskjuːˈɛl/ like "S-Q-L" but is often pronounced / ˈsiːkwəl/ like "Sequel"),[1] often referred to as Structured Query Language,[2] [3] is a database computer language designed for managing data in relational database management systems (RDBMS), and originally based upon relational algebra. Its scope includes data insert, query, update and delete, schema creation and modification, and data access control. SQL was one of the first languages for Edgar F. Codd's relational model in his influential 1970 paper, "A Relational Model of Data for Large Shared Data Banks"[4] and became the most widely used language for relational databases.[2][5] Contents [hide] * 1 History * 2 Language elements o 2.1 Queries + 2.1.1 Null and three-valued logic (3VL) o 2.2 Data manipulation o 2.3 Transaction controls o 2.4 Data definition o 2.5 Data types + 2.5.1 Character strings + 2.5.2 Bit strings + 2.5.3 Numbers + 2.5.4 Date and time o 2.6 Data control o 2.7 Procedural extensions * 3 Criticisms of SQL o 3.1 Cross-vendor portability * 4 Standardization o 4.1 Standard structure * 5 Alternatives to SQL * 6 See also * 7 References * 8 External links [edit] History SQL was developed at IBM by Donald D.
    [Show full text]
  • Sql Server Truncate All Tables in Database Logging
    Sql Server Truncate All Tables In Database Curbless Lorenzo naphthalised dissimilarly, he divinised his scavengers very wham. Embryologic and systematized Allan never engages his avarices! Sometimes belted Willi stenciled her Layla murderously, but direst Lucien hearkens retroactively or rebuilds voetstoots. Sp_refreshview in sql server truncate all the records in the db truncate all triggers from one way to remove all of a delete clause. Challenges so how to sql server truncate all database platform supports information_schema is this worked for. Identities of their database server truncate all tables at once we get involved, a business process modeler bpm tool micro. Affect my tables, all tables in my blogs is going to find still getting an aos server table or build my own and sql. Referred in sql truncate all database backup, but we can an account. Control and sql truncate tables database in a database and allocated space than the truncate the sql truncate a little late but you can use a number of the server? Exactly what query and server truncate all tables in database by a script? Tell sql databases with sql server truncate tables in three simple use a database engineer certified by a specific comment. Freelancing work or a sql truncate all tables database with lots of the tables referenced by anybody that? Work or window and sql server truncate all in database backup, you are used to install we can perform truncate all the tables instead of a test. Client has to sql server truncate database and the command because it might be reset it requires to complete overview of columns in microsoft analysis services.
    [Show full text]
  • Overview of SQL:2003
    OverviewOverview ofof SQL:2003SQL:2003 Krishna Kulkarni Silicon Valley Laboratory IBM Corporation, San Jose 2003-11-06 1 OutlineOutline ofof thethe talktalk Overview of SQL-2003 New features in SQL/Framework New features in SQL/Foundation New features in SQL/CLI New features in SQL/PSM New features in SQL/MED New features in SQL/OLB New features in SQL/Schemata New features in SQL/JRT Brief overview of SQL/XML 2 SQL:2003SQL:2003 Replacement for the current standard, SQL:1999. FCD Editing completed in January 2003. New International Standard expected by December 2003. Bug fixes and enhancements to all 8 parts of SQL:1999. One new part (SQL/XML). No changes to conformance requirements - Products conforming to Core SQL:1999 should conform automatically to Core SQL:2003. 3 SQL:2003SQL:2003 (contd.)(contd.) Structured as 9 parts: Part 1: SQL/Framework Part 2: SQL/Foundation Part 3: SQL/CLI (Call-Level Interface) Part 4: SQL/PSM (Persistent Stored Modules) Part 9: SQL/MED (Management of External Data) Part 10: SQL/OLB (Object Language Binding) Part 11: SQL/Schemata Part 13: SQL/JRT (Java Routines and Types) Part 14: SQL/XML Parts 5, 6, 7, 8, and 12 do not exist 4 PartPart 1:1: SQL/FrameworkSQL/Framework Structure of the standard and relationship between various parts Common definitions and concepts Conformance requirements statement Updates in SQL:2003/Framework reflect updates in all other parts. 5 PartPart 2:2: SQL/FoundationSQL/Foundation The largest and the most important part Specifies the "core" language SQL:2003/Foundation includes all of SQL:1999/Foundation (with lots of corrections) and plus a number of new features Predefined data types Type constructors DDL (data definition language) for creating, altering, and dropping various persistent objects including tables, views, user-defined types, and SQL-invoked routines.
    [Show full text]
  • Real Federation Database System Leveraging Postgresql FDW
    PGCon 2011 May 19, 2011 Real Federation Database System leveraging PostgreSQL FDW Yotaro Nakayama Technology Research & Innovation Nihon Unisys, Ltd. The PostgreSQL Conference 2011 ▍Motivation for the Federation Database Motivation Data Integration Solution view point ►Data Integration and Information Integration are hot topics in these days. ►Requirement of information integration has increased in recent year. Technical view point ►Study of Distributed Database has long history and the background of related technology of Distributed Database has changed and improved. And now a days, the data moves from local storage to cloud. So, It may be worth rethinking the technology. The PostgreSQL Conference 2011 1 All Rights Reserved,Copyright © 2011 Nihon Unisys, Ltd. ▍Topics 1. Introduction - Federation Database System as Virtual Data Integration Platform 2. Implementation of Federation Database with PostgreSQL FDW ► Foreign Data Wrapper Enhancement ► Federated Query Optimization 3. Use Case of Federation Database Example of Use Case and expansion of FDW 4. Result and Conclusion The PostgreSQL Conference 2011 2 All Rights Reserved,Copyright © 2011 Nihon Unisys, Ltd. ▍Topics 1. Introduction - Federation Database System as Virtual Data Integration Platform 2. Implementation of Federation Database with PostgreSQL FDW ► Foreign Data Wrapper Enhancement ► Federated Query Optimization 3. Use Case of Federation Database Example of Use Case and expansion of FDW 4. Result and Conclusion The PostgreSQL Conference 2011 3 All Rights Reserved,Copyright ©
    [Show full text]
  • SQL Commands
    Computer Science (083) _ 7th Week Assignment with Notes Chapter Name: - MySQL Revision tour Class: -12th SQL Commands o SQL commands are instructions. It is used to communicate with the database. It is also used to perform specific tasks, functions, and queries of data. o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set permission for users. 1. Data Definition Language (DDL) o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc. o All the command of DDL are auto-committed that means it permanently save all the changes in the database. Here are some commands that come under DDL: o CREATE o ALTER o DROP o TRUNCATE CREATE :- It is used to create a new table in the database. Syntax: CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]); Example: CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DAT E); DROP: It is used to delete both the structure and record stored in the table. Syntax:- DROP TABLE ; Example:- DROP TABLE EMPLOYEE; ALTER: It is used to alter the structure of the database. This change could be either to modify the characteristics of an existing attribute or probably to add a new attribute. Syntax: To add a new column in the table ALTER TABLE table_name ADD column_name COLUMN-definition; To modify existing column in the table: ALTER TABLE MODIFY(COLUMN DEFINITION....); EXAMPLE ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20)); ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20)); TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
    [Show full text]
  • SQL Views for Medical Billing
    SQL Views for Cortex Medical Billing SQL Views To execute a view in the SQL Query Analyzer window “Select * from view_name”. To narrow the results of a view you may add a WHERE clause. The column named in the WHERE clause must match the column name in the view in the following order: 1. A column name that follows the view name 2. A column name in the SELECT statement of the view To find out the name of a column in a view, double click on the view name in Enterprise Manager. EXAMPLE: CREATE VIEW ClientPayment_view( ClPaymentServiceNumber,ClPaymentAmount ) AS SELECT ClientPayment.ClientServiceNumber, SUM(ClientPayment.Amount) FROM ClientPayment GROUP BY ClientPayment.ClientServiceNumber In this example, in order to execute a SQL query with a WHERE clause on the ClientPayment_view you must use the column name “ClPaymentServiceNumber” or “ClPaymentAmount”. If the column names (ClPaymentServiceNumber,ClPaymentAmount) did *NOT* follow the view name you could use the column names in the SELECT statement (ClientServiceNumber, Amount). Example SELECT statement with WHERE clause: “ CONFIDENTIAL Page 1 of 4 SQL Views for Cortex Medical Billing SELECT * FROM ClientPayment_view WHERE ClPaymentServiceNumber = '0000045'” When writing a view where you only want one record returned to sum a field like amount (i.e., SUM(Amount)) you cannot return any other columns from the table where the data will differ, like EnteredDate, because the query is forced to return each record separately, it can no longer combine them. View Name Crystal Report Join Returned
    [Show full text]
  • Authorized Data Truncation
    Dealing with SQL Width in the Progress OpenEdge RDBMS: AUTHORIZED DATA TRUNCATION As a continuation of our efforts to deliver extensive SQL enhancements to Progress® OpenEdge® 11, customers will now find two new features to help better manage issues that may arise due to SQL width. Data that extends beyond its SQL width definition can cause query failures and limit the ability to obtain complete result sets. To assist database administrators in addressing the issue of SQL width, we are presenting as a series, two complementary technical whitepapers, each detailing a specific solution: Dealing with SQL Width in the Progress OpenEdge RDBMS: Authorized Data Truncation (ADT), and Dealing with SQL Width in the Progress OpenEdge RDBMS: Autonomous Schema Update (ASU). OVERVIEW Progress OpenEdge 11.5.1 contains a new SQL feature called Authorized Data Truncation.* This feature helps overcome the SQL width problem that is encountered when database column values are larger than the column’s size as defined in SQL. Authorized Data Truncation can prevent queries from failing when the large column values are read. By default, if the width of the column data being operated on in a query exceeds the defined width of the column, SQL returns an error, and as a result the query fails. If Authorized Data Truncation is enabled, SQL will instead truncate the large value down to the defined size. This truncation is acceptable as a temporary workaround to help applications succeed. Truncation changes data values significantly. Users will be able to see that the values were truncated, as Data Truncation optionally logs the truncation.
    [Show full text]
  • Efficient Processing of Window Functions in Analytical SQL Queries
    Efficient Processing of Window Functions in Analytical SQL Queries Viktor Leis Kan Kundhikanjana Technische Universitat¨ Munchen¨ Technische Universitat¨ Munchen¨ [email protected] [email protected] Alfons Kemper Thomas Neumann Technische Universitat¨ Munchen¨ Technische Universitat¨ Munchen¨ [email protected] [email protected] ABSTRACT select location, time, value, abs(value- (avg(value) over w))/(stddev(value) over w) Window functions, also known as analytic OLAP functions, have from measurement been part of the SQL standard for more than a decade and are now a window w as ( widely-used feature. Window functions allow to elegantly express partition by location many useful query types including time series analysis, ranking, order by time percentiles, moving averages, and cumulative sums. Formulating range between 5 preceding and 5 following) such queries in plain SQL-92 is usually both cumbersome and in- efficient. The query normalizes each measurement by subtracting the aver- Despite being supported by all major database systems, there age and dividing by the standard deviation. Both aggregates are have been few publications that describe how to implement an effi- computed over a window of 5 time units around the time of the cient relational window operator. This work aims at filling this gap measurement and at the same location. Without window functions, by presenting an efficient and general algorithm for the window it is possible to state the query as follows: operator. Our algorithm is optimized for high-performance main- memory database systems and has excellent performance on mod- select location, time, value, abs(value- ern multi-core CPUs. We show how to fully parallelize all phases (select avg(value) of the operator in order to effectively scale for arbitrary input dis- from measurement m2 tributions.
    [Show full text]
  • PROC SQL for PROC SUMMARY Stalwarts Christianna Williams Phd, Chapel Hill, NC
    SESUG Paper 219-2019 PROC SQL for PROC SUMMARY Stalwarts Christianna Williams PhD, Chapel Hill, NC ABSTRACT One of the fascinating features of SAS® is that the software often provides multiple ways to accomplish the same task. A perfect example of this is the aggregation and summarization of data across multiple rows or BY groups of interest. These groupings can be study participants, time periods, geographical areas, or really just about any type of discrete classification that one desires. While many SAS programmers may be accustomed to accomplishing these aggregation tasks with PROC SUMMARY (or equivalently, PROC MEANS), PROC SQL can also do a bang-up job of aggregation – often with less code and fewer steps. This step-by-step paper explains how to use PROC SQL for a variety of summarization and aggregation tasks. It uses a series of concrete, task-oriented examples to do so. For each example, both the PROC SUMMARY method and the PROC SQL method will be presented, along with discussion of pros and cons of each approach. Thus, the reader familiar with either technique can learn a new strategy that may have benefits in certain circumstances. The presentation format will be similar to that used in the author’s previous paper, “PROC SQL for DATA Step Die-Hards”. INTRODUCTION Descriptive analytic and data manipulation tasks often call for aggregating or summarizing data in some way, whether it is calculating means, finding minimum or maximum values or simply counting rows within groupings of interest. Anyone who has been working with SAS for more than about two weeks has probably learned that there are nearly always about a half dozen different methods for accomplishing any type of data manipulation in SAS (and often a score of user group papers on these methods ) and summarizing data is no exception.
    [Show full text]