CGS 3066: Spring 2017 SQL Reference

Similar documents
CSC Web Programming. Introduction to SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

SQL Commands & Mongo DB New Syllabus

Sql Server Syllabus. Overview

Learn Well Technocraft

Institute of Aga. Microsoft SQL Server LECTURER NIYAZ M. SALIH

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database 11g: SQL and PL/SQL Fundamentals

Chapter-14 SQL COMMANDS

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

SQL Interview Questions

Course Outline and Objectives: Database Programming with SQL

Data about data is database Select correct option: True False Partially True None of the Above

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Full file at

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer,

SQL functions fit into two broad categories: Data definition language Data manipulation language

Data Base Concepts. Course Guide 2

T-SQL Training: T-SQL for SQL Server for Developers

Introduction to Computer Science and Business

Querying Data with Transact SQL

Oracle Database 10g: Introduction to SQL

Deccansoft softwareservices-microsoft Silver Learing Partner. SQL Server Syllabus

Chapter 3: Introduction to SQL

UNIT-IV (Relational Database Language, PL/SQL)

1. Data Definition Language.

2) SQL includes a data definition language, a data manipulation language, and SQL/Persistent stored modules. Answer: TRUE Diff: 2 Page Ref: 36

5. Single-row function

CMPT 354: Database System I. Lecture 2. Relational Model

Today Learning outcomes LO2

Jarek Szlichta

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

Chapter 1 SQL and Data

Operating systems fundamentals - B07

Assignment Session : July-March

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Slides by: Ms. Shree Jaswal

AO3 - Version: 2. Oracle Database 11g SQL

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]


SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

origin destination duration New York London 415 Shanghai Paris 760 Istanbul Tokyo 700 New York Paris 435 Moscow Paris 245 Lima New York 455

Introduction. Example Databases

DATABASES SQL INFOTEK SOLUTIONS TEAM

Oracle Database: SQL and PL/SQL Fundamentals

The SQL data-definition language (DDL) allows defining :

Chapter # 7 Introduction to Structured Query Language (SQL) Part II

CS108 Lecture 18: Databases and SQL

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

B.H.GARDI COLLEGE OF MASTER OF COMPUTER APPLICATION. Ch. 1 :- Introduction Database Management System - 1

DATABASTEKNIK - 1DL116

GITA 338: Spatial Information Processing Systems

G64DBS Database Systems. Lecture 7 SQL SELECT. The Data Dictionary. Data Dictionaries. Different Sections of SQL (DDL) Different Sections of SQL (DCL)

Chapter 4: SQL Basics

DATABASE TECHNOLOGY - 1MB025

Basant Group of Institution

Review. Objec,ves. Example Students Table. Database Overview 3/8/17. PostgreSQL DB Elas,csearch. Databases

Chapter 3:Spatial Query Languages 3.1 Standard Database Query Languages 3.2 Relational Algebra 3.3 Basic SQL Primer 3.4 Extending SQL for Spatial

Mahathma Gandhi University

8) A top-to-bottom relationship among the items in a database is established by a

Chapter 3: Introduction to SQL

The SQL database language Parts of the SQL language

Unit Assessment Guide

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

DATABASE TECHNOLOGY - 1MB025

Data! CS 133: Databases. Goals for Today. So, what is a database? What is a database anyway? From the textbook:

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Relational Database Language

HKTA TANG HIN MEMORIAL SECONDARY SCHOOL SECONDARY 3 COMPUTER LITERACY. Name: ( ) Class: Date: Databases and Microsoft Access

Advanced SQL Tribal Data Workshop Joe Nowinski

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

Oracle Syllabus Course code-r10605 SQL

Session 6: Relational Databases

Outline. Introduction to SQL. What happens when you run an SQL query? There are 6 possible clauses in a select statement. Tara Murphy and James Curran

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

In This Lecture. Yet More SQL SELECT ORDER BY. SQL SELECT Overview. ORDER BY Example. ORDER BY Example. Yet more SQL

Database Systems SQL SL03

SQL QUERIES. CS121: Relational Databases Fall 2017 Lecture 5

CS143: Relational Model

Course Outline. MySQL Database Administration & Design. Course Description: Pre-requisites: Course Content:

QQ Group

CS 582 Database Management Systems II

Chapter 1 An introduction to relational databases and SQL

Oracle Database: Introduction to SQL

Certification Exam Preparation Seminar: Oracle Database SQL

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

DATABASE TECHNOLOGY. Spring An introduction to database systems

NCSS: Databases and SQL

Chapter 4: SQL. Basic Structure

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

1Z Oracle Database 11g - SQL Fundamentals I Exam Summary Syllabus Questions

Data Manipulation Language (DML)

Oracle Database 10g: SQL Fundamentals I

Transcription:

