Databases Lab 5 Further Select Statements. Functions in SQL There are many types of functions provided. The ones that are used most are: –Date and Time.

Slides:



Advertisements
Similar presentations
Return values.
Advertisements

Copyright  Oracle Corporation, All rights reserved. 2 Single-Row Functions.
Copyright © 2007, Oracle. All rights reserved Using Single-Row Functions to Customize Output Modified: October 21, 2014.
CS 3630 Database Design and Implementation. SQL Query Clause Select and From Select * From booking; select hotel_no, guest_no, room_no from booking; select.
Let’s try Oracle. Accessing Oracle The Oracle system, like the SQL Server system, is client / server. For SQL Server, –the client is the Query Analyser.
Structured Query Language and its components. SQL SQL stands for Structured Query Language. There is a standard SQL called the American National Standards.
Functions and string manipulation Lab 2 Week 2. Date functions Commonly used date functions are: –sysdate –next_day –add_months –last_day –months_between.
JOINS cis 407 Subqueries Correlated Subqueries Exists operator performance considerations Examples.
Introduction to Oracle9i: SQL1 Selected Single-Row Functions.
Databases Week 1, lab 2 Simple selects. About the environment We are using SQL Server for the moment. The server we are using is: –Cian.student.comp.dit.ie.
1 Databases. 2 Simple selects The full syntax of the SELECT statement is complex, but the main clauses can be summarized as: SELECT select_list [INTO.
Databases Tutorial 2 Further Select Statements. Objectives for Week Data types Sort retrieved data Formatting output.
WRITING BASIC SQL SELECT STATEMENTS Lecture 7 1. Outlines  SQL SELECT statement  Capabilities of SELECT statements  Basic SELECT statement  Selecting.
Using Single-Row Functions to Customize Output
Lecture 6 29/1/15. Number functions Number functions take numbers as input, change them, and output the results as numbers. 2.
Single-Row Functions. SQL Functions Functions are a very powerful feature of SQL and can be used to do the following: Perform calculations on data Modify.
FUNCTIONS AND STORED PROCEDURES & FUNCTIONS AND PROTECTING A DB AND PHP (Chapters 9, 15, 18)
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
Chapter 5 Selected Single-Row Functions. Chapter Objectives  Use the UPPER, LOWER, and INITCAP functions to change the case of field values and character.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
SINGLE-ROW FUNCTIONS Lecture 9. SQL Functions Functions are very powerful feature of SQL and can be used to do the following:  Perform a calculation.
Single Row Functions Week 2. Objectives –Describe types of single row functions in SQL –Describe and use character, number, date, general and conversion.
Oracle 11g: SQL Chapter 10 Selected Single-Row Functions.
LECTURE 1 INTRODUCTION TO PL/SQL Tasneem Ghnaimat.
SQL Oracle PL/SQL. Select SELECT column1, column2,...columnN FROM table_name WHERE condition; SELECT column1, column2,...columnN FROM table_name WHERE.
Chapter 3 Selected Single-Row Functions and Advanced DML & DDL.
A Guide to SQL, Seventh Edition. Objectives Understand how to use functions in queries Use the UPPER and LOWER functions with character data Use the ROUND.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
EXPRESSION Transformation. Introduction ►Transformations help to transform the source data according to the requirements of target system and it ensures.
In this session, you will learn to: Use functions to customize the result set Summarize and group data Objectives.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
IFS Intro to Data Management Chapter 5 Getting More Than Simple Columns.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
Conversion Functions.
Single Row Functions. Objectives –Use character, number, and date functions –Use conversion functions –Describe types of single row functions in SQL.
Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join.
INTRODUCTION TO SQL Chapter SELECT * FROM teacher WHERE INSTR (subject_id, ‘&1’)= 4 AND LOWER (subject_id) LIKE ‘HST%’ ; When prompted for the.
3 Copyright © 2009, Oracle. All rights reserved. Using Single-Row Functions to Customize Output.
SQL Functions. SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. These functions are use full.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Introduction to Functions – Single Row Functions.
Built-in SQL Functions. 2 Type of Functions Character Functions returning character values returning numeric values Numeric Functions Date Functions Conversion.
1 Copyright © Oracle Corporation, All rights reserved. Writing Basic SQL SELECT Statements.
IMS 4212: Intro to Multi-Table SELECT Statements 1 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements—Topics.
4/2/16. Ltrim() is used to remove leading occurrences of characters. If we don’t specify a character, Oracle will remove leading spaces. For example Running.
Lab 3: Single-row Functions College of Information Technology, Universiti Tenaga Nasional 1 CISB224 02A, 02B Semester I, 2009/2010.
1 Inside Module 8 Extracting Data Page n Using the Extract command2 n Coercion3 n $-functions4 n Extract from a table7.
College of Information Technology, Universiti Tenaga Nasional1 Lab 2: Single-row Functions CISB224 01A CCSB244 01A Semester I, 2008/2009.
Gollis University Faculty of Computer Engineering Chapter Five: Retrieval, Functions Instructor: Mukhtar M Ali “Hakaale” BCS.
3 Copyright © 2009, Oracle. All rights reserved. Using Single-Row Functions to Customize Output.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
Single Row Functions Part I Week 2. Objectives –Describe types of single row functions in SQL –Describe and use character, number and date SQL functions.
Creating Database Objects
CS 3630 Database Design and Implementation
In this session, you will learn to:
Open Source Server Side Scripting MySQL Functions
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL
Using Structured Query Language (SQL) (continued)
Built-in Functions. Usage of Wildcards
SQL DATE/TIME FUNCTIONS
SQL Text Manipulation Farrokh Alemi, Ph.D.
Date Functions Farrokh Alemi, Ph.D.
VBScript Session 10.
Inside Module 8 Extracting Data Page Using the Extract command 2
Lecture 5 SQL FUNCTIONS.
Lab 3: Single-row Functions
Database Management System
Creating Database Objects
Introduction to SQL Server and the Structure Query Language
Presentation transcript:

Databases Lab 5 Further Select Statements

Functions in SQL There are many types of functions provided. The ones that are used most are: –Date and Time functions –Mathematical functions –String functions There follows a list of all functions in these categories. We will practice only the most popularly used.

All about dates Dates are relative – i.e. the date and time are the same function. The current date and time depends on where you are in the world. When you show the standard datetime, it looks like this:

Date display functions The functions day, month and year return the fields in the date that show these things: SELECT day(orderdate) from orders where orderid = Returns the day of the month in the order date field. Note, it does not have a column name. Only columns that are returned in their raw state have column names. (See next slide)

Example ‘day’ function

Example date, day, month and year

Getting the current date This is a function – we are selecting from the computer on which we are running the query, not from a table. GetDate returns the current date. As the current date is relative, this function is non deterministic. Select getdate() returns the current date and time.

The datepart function The datepart function can take as a first parameter either ‘day’, ‘month’, ‘year’, ‘quarter’, ‘dayofyear’, ‘week’, ‘weekday’, ‘hour’, ‘minute’, ‘second’, ‘millisecond’. –There are various abbreviations you can use – see the Transact SQL help.

Example query

Adding to dates DateAdd adds a number of dateparts to a date DATEADD ( datepart, number, date ) E.g. to add 4 days to the orderdate:

Subtracting from a date Note: to subtract 4 days from a date, use the DATEADD function and add a negative number of days: select orderdate, dateadd(day, -4, orderdate) from orders

Showing date differences DateDiff returns the difference between two dates in the datepart DATEDIFF ( datepart, startdate, enddate ) –E.g. Show the order date, the required date and the difference in weeks. select orderdate, requireddate, datediff(week, orderdate, requireddate) from orders order by datediff(week, orderdate, requireddate)

To put a name on a column Transact SQL allows the use of the ‘as’ clause to give a name to a column. –Unitprice as Price or –UnitPrice as ‘Unit Price’ This can be used on any column, but is especially useful in a derived column. New columns can be derived from existing fields: E.g. the value of an item in stock is the number in stock by the unit price.

Naming sample

Mathematical Functions ABS DEGREES RAND ACOS EXP ROUND ASIN FLOOR SIGN ATAN LOG SIN ATN2 LOG10 SQUARE CEILING PI SQRT COS POWER TAN COT RADIANS We will not do any explicit exercises on these today.

String Functions LEN LEFT LOWER UPPER RIGHT LTRIM RTRIM STR DIFFERENCE QUOTENAME REPLICATE STUFF SUBSTRING REVERSE ASCII NCHAR SOUNDEX CHAR PATINDEX SPACE CHARINDEX REPLACE UNICODE

String functions - LEN Len returns the number of characters in a string. E.g. len(name) returns the length of characters in a the field name. Using Northwind, try the following: select categoryName, len(categoryname) from categories

Upper, Lower, L/Rtrim UPPER converts the string to Upper case, LOWER converts it to Lowercase. Try displaying CategoryName from categories in upper and lower case. Strip leading and trailing spaces from –Rtrim strips trailing spaces –Ltrim strips leading spaces.

Taking out part of the field String fields can be manipulated by taking out the left number of characters or the right number of characters. SUBSTRING takes out a specified number of characters from the start. Try: select categoryname, substring( categoryname, 3, 4) from categories

Left and right functionality

Replace Replaces one substring with another:

Cast and CONVERT CAST and CONVERT Explicitly converts an expression of one data type to another. CAST and CONVERT provide similar functionality. This can be used to format output and convert data fields from one format to another

Cast and Convert CAST and CONVERT –Explicitly converts an expression of one data type to another. CAST and CONVERT provide similar functionality. Syntax –Using CAST: –CAST ( expression AS data_type ) –Using CONVERT: –CONVERT ( data_type [ ( length ) ], expression [, style ] )

Date conversion select convert(char(12),getdate(), 3) as TODAY TODAY /01/05 (1 row(s) affected) You can truncate unwanted date parts when converting from datetime or smalldatetime values by using an appropriate char or varchar data type length.

Number conversion When data types are converted with a different number of decimal places, the value is truncated to the most precise digit. –For example, the result of SELECT CAST( AS int) is 10. When data types in which the target data type has fewer decimal points than the source data type are converted, the value is rounded. – For example, the result of CAST( AS money) is $

B. Use CAST with arithmetic operators This example calculates a single column computation (Copies) by dividing the total year- to-date sales (ytd_sales) by the individual book price (price). This result is converted to an int data type after being rounded to the nearest whole number. –USE pubs –GO –SELECT CAST(ROUND(ytd_sales/price, 0) AS int) AS 'Copies' FROM titles GO

C. Use CAST to concatenate This example concatenates noncharacter, nonbinary expressions using the CAST data type conversion function. –USE pubs –GO –SELECT 'The price is ' + CAST(price AS varchar(12)) FROM titles WHERE price > –GO

D. Use CAST for more readable text This example uses CAST in the select list to convert the title column to a char(50) column so the results are more readable. –USE pubs –GO –SELECT CAST(title AS char(50)), ytd_sales FROM titles WHERE type = 'trad_cook' –GO

Exercises Retrieve the system date, using the ‘GetDate’ function. Convert it into char(12) format. Display it using style 3. Now display it using styles 1 through 14, noting the differences. Which of these formats do you think would be most useful in this country and for what purposes?

Exercises (Northwind) To demonstrate the effectiveness of ‘order by’: –Select all from the order details table –Select all from the order details table ordered by product id. –Select all from the order details table in descending product id order.

More exercises Show the order id, the customer id and the day, month and year of the order date, for all orders, in customer id order. Using getdate(), show the current date in every style (3 in the example) from 1 to 14. Display the order date, the shipped date and the difference in days between the two, for all orders that have been shipped (i.e. shippeddate is not null)

Display the order id, the required date, the shipped date where the shipped date is after the required date, the number of days by which it is late, ordered by the number of days by which it is late. Display the orderdate and two weeks after the orderdate for each order that has not been shipped (shippeddate is null).

Exercises Amend the previous exercises to put names on the columns. Format your outputs so that they are easy and pleasant to read.

Achievements Writing Basic SQL Select Statements –[√]List the capabilities of SQL SELECT statements –[ √ ]Execute a basic SELECT statement –[ ]Differentiate between SQL statements and iSQL*Plus commands This is specific to Oracle. Restricting and Sorting Data –[ √] Limit the rows retrieved by a query –[ √] Sort the rows retrieved by a query Single-Row Functions –[ √] Describe various types of functions available in SQL –[ √] Use character, number, and date functions in SELECT statements –[ √] Use conversion functions