Ken s SQL Syntax Refresher

Similar documents
SQL Workshop. Joins. Doug Shook

MIT Database Management Systems

Chapter 4 How to retrieve data from two tables

Chapter 7 How to code subqueries

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

Database Management Systems

Sql Server Syllabus. Overview

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

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

Subquery: There are basically three types of subqueries are:

SQL Workshop. Subqueries. Doug Shook

SQL Workshop. Introduction Queries. Doug Shook

SQL Workshop. Database Design. Doug Shook

Principles of Data Management

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

Outer Join, More on SQL Constraints

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

Working with DB2 Data Using SQL and XQuery Answers

SQL Interview Questions

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

RDBMS- Day 4. Grouped results Relational algebra Joins Sub queries. In today s session we will discuss about the concept of sub queries.

SQL Workshop. Summaries. Doug Shook

Database Management Systems,

Full file at

An Introduction to Structured Query Language

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

5. Single-row function

IBM DB2 9 Family Fundamentals. Download Full Version :

An Introduction to Structured Query Language

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

An Introduction to Structured Query Language

HNDIT 1105 Database Management Systems

Advance Database Systems. Joining Concepts in Advanced SQL Lecture# 4

Conceptual Design. The Entity-Relationship (ER) Model

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

Lecture 9: Database Design. Wednesday, February 18, 2015

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

Graphical Joins in More Detail

Oracle Syllabus Course code-r10605 SQL

Chapter 1 An introduction to relational databases and SQL

An Introduction to Structured Query Language

An Introduction to Structured Query Language

1) Introduction to SQL

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

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

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

Intermediate SQL ( )

Exam code: Exam name: Database Fundamentals. Version 16.0

Database 2: Slicing and Dicing Data in CF and SQL

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

Activant Solutions Inc. SQL 2005: Basic Data Manipulation

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

CS W Introduction to Databases Spring Computer Science Department Columbia University

Lecture 3: Continuing SQL. Monday, February 2, 2015

COMP283-Lecture 6 Applied Database Management

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

Chapter 11 How to create databases, tables, and indexes

A subquery is a nested query inserted inside a large query Generally occurs with select, from, where Also known as inner query or inner select,

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

Database design process

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

Chapter 3 How to retrieve data from a single table

3.1. Keys: Super Key, Candidate Key, Primary Key, Alternate Key, Foreign Key

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

Relational Database Languages

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

Relational Model. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

MTA Database Administrator Fundamentals Course

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Downloaded from

Course Modules for MCSA: SQL Server 2016 Database Development Training & Certification Course:

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

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CMP-3440 Database Systems

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

DB2 SQL Class Outline

Handout 6 CS-605 Spring 18 Page 1 of 7. Handout 6. Physical Database Modeling

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

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Oracle Database 11g: SQL and PL/SQL Fundamentals

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

MariaDB Crash Course. A Addison-Wesley. Ben Forta. Upper Saddle River, NJ Boston. Indianapolis. Singapore Mexico City. Cape Town Sydney.

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

SQL STRUCTURED QUERY LANGUAGE

Assignment 6: SQL III Solution

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

Unit Assessment Guide

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

C Exam Questions Demo IBM. Exam Questions C

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Physical Design of Relational Databases

Structured Query Language (SQL)

ACCESS isn t only a great development tool it s

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

Oracle Database 10g Express

SQL Overview. CSCE 315, Fall 2017 Project 1, Part 3. Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch

Oracle Database 10g: Introduction to SQL

COSC344 Database Theory and Applications. Lecture 11 Triggers

Intermediate SQL: Aggregated Data, Joins and Set Operators

Transcription:

Ken s SQL Syntax Refresher 27Apr10 Ken s SQL Syntax Refresher 1 Select SELECT [ * ALL DISTINCT column1, column2 ] FROM table1 [, table2 ]; SELECT [ * ALL DISTINCT column1, column2 ] FROM table1 [, table2 ] WHERE [ condition1 expression1 ] [ AND condition2 expression2 ]; SELECT [ * ALL DISTINCT column1, column2 ] FROM table1 [, table2 ] WHERE [ condition1 expression1 ] [ AND condition2 expression2 ] ORDER BY column1 integer [ ASC DEC ] SELECT * FROM atable; SELECT DISTINCT * FROM atable ORDER BY id ASC; SELECT col1,col2 FROM atable WHERE datecol > (now() 1 day); SELECT DISTINCT COUNT(product_id) FROM productstable; SELECT city, AGV(salary) FROM employeetbl WHERE city <> Greenwood GROUP BY city HAVING AGV(salary) > 20000 ORDER BY 2 Where clause Conjunctive Operators AND, OR SELECT P.product_name, O.orderDate, O.quantity FROM products P, orders O WHERE P.serial_number = O.serial_number AND P.vendor_number = vendor_number; SELECT emp_id, salary FROM employeetbl WHERE salary IS NOT NULL OR pay_rate IS NOT NULL

