Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query



Similar documents
Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Appendix A Practices and Solutions

3.GETTING STARTED WITH ORACLE8i

Oracle SQL. Course Summary. Duration. Objectives

Database Query 1: SQL Basics

Microsoft Access 3: Understanding and Creating Queries

Oracle Database: SQL and PL/SQL Fundamentals

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

Oracle Database: SQL and PL/SQL Fundamentals NEW

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Oracle Database: SQL and PL/SQL Fundamentals

Introduction to Microsoft Jet SQL

Ad Hoc Advanced Table of Contents

Oracle Database 10g: Introduction to SQL

Access Queries (Office 2003)

Oracle Database 12c: Introduction to SQL Ed 1.1

Microsoft Access Lesson 5: Structured Query Language (SQL)

SQL Programming. Student Workbook

SQL. Short introduction

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Programming with SQL

GET DATA FROM MULTIPLE TABLES QUESTIONS

Advanced Query for Query Developers

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

A Brief Introduction to MySQL

Information Systems SQL. Nikolaj Popov

Database Applications Microsoft Access

Click to create a query in Design View. and click the Query Design button in the Queries group to create a new table in Design View.

MOC 20461C: Querying Microsoft SQL Server. Course Overview

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Displaying Data from Multiple Tables

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Chapter 1. Writing Basic. SQL Statements

Financial Data Access with SQL, Excel & VBA

Netezza SQL Class Outline

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

SQL Access to XBRL Historical Data: A Continuous Benchmarking Story. Eric E. Cohen

Key Functions in Oracle SQL

Oracle Database 11g SQL

CONVERSION FUNCTIONS QUESTIONS

Paper An Introduction to SAS PROC SQL Timothy J Harrington, Venturi Partners Consulting, Waukegan, Illinois

CHAPTER 12. SQL Joins. Exam Objectives

Oracle Database 10g: SQL Fundamentals I

Relational Database: Additional Operations on Relations; SQL

A basic create statement for a simple student table would look like the following.

Lab Manual. Databases. Microsoft Access. Peeking into Computer Science Access Lab manual

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

MS Access Lab 2. Topic: Tables

Excel: Introduction to Formulas

SQL Basics. Introduction to Standard Query Language

Oracle/SQL Tutorial 1

PeopleSoft Query Training

Oracle Database: Introduction to SQL

Facebook Twitter YouTube Google Plus Website

Data Mining Extensions (DMX) Reference

Performing Queries Using PROC SQL (1)

SQL SELECT Query: Intermediate

Chapter 1 Overview of the SQL Procedure

Oracle Database: Introduction to SQL

Using SQL Queries in Crystal Reports

Writing Control Structures

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

AN INTRODUCTION TO THE SQL PROCEDURE Chris Yindra, C. Y. Associates

Utility Software II lab 1 Jacek Wiślicki, jacenty@kis.p.lodz.pl original material by Hubert Kołodziejski

Concepts Design Basics Command-line MySQL Security Loophole

MYSQL DATABASE ACCESS WITH PHP

Unit 10: Microsoft Access Queries

Web Development using PHP (WD_PHP) Duration 1.5 months

PL / SQL Basics. Chapter 3

Oracle Database: Introduction to SQL

European Computer Driving Licence

9.1 SAS. SQL Query Window. User s Guide

MICROSOFT ACCESS A. CREATING A DATABASE B. CREATING TABLES IN A DATABASE

Oracle Database: SQL and PL/SQL Fundamentals NEW

FileMaker 13. SQL Reference

A table is a collection of related data entries and it consists of columns and rows.

Database Administration with MySQL

Welcome to the topic on queries in SAP Business One.

Using AND in a Query: Step 1: Open Query Design

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Database Programming with PL/SQL: Learning Objectives

Chapter 5. Microsoft Access

DbSchema Tutorial with Introduction in SQL Databases

Aggregating Data Using Group Functions

C omputer D riving L icence

VB.NET Programming Fundamentals

VBScript Database Tutorial Part 1

David M. Kroenke and David J. Auer Database Processing: Fundamentals, Design and Implementation

Structured Query Language (SQL)

CODESOFT TUTORIAL DOC-OEMCS10-TU-EN-01/01/12

Transcription:

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query Objectives The objective of this lab is to learn the query language of SQL. Outcomes After completing this Lab, students are expected to: Select data from table(s). SELECT Statements Most of the queries on the relational databases use SELECT statements. The SELECT statement can do projection (selecting specific columns), selection (filtering some rows), and join (retrieving result from more than one table). In this lab, we will discuss aliasing, using common operators and single row functions, removing duplicates, filtering, and sorting. 1. Simple Selection The following SELECT statement format that would be referred for the discussed issues: FROM table; Guidelines for SELECT clause: Use * to select all the columns. SELECT * Use list of columns separated by coma to display specific columns. SELECT employees_id, department_id Use expression to do operation using some operators and/or some single-row functions. The following are list of operators: Operator + Addition - Subtraction * Multiplication / Division Concatenation Note: Arithmetic expressions containing a null value evaluate to null. Use the appropriate function described bellow to overcome this issue. The precedence rules also apply. Use parenthesis to change the precedence explicitly.

