Querying with Transact-SQL Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

What is SQL?

A

Structured Query Language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Good to Remember

A

SQL is a declarative language and not a procedural language.

Describe what you want to get not how you want to get it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Key Points

A

KEY POINTS

  • Transact-SQL is the language used to query data in Microsoft SQL Server and Azure SQL Database.
  • Data is stored in tables, which may be related to one another through common key fields.
  • Objects in a database are organized into schemas.
  • The fully qualified naming syntax for an object is server_name.database_name.schema_name.object_name, but in most cases you can abbreviate this to schema_name.object_name.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

The result of a SELECT statement is always a………………..

A

Virtual Table

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the ‘AS’ statement do?

A

Assigns a new name or an alias name to a column

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Waht is ‘NULL’

A

NULL is an unknown value and any column operation performed on NULL will return a NULL ( eg. 58 + NULL = NULL)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

KEY POINTS

A

Use the SELECT statement to retrieve a rowset of data from tables and views in a database.

SELECT statements are written with the following clauses: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. However, the query engine processes the clauses in this order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.

In the SELECT clause, you can use * to return all columns, but generally you should specify explicit columns.

You can specify expressions in the SELECT clause to return the results of calculations.

You can use the AS keyword to specify aliases for columns in the rowset returned by the SELECT statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can you Concatenate or add 2 different data types?

A

NO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Explicit Conversion of Data Types?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Data Types : KEY POINTS

A

Transact-SQL supports a wide range of data types, which can be broadly categorized as exact numeric,approximate numeric, character, date/time, binary, and other (which includes specialized data types for handling data such as XML and spatial data).

Some data types are compatible, and values can be implicitly converted between them. Conversion between other data types requires the use of explicit conversion functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Working with NULLs

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

CASE Expression Syntax

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

KEY POINTS : NULL Datatype

A

NULL is used to indicate an unknown or missing value. NULL is not equivalent to zero or an empty string.

Arithmetic or string concatenation operations involving one or more NULL operands return NULL. For example, 12 + NULL = NULL.

If you need to compare a value to NULL, use the IS operator instead of the = operator.

The ISNULL function returns a specified alternative value for NULL columns and variables.

The NULLIF function returns NULL when a column or variable contains a specified value.

The COALESCE function returns the first non-NULL value in a specified list of columns or variables).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

You write a query that returns the Name and Price columns from a table named Product in the Production schema. In the resulting rowset, you want the Name column to be named ProductName.

Which of the following Transact-SQL statements should you use?

A

SELECT Name AS ProductName, Price FROM Production.Product;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

You need to retrieve data from a column that is defined as char(1). If the value in the column is a digit between 0 and 9, the query should return it as an integer value. Otherwise, the query should return NULL.

Which two functions can you use to accomplish this?

A
  • TRY_CAST
  • TRY_CONVERT
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

You write a Transact-SQL query that returns the Cellphone column from the Sales.Customer table. Cellphoneis a varchar column that permits NULL values. For rows where the Cellphone value is NULL, your query should return the text ‘None’. Select the correct function to complete the following query:

SELECT FirstName, LastName, __________(Cellphone, ‘None’) AS Cellphone

FROM Sales.Customer;

A

The ISNULL function substitutes the specified value for NULL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

ISNULL (Transact-SQL) Function

A

Examples:

SELECT Description, DiscountPct, MinQty, ISNULL(MaxQty, 0.00) AS ‘Max Quantity’ FROM Sales.SpecialOffer;

Testing for NULL in a WHERE clause

SELECT Name, Weight FROM Production.Product WHERE Weight IS NULL;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Removing Duplicates

A

In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values.

The DISTINCT keyword can be used to return only distinct (different) values.

Example

SELECT DISTINCT City FROM Customers;

SELECT COUNT (DISTINCT Country)

FROM Supplier;

SELECT DISTINCT Color,Size FROM Product;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you Sort Results?

A

ORDER BY

Example of Using ORDER BY and TOP expressions

SELECT TOP 10 Id, ProductName, UnitPrice, Package

FROM Product