27Apr10 Ken s SQL Syntax Refresher 2 Compund Queries UNION, UNION ALL, EXCEPT MINUS, INTERSECT The previous OR is the same as: SELECT emp_id, salary FROM employeetbl WHERE salary IS NOT NULL UNION Union is Distinct = no duplicated rows (vs Union All) SELECT emp_id, salary FROM employeetbl WHERE pay_rate IS NOT NULL SELECT * FROM Orders WHERE Quantity BETWEEN 1 AND 100 EXCEPT <= Oracle uses MINUS SELECT * FROM Orders WHERE Quantity BETWEEN 50 AND 75; Where clause operators =, <>, >, <, >=, <=, BETWEEN, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, EXISTS, NOT EXISTS WHERE salary LIKE 200% means match on wildcard 200* WHERE salary LIKE _00 means match on wildcard?00 SELECT a.firstname, a.lastname FROM Person.Contact AS a WHERE EXISTS ( SELECT * FROM HumanResources.Employee AS b WHERE a.contactid = b.contactid AND a.lastname = 'Johnson'); - is the same as - SELECT a.firstname, a.lastname FROM Person.Contact AS a WHERE a.lastname IN ( SELECT a.lastname FROM HumanResources.Employee AS b WHERE a.contactid = b.contactid AND a.lastname = 'Johnson'); Summary operators COUNT, SUM, AVG, MAX, MIN SELECT SUM(salary) as sum_salary FROM employeetbl SELECT COUNT(employeeId) as emp_count FROM employeetbl SELECT MAX(job_number) as max_job FROM atable SELECT MAX(job_number) as max_job, MIN(job_number) as min_job FROM atable Subquery with SELECT SELECT E.emp_id, EP.pay_rate FROM employee_tbl E, employee_pay_tbl EP

27Apr10 Ken s SQL Syntax Refresher 3 WHERE E.emp_id = EP.emp_id AND EP.pay_rate > (SELECT pay_rate FROM employee_tbl WHERE emp_id = 12345 ) Efficent Queries 1. Query the smallest table first 2. Use the most restrictive query first 3. Use IN rather than OR SELECT emp_id, last_name, first_name FROM employee_tbl WHERE city = Indianapolis OR city = Brownsburg OR city = Greenfield Use this one: SELECT emp_id, last_name, first_name FROM employee_tbl WHERE city IN ( Indianapolis, Brownsburg, Greenfield ) Join SELECT field-list FROM table-1 { INNER LEFT OUTER RIGHT OUTER } JOIN table-2 ON table-1.field-1 { = < > <= >= <> } table-2.field.2 [ WHERE selection-criteria ] [ ORDER BY field-list ] SELECT * FROM employee, department WHERE employee.deptid = department.deptid - is equivalent to SELECT * FROM employee INNER JOIN department ON employee.deptid = department.deptid - is equivalent to (equi join) - SELECT * FROM employee INNER JOIN department USING (deptid) deptid employee department deptid Natural Join: only has one column with the matches from both tables: SELECT * FROM employee NATURAL JOIN department Join on more than two tables SELECT Vendors INNER JOIN Invoices ON Vendors.VendorID = Invoices.VendorID INNER JOIN InvoiceLineItems

27Apr10 Ken s SQL Syntax Refresher 4 ON Invoices.InvoiceID = InvoiceLineItems.InvoiceID There no SELECT DISTINCT on Joins, use a Nautral Join A Natural Join is a special equi(equals)-join returns the columns and rows in common between multiple tables SELECT * FROM employee NATURAL JOIN department SQL Server supports additional cross joins and full outer joins SELECT * FROM employee CROSS JOIN department same as: SELECT * FROM employee, department; Outer Joins returns blank (or non existant) rows in the other table SELECT E.id P.id FROM employeetable E, employeepay P, WHERE E.id = P.id(+); SELECT * FROM employee LEFT OUTER JOIN department ON employee.departmentid = department.departmentid Insert INSERT INTO table-name [ ( field-list ) ] VALUES ( value-list ) INSERT INTO atable (col1, col2, col2) VALUES ( value1, value2, NULL ); Subquery with Insert INSERT INTO table-name ( field-columns) SELECT-statement <= for the values to put into the field-columns INSERT INTO atable (col1, col2, col3) SELECT FROM anothertable col1,col2,col3 WHERE datecol > (now() 1 day); INSERT INTO InvoiceArchive SELECT * FROM Invoices WHERE InvoiceTotal PaymentTotal CreditTotal = 0

