Presentation is loading. Please wait.

Presentation is loading. Please wait.

Prof: Dr. Shu-Ching Chen TA: Haiman Tian

Similar presentations


Presentation on theme: "Prof: Dr. Shu-Ching Chen TA: Haiman Tian"— Presentation transcript:

1 Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Sql language tutorial Prof: Dr. Shu-Ching Chen TA: Haiman Tian

2 Basic Syntax of SQL Language
SELECT attribute name(s) FROM table name WHERE comparison predicate (Boolean expression) GROUP BY attribute name(s) HAVING comparison predicate ORDER BY attribute name(s) SQL (Structured Query Language) is a computer language aimed to store, manipulate, and query data stored in relational databases HAVING is used when you are using an aggregate such as GROUP BY. It is used to check conditions after the aggregation takes place. WHERE is used before the aggregation takes place.

3 Create Tables Note that all data types use rather obvious input formats. Constants that are not simple numeric values must usually be surrounded by single quotes ('), as in the example. The date column is actually quite flexible in what it accepts, but for this tutorial we will stick to the format shown here. The syntax used so far requires you to remember the order of the columns. An alternative syntax allows you to list the columns explicitly: You can list the columns in a different order if you wish or you can even omit some columns, for example, if the precipitation is unknown: Many developers consider explicitly listing the columns better style than relying on the order implicitly.

4 SQL ALTER TABLE ADD COLUMN
ALTER TABLE table name ADD column_name datatype; TODO: Add the update by adding a column example

5 SELECT ALL records SQL is not case sensitive. SELECT is the same as select. Tip: The asterisk (*) is a quick way of selecting all columns!

6 Formula Like & DISTINCT
The LIKE operator is used to search for a specified pattern in a column. The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern. It is also possible to select the city that does NOT contain the pattern “Sa" from the “weather" table, by using the NOT keyword. SELECT * FROM Persons WHERE City NOT LIKE '%tav%‘ % => A substitute for zero or more characters _ => A substitute for exactly one character

7 SELECT ALL with LIKE operator
SELECT column1, column2, … FROM table_name WHERE columnN LIKE pattern; LIKE Operator Description WHERE column_name LIKE 'a%' Finds any values that starts with "a" WHERE column_name LIKE '%a' Finds any values that ends with "a" WHERE column_name LIKE '%or%' Finds any values that have "or" in any position WHERE column_name LIKE '_r%' Finds any values that have "r" in the second position WHERE column_name LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length WHERE column_name LIKE 'a%o' Finds any values that starts with "a" and ends with "o"

8 SELECT ALL with LIKE operator
Example: WHERE column_name LIKE 'a%'

9 SELECT ALL with LIKE operator
Example: WHERE column_name LIKE ’%a'

10 SELECT specific records with conditions

11 SELECT IN SELECT column1, column2, … FROM table_name
You use the IN operator in the WHERE clause to check if a value matches any value in a list of values. The syntax of the IN operator is as follows: SELECT column1, column2, … FROM table_name WHERE columnN IN (value1, value2, …); The expression returns true if the value matches any value in the list i.e., value1, value2, etc. The list of values is not limited to a list of numbers or strings but also a result set of a SELECT statement as shown in the following query: SELECT column1, column2, … FROM table_name WHERE columnN IN (SELECT value FROM tbl_name);

12 SELECT NOT IN SELECT column1, column2, … FROM table_name
You can combine the IN operator with the NOT operator to select rows whose values do not match the values in the list. SELECT column1, column2, … FROM table_name WHERE columnN NOT IN (value1, value2, …);

13 SELECT ANY (1) The ANY operator must be preceded by one of the following operator =,<=,>,<,>,<> The ANY operator returns true if any value of the subquery meets the condition, otherwise, it returns false. The subquery must return exactly one column. SELECT column1, column2, … FROM table_name WHERE columnN operator ANY (subquery);

14 SELECT ANY (2) The = ANY is equivalent to IN operator.
Note that the <>ANY operator is different from NOT IN. x<>ANY(a,b,c) is equivalent to x<>a OR x<>b OR x<>c

15 SELECT from two TABLES (1)
Products Categories

16 SELECT from two TABLES (2)
Query: List the name(s) of all products that are categorized as beverages.

17 SQL ORDER BY The ORDER BY keyword is used to sort the result-set by a specified column. The ORDER BY keyword sort the records in ascending order by default. SELECT * FROM Persons ORDER BY LastName DESC

18 SQL ORDER BY DESC

19 ASCII Value (1)

20 ASCII Value (2) Example select grade, ascii(grade) from enroll
order by ascii(grade)

21 SQL IN OPERATOR AVG() - Returns the average value
COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum The IN operator allows you to specify multiple values in a WHERE clause The MAX() function returns the largest value of the selected column SQL has many built-in functions for performing calculations on data

22 SQL Alias This can be a good thing to do if you have very long or complex table names or column names An alias name could be anything, but usually it is short. As you'll see from the two SELECT statements above; aliases can make queries easier to both write and to read.

23 SQL Joins SELECT column_name(s) FROM table_name1 JOIN_TYPES table_name2 ON table_name1.column_name = table_name2.column_name INNER JOIN: Return rows when there is at least one match in both tables LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables Tables in a database are often related to each other with keys. A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table

24 SQL INNER JOIN

25 SQL LEFT JOIN

26 SQL RIGHT JOIN

27 SQL UPDATE FIELD UPDATE table name
SET column1 = value, column2 = value2,… WHERE comparison predicate (Boolean expression)

28 SQL UPDATE Join (1) UPDATE A SET A.c1 = expression FROM B
Sometimes, you need to update data of a table based on values in another table. In this case, you can use the PostgreSQL UPDATE join syntax as follows: UPDATE A SET A.c1 = expression FROM B WHERE A.c2 = B.c2

29 SQL UPDATE Join (2) product_segment product
The product_segment table has the discount column that stores the discount percentage based on a specific segment. For example, grand luxury products have 5% discount while luxury and mass products have 6% and 10% discount respectively. The product table has the foreign key column segment_id that links to the id of the segment table.

30 SQL UPDATE Join (3) product_segment product
The product_segment table has the discount column that stores the discount percentage based on a specific segment. For example, grand luxury products have 5% discount while luxury and mass products have 6% and 10% discount respectively. The product table has the foreign key column segment_id that links to the id of the segment table.

31 SQL UPDATE Join (4) UPDATE product
SET net_price = price – price * discount FROM product_segment WHERE product.segment_id = product_segment.id; This statement joins the product table to the product_segment table. If there is a match in both tables, it gets the discount from the product_segment table, calculates the net price based on the following formula, and updates the net_pricecolumn. net_price = price – price * discount;

32 SQL UPDATE Join (5)

33 SQL GROUP BY Statement The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. Now we want to find the total sum (total order) of each customer. We will have to use the GROUP BY statement to group the customers

34 SELECT GROUP BY (1) Products Categories

35 SELECT GROUP BY (2) Query: Count the number of products in each category.

36 SELECT INNER JOIN Query: Count the number of products in each category (using inner join).

37 (nesting the previous query)
SELECT GROUP BY (3) Query: List the category names that contain greater-than-or-equal to 3 products (nesting the previous query)

38 SQL HAVING Clause

39 SELECT HAVING (1) Products Categories

40 (without nesting query)
SELECT HAVING (2) Query: List the category names that contain greater-than-or-equal to 3 products (without nesting query)

41 SQL DATE Type Example Description 1999-01-08
ISO 8601; January 8 in any mode (recommended format) January 8, 1999 unambiguous in any datestyle input mode 1/8/1999 January 8 in MDY mode; August 1 in DMY mode 1/18/1999 January 18 in MDY mode; rejected in other modes 01/02/03 January 2, 2003 in MDY mode; February 1, 2003 in DMY mode; February 3, 2001 in YMD mode 1999-Jan-08 January 8 in any mode Jan 08-Jan-1999 99-Jan-08 January 8 in YMD mode, else error 08-Jan-99 January 8, except error in YMD mode Jan-08-99 ISO 8601; January 8, 1999 in any mode 990108 year and day of year J Julian day January 8, 99 BC year 99 BC Possible inputs for the date type.

42 SQL DATE Type (1) Function Return Type Description Example Result
age(timestamp, timestamp) interval Subtract arguments, producing a "symbolic"result that uses years and months age(timestamp ' ', timestamp ' ') 43 years 9 mons 27 days age(timestamp) Subtract from current_date (at midnight) age(timestamp ' ') 43 years 8 mons 3 days current_date date Current date; current_time time with time zone Current time of day;

43 SQL DATE Type (2) Function Return Type Description Example Result
date_part(text, timestamp) double precision Get subfield (equivalent to extract); date_part('hour', timestamp ' :38:40') 20 date_trunc(text,timestamp) timestamp Truncate to specified precision; date_trunc('hour', timestamp ' :38:40') :00:00 now() timestamp with time zone Current date and time (start of current transaction); timeofday() text Current date and time (like clock_timestamp, but as a text string);

44 date_trunc(‘datepart’, field)
SQL DATE Type (3) date_trunc: function truncates a TIMESTAMP value based on a specified date part (e.g. hour, week, month) date_trunc(‘datepart’, field) Possible inputs for the date type.

45 SQL DATE Type (4) date() function converts a string literal to a date value. The following is the syntax: date(‘DD/MM/YYYY’) Possible inputs for the date type.

46 SQL DATE Type (5)

47 PosgreSQL Arrays (1) PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, or composite type can be created. Arrays of domains are not yet supported As shown, an array data type is named by appending square brackets ([]) to the data type name of the array elements. The above command will create a table named sal_emp with a column of type text (name), a one-dimensional array of type integer(pay_by_quarter), which represents the employee's salary by quarter, and a two-dimensional array of text (schedule), which represents the employee's weekly schedule

48 PosgreSQL Arrays (2) The array subscript numbers are written within square brackets. By default PostgreSQL uses a one-based numbering convention for arrays, that is, an array of n elements starts with array[1] and ends with array[n] We can also access arbitrary rectangular slices of an array, or subarrays. An array slice is denoted by writing lower-bound:upper-bound for one or more array dimensions. For example, this query retrieves the first item on Bill's schedule for the first two days of the week: If any dimension is written as a slice, i.e., contains a colon, then all dimensions are treated as slices. Any dimension that has only a single number (no colon) is treated as being from 1 to the number specified. For example, [2] is treated as [1:2]

49 PosgreSQL Arrays (3) An array value can be replaced completely:
or using the ARRAY expression syntax: An array can also be updated at a single element or updated in a slice:

50 PosgreSQL Composite Types


Download ppt "Prof: Dr. Shu-Ching Chen TA: Haiman Tian"

Similar presentations


Ads by Google