ORDER BY UnitPrice DESC;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

OFFSET FETCH Clause

A

The OFFSET-FETCH clause provides you with an option to fetch only a window or page of results from the result set. OFFSET-FETCH can be used only with the ORDER BY clause.

Limitations in Using OFFSET-FETCH

ORDER BY is mandatory to use OFFSET and FETCH clause.

OFFSET clause is mandatory with FETCH. You can never use, ORDER BY … FETCH.

TOP cannot be combined with OFFSET and FETCH in the same query expression.

The OFFSET/FETCH rowcount expression can be any arithmetic, constant, or parameter expression that will return an integer value. The rowcount expression does not support scalar sub-queries.

Example 1 Skip first 10 rows from the sorted result set and return the remaining rows.

SELECT First Name + ‘ ‘ + Last Name FROM Employees ORDER BY First Name OFFSET 10 ROWS;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

KEY POINTS : ORDER BY

A

By default, the SELECT statement returns all rows. If mulitple rows contain the same values for every column, they are duplicated in the results. Using the DISTINCT keyword eliminates duplicates, ensuring that only onerow for each distinct combination of column values is returned.

The order of rows in the result of a SELECT statement is not guaranteed unless you explicitly specify one or more columns in an ORDER BY clause. You can specify sort direction as ASC (the default) or DESC.

You can combine the ORDER BY clause with the TOP keyword to retrict the results so that they include only the top n rows (where n is the number or percentage of rows you want to return).

You can implement a query to retrieve a specified “page” of results by using the OFFSET and FETCH keywords with the ORDER BY clause.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Filtering and Using Predicates

A

KEY POINTS

Use the WHERE clause to filter the results returned by a SELECT query based on a search condition.

A search condition is composed of one or more predicates.

Predicates include conditional operators (such as =, >, and <), IN, LIKE, and NOT.

You can use AND and OR to combine predicates based on Boolean logic.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the wild card character in SQL?

A

%

24
Q

LAB

you need to find the names, colors, and sizes of the products with a product model ID 1.

A

CODE:

SELECT Name,Color,Size from SalesLT.Product WHERE ProductModelID=1;

25
Q

TASK:

Retrieve the product number and name of the products that have a color of ‘black’, ‘red’, or ‘white’ and
a size of ‘S’ or ‘M’.

A

CODE:

SELECT ProductNumber, Name
FROM SalesLT.Product
WHERE Color IN (‘Black’,’Red’,’White’) and Size IN (‘S’,’M’);

26
Q

TASK:

Retrieve the product number, name, and list price of products whose product number begins ‘BK-‘.

A

CODE:

SELECT ProductNumber, Name, ListPrice
FROM SalesLT.Product
WHERE ProductNumber LIKE ‘BK-%’;

27
Q

Retrieve the product number, name, and list price of products whose product number begins ‘BK-‘.

Modify your previous query to retrieve the product number, name, and list price of products whose
product number begins ‘BK-‘ followed by any character other than ‘R’, and ends with a ‘-‘ followed by
any two numerals.

A

CODE:

SELECT ProductNumber, Name, ListPrice
FROM SalesLT.Product
WHERE ProductNumber LIKE ‘BK-[^R]%-[0-9][0-9]’;

28
Q

The SQL JOIN syntax

A

SELECT column-names

FROM table-name1 JOIN table-name2

ON column-name1 = column-name2

WHERE condition

29
Q

Inner Joins KEY POINTS:

A

Inner joins return only rows where a match can be found in both tables.

Inner joins that match rows based on columns containing the same value in both tables are sometimes referred to as equi-joins.

30
Q

SELF JOIN KEY POINTS

A
  • A self-join is an inner, outer, or cross join that matches rows in a table to other rows in the same table.
  • When defining a self-join, you must specify an alias for at least one instance of the table being joined.
31
Q

TASK:

write a query that returns the company name from the SalesLT.Customer table, and the sales order ID and total due from the SalesLT.SalesOrderHeader table.

A

CODE:

SELECT c.CompanyName, oh.SalesOrderID, oh.TotalDue
FROM SalesLT.Customer AS c
JOIN SalesLT.SalesOrderHeader AS oh
ON oh.CustomerID = c.CustomerID;

32
Q

TASK:

The sales manager wants a list of all customer companies and their contacts (first name and last name),
showing the sales order ID and total due for each order they have placed. Customers who have not
placed any orders should be included at the bottom of the list with NULL values for the order ID and
total due.

A

CODE:

SELECT c.CompanyName, c.FirstName, c.LastName, oh.SalesOrderID, oh.TotalDue
FROM SalesLT.Customer AS c
LEFT JOIN SalesLT.SalesOrderHeader AS oh
ON c.CustomerID = oh.CustomerID
ORDER BY oh.SalesOrderID DESC

33
Q

TASK :

Write a query that returns a list of customer IDs, company names, contact names
(first name and last name), and phone numbers for customers with no address stored in the database.

A

CODE:

SELECT c.CompanyName, c.FirstName, c.LastName, c.Phone
FROM SalesLT.Customer AS c
LEFT JOIN SalesLT.CustomerAddress AS ca
ON c.CustomerID = ca.CustomerID
WHERE ca.AddressID IS NULL;

34
Q

TASK:

Some customers have never placed orders, and some products have never been ordered. Create a query
that returns a column of customer IDs for customers who have never placed an order, and a column of
product IDs for products that have never been ordered. Each row with a customer ID should have a
NULL product ID (because the customer has never ordered a product) and each row with a product ID
should have a NULL customer ID (because the product has never been ordered by a customer).

A

CODE:

SELECT c.CustomerID, p.ProductID
FROM SalesLT.Customer AS c
FULL JOIN SalesLT.SalesOrderHeader AS oh
ON c.CustomerID = oh.CustomerID
FULL JOIN SalesLT.SalesOrderDetail AS od
ON od.SalesOrderID = oh.SalesOrderID
FULL JOIN SalesLT.Product AS p
ON p.ProductID = od.ProductID
WHERE oh.SalesOrderID IS NULL
ORDER BY ProductID, CustomerID;

35
Q

KEY POINTS: Union Query

A

Use UNION to combine the rowsets returned by mulitple queries.

Each unioned query must return the same number of columns with compatible data types.

By default, UNION eliminates duplicate rows. Specify the ALL option to include duplicates (or to avoid the overhead of checking for duplicates when you know in advance that there are none).

36
Q

KEY POINTS: INTERSECT and EXCEPT

A

Use INTERSECT to return only rows that are returned by both queries.

Use EXCEPT to return rows from the first query that are not returned by the second query.

37
Q

What does the UNION ALL statement do?

A

UNION ALL combines the results from both queries and retains duplicates.

38
Q

What does the INTERSECT Statement do?

A

INTERSECT returns only rows that are present in both query resultsets.

39
Q

What result does the following query return?

SELECT DISTINCT ProductID

FROM Sales.SalesOrderDetail

EXCEPT

SELECT ProductID

FROM Production.Product

WHERE Discontinued = 1

A

All non-discontinued products that have been sold

Combining queries using the EXCEPT set operator filters the results to include only rows that are returned by the first query but not by the second query.

40
Q

KEY POINTS : Functions

A

Scalar functions return a single value based on zero or more input parameters.

Logical functions return Boolean values (true or false) based on an expression or column value.

Window functions are used to rank rows across partitions or “windows”. Window functions include RANK, DENSE_RANK, NTILE, and ROW_NUMBER.

Aggregate functions are used to provide summary values for mulitple rows - for example, the total cost of products or the maximum number of items in an order. Commonly used aggregate functions include SUM, COUNT, MIN, MAX, and AVG.

41
Q

KEY POINTS: GROUP BY FUNCTIONS

A

You can use GROUP BY with aggregate functions to return aggregations grouped by one or more columns or expressions.

All columns in the SELECT clause that are not aggregate function expressions must be included in a GROUP BY clause.

The order in which columns or expressions are listed in the GROUP BY clause determines the grouping hierarchy.

