SQL Training
SQL Training
What is a database(DBMS)?
DBMS means Data Base Management System Database is a structured collection of data. Database stores records relating to each other in a table Tables are uniquely identified by their names and consists of rows and columns Columns contain the column name, data type and any other attributes for the column Rows contain the records or data for the columns Visualize table as a tabular arrangement of data vertical columns and horizontal rows Database Applications: Banking: all transactions Airlines: reservations, schedules Universities: registration, grades Sales: customers, products, purchases Manufacturing: production, inventory, orders, supply chain Human resources: employee records, salaries, tax deductions Databases touch all aspects of our lives
Attributes
Example of tabular data in the relational model
Customer-id customer-name customer-street customer-city account-number
192-83-7465
Johnson
Alma
Palo Alto
A-101
019-28-3746
192-83-7465 321-12-3123 019-28-3746
Smith
Johnson Jones Smith
North
Alma Main North
Fractal Academy of Analytics
Rye
Palo Alto Harrison Rye
A-215
A-201 A-217 A-201
5
Relational database[RDBMS]
Following databases falls under RDMBS IBM DB2 Microsoft Access Microsoft SQL Server MySQL NonStop SQL Oracle The SAS system SQLBase SQLite
10
Foreign Keys: Foreign keys is used to implement referential integrity between tables within your database. By creating foreign keys you can ensure that related tables cannot contain invalid rows
11
Constraints
Constraints are basically the limitation that you want to put on your database while inserting new data in the table Default constraints allow you to specify a value that is written to the column if the application does not supply a value Default constraints apply only to new rows added with an INSERT statement You can define default constraints for either NULL or NOT NULL columns The following chart describes the types of restrictions you can place on columns and tables by using database-level constraints and triggers
12
Database Objects
13
Database Objects
Handle storage, manipulation, retrieval of data & data integrity . Available database objects are: Tables - a table is a set of data elements (values) that is organized columns rows. Views - a view is the result set of a stored query. Temporary Table It could be very useful to keep temporary data and will be deleted when the current client session terminates.
Delimited Identifiers If an identifier does not comply with the rules for the format identifiers, it must always be delimited Used when names contain embedded spaces, or when reserved words are used
15
16
Creating Database
Name of the database to be created CREATE DATABASE database_name ON ( [ NAME = logical_file_name, ] FILENAME = 'os_file_name' [, SIZE = size] [, MAXSIZE = { max_size | UNLIMITED } ]; ) Logical database name (Optional) Location of the database to be created (Optional)
Example:
Types of Database File:
CREATE DATABASE Test ON ( NAME = Test, FILENAME = 'c:\Test.mdf', SIZE = 4, MAXSIZE = 10, FILEGROWTH = 1 );
Primary Data base File (.mdf) / Main database file Mandatory Secondary Data base File (.ndf) Log Data base File (.ldf) Archive Data base File
Alter Database
Altering DB by Adding New file / Removing Existing File Syntax: ALTER DATABASE database { ADD FILE < filespec > [ ,...n ] | ADD LOG FILE < filespec > [ ,...n ] | REMOVE FILE logical_file_name | MODIFY FILE < filespec > | MODIFY NAME = new_dbname } ;
Example: ALTER DATABASE Test ADD FILE (NAME = addnewfile_data, FILENAME = 'c:\addnewfile.ndf', SIZE = 5MB, MAXSIZE = 100MB, FILEGROWTH = 5MB) ; Removing file from the database ALTER DATABASE Test REMOVE FILE Testlog ; Modifying a file ALTER DATABASE Test MODIFY FILE (NAME = Testlog, SIZE = 20MB) ;
Fractal Academy of Analytics
18
Create Table
The general syntax for a CREATE TABLE command is: CREATE TABLE r (A_1 D_1, A_2 D_2, , A_n D_n, (integrity-constraint_1), (integrity-constraint_m) ) Given a row, the values for some columns may be missing, unknown or not applicable for that row Such values are designated with the SQL keyword NULL Using SQL, one can specify an integrity constraint on a column ensuring it does not contain null values for any row The primary key is a combination of columns which uniquely identify each row No two rows can have same values in all the columns of the primary key A table may or may not have a primary key
19
Create Table . . .
CREATE TABLE MEMBERS ( MEMBER_ID VARCHAR2(6) NOT NULL, MEMBER_NAME VARCHAR2(10), MEMBER_AGE NUMBER, ADDRESS VARCHAR2(40));
Member_id Member_name Member_age Address
Book_id
Book_name
Author_name
Category
CREATE TABLE BOOKS ( BOOK_ID VARCHAR2(6) NOT NULL, BOOK_NAME VARCHAR2(20), AUTHOR_NAME VARCHAR2(15), CATEGORY VARCHAR2(15) );
CREATE TABLE TRACKER ( BOOK_ID VARCHAR2(6) NOT NULL, MEMBER_ID VARCHAR2(6), ISSUE_DATE DATE, ISSUED_BY VARCHAR2(15));
Book_id
Member_Id
Issue_date
Issued_By
20
The DROP TABLE command deletes the specified table from the database DROP TABLE TRACKER
21
22
Syntax : INSERT INTO table_name VALUES (value1,value2,value3,...); Types of Insert : Insert the exact values as per table structure (columns). : INSERT INTO SalesStaff1 VALUES (1, 'Stephen', 'Jiang');
Insert multiples values at same time i.e. using single query. : INSERT INTO SalesStaff1 VALUES (2, 'Michael', 'Blythe'), (3, 'Linda', 'Mitchell'), (4, 'Jillian', 'Carson'); Insert only required values into a table from another table. : INSERT INTO SalesStaff1(StaffID, FirstName) SELECT StaffID, FirstName FROM SalesStaff2 WHERE StaffID=8;
23
IDENTITY keyword is used for auto-increment. Default starting value is 1 and increments by 1 for each new record. To specify that the "P_Id" column should start at value 10 and increment by 5, change the identity to IDENTITY(10,5). INSERT INTO Person (FirstName,LastName) VALUES ('Lars','Monsen');
No Need to provide value for IDENTITY column as it is entered automatically by SQL server.
Fractal Academy of Analytics
24
UPDATE table1 A SET A.Fld1 = ( SELECT B.Fld1 FROM table2 B WHERE A.Fld2 = B.Fld2 );
If WHERE clause is omitted in above query then all records will get updated.
25
Syntax :
The above query will create new table with same table structure as that of old table and all rows will get copied. Ex:
SELECT * INTO Person_cpy FROM Person;
26
DELETE FROM Customers WHERE CustName=Jim Anders' AND ContactName='Maria Anders'; DELETE * FROM Customers; TRUNCATE (DDL) Records removed by the TRUNCATE TABLE statement cannot be restored. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes remain. Syntax : TRUNCATE TABLE table_name; TRUNCATE TABLE Customers;
Fractal Academy of Analytics
27
DELETE Logs delete operation thus making it slow. Can be rolled back. Can have criteria (WHERE clause) to delete.
TRUNCATE Does not log any activity, therefore it is faster. Cannot be rolled back. There is no criteria, all records are truncated.
28
The WHERE clause is used to extract only those records that fulfill a specified criterion. SELECT column_name1 FROM table_name WHERE column_name 2 operator value;
29
30
32
33
TOP Clause
The TOP clause is used to specify the number of records to return. The TOP clause can be very useful on large tables with thousands of records. Returning a large number of records can impact on performance. This is very useful for large tables with thousands of records
SELECT TOP number|percent column_name(s) FROM table_name SELECT TOP 1 Country_Code, Vendor_Value_MLC, Vendor_Volume_MSU FROM [AAIJK BABY CARE] COUNTRY_CODE IN DATABASE DP VENDOR_VALUE_MLC 33.32184 VENDOR_VOLUME_MSU 0.01546311
SELECT TOP 1* FROM [ [AAIJK BABY CARE] SELECT TOP 60 percent * FROM CUSTOMER
34
Aggregate Functions
With SQL and SQL Server you can use lots of built-in functions or you may create your own functions. SQL has many built-in functions for performing calculations on data. We have 2 categories of functions, Aggregate functions return a single value, calculated from values in a column, while scalar functions return a single value, based on the input value. Aggregate functions - examples: AVG() - Returns the average value COUNT() - Returns the number of rows MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum Scalar functions - examples: UPPER() - Converts a field to upper case LOWER() - Converts a field to lower case ROUND() - Rounds a numeric field to the number of decimals specified GETDATE() - Returns the current system date and time
35
Aggregate Functions
The AVG() function returns the average value of a numeric column. SELECT AVG(column_name) FROM table_name SELECT Avg(VENDOR_VALUE_MLC) AVG_VENDOR_VALUE_MLC 229483.726994896 The COUNT() function returns the number of rows that matches a specified criteria. The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name SELECT Count(Country_Code) AS CNT_VENDOR_VALUE_MLC FROM [AAIJK BABY CARE] CNT_VENDOR_VALUE_MLC 1080174
Fractal Academy of Analytics
36
Group By
The GROUP BY statement is often used with the aggregate functions to group the result-set by one or more columns. SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name Example SELECT COUNTRY_CODE, Avg(VENDOR_VOLUME_MSU) AS AVG_VENDOR_VOLUME_MSU FROM [AAIJK BABY CARE] GROUP BY COUNTRY_CODE COUNTRY_CODE ID IN JP PH VN AVG_VENDOR_VOLUME_MSU 2.65908836939374 1.08605703692316 0.954831321140269 1.33917439045886 2.07322729027707
Fractal Academy of Analytics
37
Having Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value Example SELECT COUNTRY_CODE, Avg(VENDOR_VOLUME_MSU) AS AVG_VENDOR_VOLUME_MSU FROM [AAIJK BABY CARE] GROUP BY COUNTRY_CODE HAVING Avg(VENDOR_VOLUME_MSU)>2
COUNTRY_CODE
ID VN
AVG_VENDOR_VOLUME_MSU
2.65908836939374 2.07322729027707
38
Built-in Functions
39
The POW(m,n) function returns m raised to the nth power SELECT POW(m, n);
SELECT POW(8,3);
40
SELECT CEILING(52.58)
Similarly, there is FLOOR ( m ) function which returns greatest integer smaller than or equal to m
41
42
The LEFT ( s, n ) function returns the left part of a character string with the specified number of characters. SELECT LEFT ( character_expression , integer_expression ) SELECT LEFT ( abcd , 2 ) Similarly, RIGHT ( s, n ) function returns the right part of a character string with the specified number of characters.
43
The DAY ( d ) function returns day number of the month SELECT DAY(d) SELECT DAY (01/31/2012) returns 31
The MONTH ( d ) function returns month number of the year SELECT MONTH (d) SELECT MONTH (01/31/2012) Similarly, we have YEAR( d ) function
Fractal Academy of Analytics
44
returns 1
45
46
The ALTER TABLE statement can: Add a column definition to a table Drop a column from a table Change the default value for a column Add or drop a primary key for a table Add or drop a new foreign key for a table Add or drop a uniqueness constraint for a table Add or drop a check constraint for a table
47
you cannot simply declare the new column NOT NULL, because the DBMS would assume NULL values for the column in the existing rows, immediately violating the constraint!
Fractal Academy of Analytics
48
RESTRICT: If any other objects in the database (foreign keys, constraints, and so on) depend on the column to be dropped, the ALTER TABLE statement fails with an error and the column is not dropped. CASCADE: Any other objects in the database (foreign keys, constraints, and so on) that depend on the column are also dropped as a cascaded effect of the ALTER TABLE statement.
Changing Default Value of a Column You can create a DEFAULT definition as part of the table definition when you create a table. If a table already exists, you can add DEFAULT definition to it. Each column in a table can contain one DEFAULT definition. If a DEFAULT definition already exists, you can modify or delete it. ALTER TABLE table_name ADD CONSTRAINT constraint_name DEFAULT value For column_name
Default value should match with the data type of the column
Fractal Academy of Analytics
50
51
52
Sub Queries
A Sub-Query is a SQL query nested inside a larger query. A Sub-Query may occur in : A SELECT clause A FROM clause A WHERE clause A Sub-Query can be treated as an inner query, which is a SQL query placed as a part of another query called as outer query. A Sub-Query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
54
Example: SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500)
55
Example: SELECT emp_last_name "Last Name, emp_first_name "First Name" FROM employee WHERE emp_ssn IN (SELECT dep_emp_ssn FROM dependent WHERE dep_gender = 'M') When a Sub-Query uses the EXISTS operator, the Sub-Query functions as an existence test. The WHERE clause of the outer query tests for the existence of rows returned by the inner query. The Sub-Query does not actually produce any data; rather, it returns a value of TRUE or FALSE.
Example: SELECT emp_last_name "Last Name", emp_first_name "First Name FROM employee WHERE EXISTS (SELECT * FROM dependent WHERE emp_ssn = dep_emp_ssn)
56
57
SQL Aliases
SQL aliases are used to temporarily rename a table or a column heading. Basically aliases are created to make column names more readable. Aliases can be useful when: There are more than one table involved in a query Functions are used in the query Column names are big or not very readable Two or more columns are combined together
SQL Aliases
58
59
Same SQL statement without aliases SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName FROM Customers, Orders WHERE Customers.CustomerName='Alfreds Futterkiste';
60
SQL Joins
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. Types the different SQL JOINS are as follows INNER JOIN: Returns all rows when there is at least one match in BOTH tables. LEFT JOIN: Return all rows from the left table, and the matched rows from the right table. RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table. FULL JOIN: Return all rows when there is a match in ONE of the tables. SELF JOIN is used to join a table to itself, as if the table were two tables, temporarily renaming at least one table in the SQL statement. CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records from the two or more joined tables.
61
SQL INNER JOIN Syntax SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name; OR SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name;
62
Select FROM
e.eno, ename, dept, desig, salary Employee e Inner Join Salary s On e.eno = s.eno;
Output ENO ENAME DEPT 100 Raji Eswar CSE EEE DESIG LECT Sr. LECT SALARY 15000 20000
Select
From Where
200
63
SQL LEFT JOIN Syntax SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name=table2.column_name;
64
e.eno, ename, dept, desig, salary employee e Left Outer Join salary s On e.eno = s.eno;
Select From
s.eno, ename, dept, desig, salary salary s Left Outer Join employee e On e.eno = s.eno;
400
Durga
IT
Null
Null
SQL Right JOIN Syntax SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name=table2.column_name; OR SELECT column_name(s) FROM table1 RIGHT OUTER JOIN table2 ON table1.column_name=table2.column_name;
66
Salary
ENO LECT Sr. LECT PROF DESIG SALARY 15000 20000 35000
600
Ass. PROF
30000
Select From
e.eno, ename, dept, desig, salary salary s Right Outer Join employee e On e.eno = s.eno;
From employee e Right Outer Join salary s On e.eno = s.eno; ENO 100 200 500 600 ENAME Raji Eswar Null Null DEPT CSE EEE Null Null DESIG LECT Sr. LECT PROF Ass. PROF SALARY 15000 20000 35000 30000
ENO 100
ENAME Raji
DEPT CSE
200
300 400
Eswar
Kailash Durga
EEE
ECE IT
SQL Full Outer JOIN Syntax SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name=table2.column_name;
68
600
Ass. PROF
30000
Select s.eno, ename, dept, desig, salary From employee e Full Outer Join salary s On e.eno = s.eno;
e2.ename as Employee Name , e1.ename as Manager Name employee e1, employee e2 e2.mgrno = e1.eno; Employee Name Raji Eswar Kailash Durga Shanmuga Ganesh Manager Name Raji Raji Eswar Kailash Kailash Kailash
Fractal Academy of Analytics
70
Employee
ENO 100 200 ENAME Raji Eswar DEPT CSE EEE
300
Select From
Kailash
ECE
DESIG LECT Sr. LECT LECT Sr. LECT LECT Sr. LECT
SQL Union Syntax SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2;
SQL UNION ALL Syntax SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2;
Fractal Academy of Analytics
72
Select eno, ename, dept Union all Select eno, ename, dept
73
Thank you
74