27Apr10 Ken s SQL Syntax Refresher 5 Update UPDATE table-name SET expression-1 [,expression-2 ] WHERE selection-criteria UPDATE orderstable SET quantity = 5 WHERE order_no = 12345 ; Subquery with Update UPDATE employee_pay_tbl SET pay_rate = pay_rate * 1.1 WHERE emp_id IN (SELECT emp_id FROM employee_tbl WHERE city = Indianapolis ) Delete DELETE FROM table-name WHERE selection-criteria DELETE FROM orders_table WHERE order_no = 12345 AND date < (now() 30 days); Subquery with Delete DELETE FROM employee_pay_tbl WHERE emp_id = (SELECT emp_id FROM employee_tbl WHERE last_name = Freed AND first_name = Ken ) Views A View is a predefined query that s stored in a database CREATE VIEW VendorsMin AS SELECT VendorName, VandorStatus FROM Vendors Use the above view just like it was a table: SELECT * FROM VendorsMin

27Apr10 Ken s SQL Syntax Refresher 6 Stored Procedures A Stored Procedure is one or more SQL statements that - can accept input parameters and - that have been compiled and stored within the database. Stored Procedures can improve db performance since they re compiled and optimized the first time they re executed Their alternative is to execute Transact-SQL programs stored locally on client computers Lots of places that use SQL Server use stored procs for database I/O. While it gets better performance & security, it can be a real pain to figure out what is going on if there is data issue. The SQL server profiler can be a useful utility for troubleshooting though. - The biggest complaint with Stored Procedures is when there is a series of transactions that were fired off as a bunch of stored procedures, it can be difficult and time consuming to replicate the events that led up to where the problem is occurring, depending on how many stored procs are called. A Trigger is a special type of stored procedure that s fired when record are inserted, updated or deleted from a table. - Triggers can be used to enforce Referential Integrity. - Triggers can be used to check the validity of data updated or inserted into a table CREATE PROCEDURE VendorByState @State Char As SELECT VendorName, VendorState, VendorPhone FROM Vendors WHERE VendorState = @State ORDER BY VendorName Using the above stored procedure: Execute VendorsByState for State = CA

27Apr10 Ken s SQL Syntax Refresher 7 Some Common Queries CREATE DATABASE adatabase; CREATE TABLE testtable (id INT NOT NULL AUTO_INCRMENT, PRIMARY_KEY(id), testfield VARCHAR(50); GRANT insert,update,select on *.* to atable@localhost identified by apassword ; INSERT INTO testtable (testfield) VALUES ( first message ); DELETE FROM testtable WHERE id=2; UPDATE members set expire_ts= 2009-09-09 12:00:00 where id=26; ALTER TABLE some_table ADD expired TYPE boolean; // add a column ALTER TABLE (atablename) ADD <colname> <coltype>; show tables; show tables like 'journal%' describe service_attr;

27Apr10 Ken s SQL Syntax Refresher 8 MISC Database Normalization 1 st normal form: No repeated data. Create separate tables 2 nd normal form: Data depends on the WHOLE key (e.g., in case you concatenate two attributes together to make a unique key e.g.: person,skill <= address violates since address has nothing to do with skill 3 rd normal form: Attributes don t depend on an attribute which depends on the whole key, e.g.: tournament,year <= winner <= winner s birthday Referential Integrity: Means that the records with foreign keys always have records with a matching primary key in another table. - This means that you can t add a record with a foreign key value if the primary key record doesn t already exist (in another table). - It also means that you can t delete a primary key record without deleting related foreign key records. One way to enforce Referential Integrity is to define the primary and foreign key relationship within the database. - SQL Server calls this Foreign Key Constraints. - When you do this, you re using what SQL Server calls Declarative Referential Integrity (DRI) = Referential Integrity is enforce automatically by the DBMS - SQl Server doesn t provide for cascading changes and deletes to related tables. - If you want to be able to cascade changes and deletes with SQL Server, you can use Triggers to enforce referential integrity instead of Foreign Key Constraints, i.e. Triggers let you cascade changes from the Primary Keys in one table to the Foreign Keys in a related table. A 1-1 table relationship means you can just put it all in one table. - Sometimes you d do this for secure columns, or too many columns

27Apr10 Ken s SQL Syntax Refresher 9 Handling Lists of Things in Tables Wrong way to design: firstname lastname Instrument1 Instrument2 Instrument3 Angie Beltran Guitar Sax Laura Chow Sax Clarinet Piano Debbie Moss Drums Guitar Raul Garcia Guitar Piano Drums Right way to design (repeat some info in the rows), which is a one-to-many relationship: firstname lastname Instrument Angie Beltran Guitar Angie Beltran Sax Debbie Moss Drums Debbie Moss Guitar Raul Garcia Guitar Raul Garcia Piano Raul Garcia Drums