CGS 3066: Spring 2017 SQL Reference Can also be used as a study guide. Only covers topics discussed in class. This is by no means a complete guide to SQL. Database accounts are being set up for all students who have given me your CS usernames. You will receive your credentials through CS email. You can access your CS email through webmail2.cs.fsu.edu. Use your CS username and password to log in. You would have received an email that contains a username for the database account, a password and a database name. You can access the database server at dbsrv2.cs.fsu.edu. This requires the use of a command line terminal. You can also access the database through a PHP script that is on the ww2 server. For this, you have to test the file by uploading it on the server. It won t work from your local machine. 1 Databases A database is a repository of information, where data is stored according to a particular model. Databases make the storage and retrieval of data easy and safe. Without databases, we d have to store data in memory, which is impractical due to volatility of memory and the ever growing amount of data; or we d have to store data in text files, which, while being persistent storage, makes the retrieval of data onerous. A database is an organized collection of data. The data is typically organized to model aspects of reality in a way that supports the processes requiring the information. Databases are supported by Database Management Systems. 2 Database Management System (DBMS) Database management systems are computer software applications that interact with the user, other applications, and the database itself to capture and analyze data. A general-purpose DBMS is designed to allow the definition, creation, querying, update, and administration of databases. different DBMS satisfy different properties and requirements. DBMS are classified in different ways, including relational and object-oriented, SQL and NoSQL, etc. Some of the popular DBMS are Oracle: Object-relational database management system produced and marketed by Oracle Corporation. DB2: Family of database server products developed by IBM. These products all support the relational model. Some products have been extended to support object-relational features and non-relational structures. 1

SQL Server: Relational database management system developed by Microsoft. There are at least a dozen different editions of Microsoft SQL Server aimed at different audiences. PostgreSQL: object-relational database management system (ORDBMS) with an emphasis on extensibility and standards-compliance. MySQL: The world s second most widely used relational database management system and most widely used open-source RDBMS. 3 Structured Query Language SQL is the standard language for querying and manipulating data. Queries are commands given to the database to carry out certain actions. Most of the time, queries are questions about the data that SQL generates responses to after looking at the database. Initially developed at IBM by Donald Chamberlin and Raymond Boyce in the early 1970s. A very-high-level language, in which programmers are able to avoid specifying a lot of datamanipulation details that would be necessary in languages like C++. Its queries are optimized quite well, yielding efficient query executions. Many standards out there: SQL92, SQL3, SQL99, SQL 2011... Vendors support various subsets of these standards. 3.1 Sub-Languages SQL has 3 sub-languages. Data Definition Language (DDL): Used to define and modify the database schema. Schema refers to the structure of the database. Data Manipulation Language (DML): Used to insert, update, delete and query the data in the tables. Data Control Language (DCL): Used to control access to the data. Mainly for maintaining users. 4 Some Terminology This is some common SQL terminology. Table: A database most often contains one or more tables. Each table is identified by a name. Tables contain records (rows) with data. Field: A column in a table. Record/Tuple: A row in a table. Key: A group of field names that can uniquely identify a row in a table. Primary Key: A single field key that s chosen to be the key for a table. Foreign Key: A field in one table that acts as a primary key for another table. 2

5 Database Setup This is the sample database setup we ll use for the rest of this document. Database: Bank Table: Accounts Name Social Address AccountNo DateOfCreation Type Table: Transactions TransID DateofTransaction AccountNo Type Amount Balance 6 DDL Queries This section outlines the queries used to set up the schema (or structure) of the database. Words in uppercase are SQL keywords. 6.1 Create Database Used to create a database. A database contains all the tables that are used in a particular application. Very large applications might have several databases, each serving a particular purpose. For creating the database Bank, CREATE DATABASE Bank; 6.2 Create Table Used to create a table in a database. Tables are organized into rows and columns; and each table must have a name. Columns must have a name and a datatype, with optional size and constraints. Constraints include uniqueness, primary key or foreign key constraints, etc. To set up the 2 tables above, we use the two queries below. CREATE TABLE Accounts ( Name Social Address ); AccountNo DateOfCreation DATE, Type VARCHAR(50), INTEGER(10) UNIQUE, VARCHAR(200), INTEGER(14) PRIMARY KEY, VARCHAR(10) CREATE TABLE Transactions ( TransID INTEGER(20) PRIMARY KEY, DateOfTransaction DATE, AccountNo INTEGER(14) FOREIGN KEY REFERENCES Accounts(AccountNo), Type VARCHAR(10), Amount FLOAT, Balance FLOAT ); 3