You can filter the groups that are included in the query results by specifying a HAVING clause.

42
Q

What value will the following query return in the OrderStatus column for rows with a Status value of 2?

SELECT OrderNumber, CHOOSE(Status, ‘Ordered’, ‘Shipped’, ‘Delivered’) AS OrderStatus

FROM Sales.SalesOrderHeader

A

Shipped.

The CHOOSE function returns the value in the 1-based ordinal position of the list that corresponds to the value returned by the expression in the first parameter

43
Q

You run the following query:

SELECT COUNT(ProductID) AS ProductIDCount, COUNT(Quantity) AS QuantityCount, SUM(UnitPrice) AS PriceSum

FROM Sales.SalesOrderDetail;

What does the value returned by the query for the QuantityCount column represent?

A

The number of rows containing a Quantity value.

The COUNT function counts the number of rows containing a non-null value for the specified column or expression.

44
Q

GROUP BY CLAUSE : GOOD TO REMEMBER

A

You cannot use column aliases in a GROUP BY clause, so you must specify the columns or expressions on which you want to group. When the grouping fields represent a hierarchy, you should generally specify them in order of increasing granularity.

45
Q

TASK:

Write a query to return the product ID of each product, together with the product name formatted as upper case and a column named ApproxWeight with the weight of each product rounded to the nearest whole unit.

A

CODE:

SELECT ProductID,
UPPER(Name) AS ProductName,
ROUND(Weight, 0) AS ApproxWeight
FROM SalesLT.Product;

46
Q

KEY POINTS : Subqueries

A

Subqueries are Transact-SQL queries nested within an outer query.

Scalar subqueries return a single value.

Multi-valued subqueries return a single-column rowset.

47
Q

KEY POINTS : Corelates Subqueries

A

Correlated subqueries reference objects in the outer query.

48
Q

KEY POINTS : APPLY Query

A

The APPLY operator enables you to execute a table-valued function for each row in a rowset returned by a SELECT statement. Conceptually, this approach is similar to a correlated subquery.

CROSS APPLY returns matching rows, similar to an inner join. OUTER APPLY returns all rows in the original SELECT query results with NULL values for rows where no match was found.

49
Q

KEY POINTS : VIEW Query

A

Views are database objects that encapsulate SELECT queries.

You can query a view in the same way as a table, however there are some considerations for updating them.

50
Q

KEY POINTS : Temporary Tables and Variables

A

Temporary tables are prefixed with a # symbol and stored in a temporary workspace (the tempdb database in SQL Server).

Temporary tables are automatically deleted when the session in which they were created ends.

Excessive use of temporary tables can negatively affect overall database server performance.

Table variables are prefixed with a @ symbol and are stored in memory.

Table variables are scoped to the batch in which they are created.

Table variables work best with small sets of data.

51
Q

KEY POINTS: Querying Table-Valued Functions

A

Table-Valued Functions (TVFs) are functions that return a rowset.

TVFs can be parameterized.

52
Q

KEY POINTS : Common Table Expressions

A

A derived table is a subquery that generates a multicolumn rowset. You must use the AS clause to define an alias for a derived query.

Common Table Expressions (CTEs) provide a more intuitive syntax or defining rowsets than derived tables, and can be used mulitple times in the same query.

You can use CTEs to define recursive queries.

53
Q

KEY POINTS : INSERT STATEMENT

A

Use the INSERT statement to insert one or more rows into a table.

When inserting explicit values, you can omit identity columns, columns that allow NULLs, and columns on which a default constraint is defined.

Identity columns generate a unique integer identifier for each row. You can also use a sequence to generate unique values that can be used in multiple tables

54
Q

FIND EXAMPLES TO UPDATE,INSERT AND MERGE,DELETE DATA IN A TABLE

A
55
Q

KEY POINTS : UPDATE,INSERT,MERGE

A

Use the UPDATE statement to modify the values of one or more columns in specified rows of a table.

Use the DELETE statement to delete specified rows in a table.

Use the MERGE statement to insert, update, and delete rows in a target table based on data in a source table

56
Q
A