SELECT last_name, 12*salary*commission_pct ; SELECT employees_id ' is a manager of department ' department_id Some useful single-row functions Functions LOWER(str) UPPER(str) Make all characters in str lower-case or uppercase INITCAP(str) Make first character of each word in str upper-case and the remaining characters lowercase CONCAT(str1, str2) Concatenating str1 and str2 SUBSTR(str, index, Copy a string from str starting from index length) for length characters. LENGTH(str) Find the number of characters on str INSTR(str1, str2) Find the occurrence of str2 on str1. If found return the position else return 0. LPAD(column, length, Generate length characters string, fill with char) char on the left (or right) of column, when the RPAD(column, length, char) length of column is less than the length. REPLACE(str1, str2, str3) Replaces the occurrences of str2 in str1 with str3. ROUND(value, decimal) Rounds value to specified decimal TRUNC(value, decimal) Truncate value to specified decimal MOD(value, divisor) Return reminder of division TO_CHAR(value, 'format') Explicitly convert value (either date or number) to string based on specified format. TO_DATE(str [,'format']) Explicitly convert str to DATE format based on specified format. TO_NUMBER(str Explicitly convert str to number format based [,'format']) on specified format. NVL(val1, val2) NVL2(val1, val2, val3) DECODE(column expression, search1, result1 [, search2, result2,...,] [, default]) Returns val2 if the val1 is NULL Returns val2 if the val1 is NOT NULL, otherwise return val3 Replicates the CASE or IF-THEN-ELSE statements. The function evaluates column or expression, if it equals search1 then returns result1, else if it equals search2 then returns result2, and on, otherwise returns default. Note: A function can be nested within another function. The inner function will be evaluated first, then go outward.

SELECT INITCAP(first_name ' ' last_name) ; SELECT last_name, 12 * salary * NVL(commission_pct, 1) ; SELECT last_name, salary, DECODE (TRUNC(salary/5000, 0), 0, ' Below 5,000', 1, ' 5,000 10,000', 2, ' 10,000 15,000', ' Above 15,000') ; Use DISTINCT clause to remove duplicates result SELECT DISTINCT employees_id, department_id For aliasing, put the new header / column name right after column name or expression. Optionally "As" keyword can be inserted between new and old names. Use double quote to preserve the word case and allow usage of spaces. SELECT INITCAP(first_name ' ' last_name) Full_Name ; SELECT last_name, 12 * salary * NVL(commission_pct, 1) "Annual Income" ; SELECT last_name, salary, DECODE (TRUNC(salary/5000, 0), 0, ' Below 5,000', 1, ' 5,000 10,000', 2, ' 10,000 15,000', ' Above 15,000') AS "Salary Group" ; 2. Conditional Selection SELECT statement can be used to filter selected rows, by use of WHERE clause. It has the format as followed: FROM table [WHERE condition(s)]; The WHERE clause follows the FORM clause. The condition is the valid expression that returns a Boolean value (true/false). Logical operators (OR and AND) could be use to combine the multi Boolean expressions. The NOT operator would negate the following Boolean expression. The condition will evaluate each row on the table. Character strings and date values are enclosed by single quotation marks. Character values are casesensitive, and date values are format-sensitive. The default date format is 'DD-MON-YY'.

Logical Comparison operators: Operator = Equals < Less than <= Less than or equal to > Greater than >= Greater than or equal to <> Not equal to BETWEEN AND Between two values (inclusive) IN (SET) Match any of a list of values LIKE Match character pattern IS NULL Is a null value IS NOT NULL Is a non-null value Note: Data types for both left and right operands must match. The precedence rules also apply among logical comparison and condition operators. Use parenthesis to change the precedence explicitly. SELECT last_name, salary WHERE hire_date < '01-JAN-00' AND job_id = 'IT_PROG'; SELECT last_name, salary WHERE hire_date BETWEEN '01-JAN-00' AND '31-DEC-00'; WHERE department_id IN (10, 50, 90 ); WHERE department_id IS NULL; LIKE condition operator. Use the LIKE condition to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers: o % denotes zero or many characters. o _ denotes exactly one character. Pattern-matching characters can be combined. Use ESCAPE identifier - '\' (back slash) to search actual '%' and '_' symbols. WHERE last_name LIKE '_i%'; SELECT last_name, department_id, salary WHERE job_id LIKE 'SA\_%';

3. Sorting the result Sorting the result can be achieved by using ORDER BY clause. It has the format as followed: FROM table [WHERE condition(s)] [ORDER BY {column expr numeric_position } [DESC ASC]; ORDER BY clause must be the last clause of SELECT statement. A column, an expression, alias, or column position can be used as sort condition. Explicit DESC or default optional ASC can follow sort condition to determine either descending or ascending order respectively. SELECT employee_id, last_name, salary*12 annsal ORDER BY annsal; SELECT last_name, department_id, salary ORDER BY department_id, salary DESC; Lab Exercises For the following exercises create the tables using the given script. Write SELECT statement and save the SQL script for each exercise (or query). 1. Increase the SALARY by 20% of all employees whose job is "IT_PROG" 2. Display Last name and his / her manager id in the form of: "Last_Name must report to employee : Manager_Id". Rename the column header to "Report Status". 3. Display Last name and his / her manager id, for employee who does not have manager display "NO Manager". Give Column header appropriately. 4. Display the last name and their revised salary based on the following criteria of JOB_ID: 'AD_VP' increase 10%, 'IT_PROG' increase 15%, 'SA_REP' increase 20%, other increase 5%. Give Column header appropriately. 5. Display last name and his/her salary in form of number of '#'es. Each '#' represents 1,000. Give Column header appropriately. 6. Display employees (all columns) who do not belong to any department 7. Display employees (all columns) whose last name contains 'r', followed by one character, then followed by 'n', and being hired on the year of 1999. 8. Display first name, last name, hire date, manager's last name, and manager's hire date of employees whose manager is junior (being hired later).