6.3 Alter Table The alter table query is used to add or remove columns from existing tables. While adding columns, we specify the column name and its datatype. If we want to add a column Balance to the Accounts tables, we use the following query. ALTER TABLE Accounts ADD Balance FLOAT; If we want to remove columns from the table, we just ask for the column to be dropped. If we decide that having Balance in the Accounts table doesn t make sense, we use the query, ALTER TABLE Accounts DROP COLUMN Balance; 6.4 Truncate Table This query is used to delete all the rows in a table. To remove all data from the Transactions table, TRUNCATE TABLE Transactions; 6.5 Drop Table This query is used to delete a table. A table can be deleted only if it is empty. DROP TABLE Transactions; 7 DML Queries This section describes te queries used to manipulate the data in the tables. Ideally, DDL queries are executed only once, during the initial set up of the application. DML queries are used in everyday interactions with the database. Words in uppercase are SQL keywords. SQL is not case sensitive, but it is convention to write SQL keywords in uppercase. 7.1 Insert This statement is used to add records into the table. There are 2 modes for the insert statement. If we know the order of the columns in the table, we need not specify column names in the insert statement. INSERT INTO Accounts VALUES ( John Smith, 1234567890, 1, Blue Road, Greenville, MA 12345, 2340000000057, 2015-03-25, Savings ); If we don t know the order, or if we don t have values for every field, we can specify the colums where we want to insert data. INSERT INTO Accounts (Name, Social, AccountNo, DateOfCreation, Type) VALUES ( John Smith, 1234567890, 2340000000057, 2015-03-25, Savings ); 7.2 Update This query is used to change data in particular fields. Basically, it s used to update existing data. When update is used without the WHERE clause, it will change the value for that field for ALL rows in the table. The query UPDATE Transactions SET Type= Deposit ; will change the transaction type of every transaction ever made to Deposit. If we don t want this to happen, we should use the WHERE clause. If we want to affect only one row, we would use the primary key in the WHERE clause. It is also possible to use the WHERE clause with a range to affect more than one row. UPDATE Transactions SET Type= Deposit WHERE TransID=10003451890000000072; 4

7.3 Delete We can also delete rows from a table. Delete queries are usually used with WHERE clauses. If we don t specify a WHERE clause, we ll end up deleting ALL the rows in the table. To remove all checking accounts from the Accounts table, DELETE FROM Accounts WHERE Type= Checking ; All the queries encountered so far would return only success or failure. If the query was executed successfully, it will also mention how many rows were affected. The SELECT query, on the other hand returns a table upon successful execution. 7.4 Select The Select statement is used to select data from a database. The result is stored in a result table, called the result-set. The order of rows in the result-set is To Select ALL rows and columns from a table, SELECT * FROM Accounts; If we want all the rows, but only a few columns, we can specify the columns we want. SELECT Name, AccountNo, Type FROM Accounts; The WHERE clause is used to extract only those records that fulfill a specified criterion. SELECT AccountNo, Amount, Type, Balance FROM Transactions WHERE DateOfTransaction = 2015-03-26 ; The AND & OR operators are used to filter records based on more than one condition. SELECT AccountNo, Amount, Type, Balance FROM Transactions WHERE DateOfTransaction = 2015-03-26 AND Amount>100 OR Type= Withdrawal ; This query retrieves rows where the transaction took place on March 26 2015 with the amount being grater than $100 or if it was a withdrawal (that happened since the beginning of time for any amount). The ORDER BY keyword is used to sort the result-set according to a particular field. By default, it s presented in ascending order. To sort the rows in descending order, we use the keyword DESC. SELECT AccountNo, Amount, Type, Balance FROM Transactions WHERE DateOfTransaction = 2015-03-26 AND Amount>100 OR Type= Withdrawal ORDER BY AccountNo DESC; 7.5 Nested Queries It is possible to have Select queries inside Select queries. The inner query is executed first, and the outer query is executed on the result of the inner query. Nested queries can be used as an alternative to joins. The inner query and the outer query must be matched by a foreign key - primary key pair. Also, instead of using relational operators, we use the IN keyword. For example, if we wanted to print the names of account holders who made a transaction on March 30 2015, we would use the following query. SELECT Name from Accounts WHERE AccountNo IN ( SELECT AccountNo from Transactions WHERE DateOfTransaction = 2015-03-30 ); 5

7.6 Aggregate Function Aggregate functions are used to obtain certain statistics on the data. return a single value, calculated from values in a column. For example, SQL aggregate functions SELECT Sum(Amount) FROM Transactions WHERE Type= Deposit AND DateOfTransaction = 2015-03-26 ; Some of the commonly used aggregate functions are: AVG: Calculates average. SUM: Calculates sum. MAX: Calculates maximum value in a column. MIN: Calculates minimum value in a column. COUNT: Calculates number of rows. COUNT DISTINCT: Calculates number of distinct values in a column. 7.6.1 GROUP BY and HAVING The GROUP BY statement is used in conjunction with the aggregate functions to group the resultset by one or more columns. If we want to have all the deposit transactions grouped together, followed by all the withdrawal, we can use the GROUP BY clause. SELECT TransID, AccountNo, Amount, Type FROM Transactions WHERE Balance >= 2500 GROUP BY Type; The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. For example, if we want to display all the account numbers whose average transaction is $500 or higher, we use the following query. SELECT DISTINCT AccountNo FROM Transactions GROUP By AccountNo HAVING AVG(Amount) > 500; 6