Prep Database SQL Server Queries

  1. How many Venn diagrams represent SQL joins? Draw each. How would you write each one using a join query?
    • Seven Venn diagrams each, represented by:
    • 1. SELECT * FROM A LEFT JOIN B ON A.KEY = B.KEY
    • 2. SELECT * FROM A RIGHT JOIN B ON A.KEY = B.KEY
    • 3. SELECT * FROM A LEFT JOIN B ON A.KEY = B.KEY AND B.KEY IS NULL
    • 4. SELECT * FROM A RIGHT JOIN B ON A.KEY = B.KEY AND A.KEY IS NULL
    • 5. SELECT * FROM A INNER JOIN B ON A.KEY = B.KEY
    • 6. SELECT * FROM A FULL OUTER JOIN B ON A.KEY = B.KEY 
    • 7. SELECT * FROM A FULL OUTER JOIN B ON A.KEY = B.KEY AND A.KEY IS NULL OR B.KEY IS NULL
  2. What is the difference between a LEFT JOIN and an INNER JOIN?
    An inner join is one in which both tables share a common key match and so those record rows are returned. In a left join, all records in the left table are returned, even if no matches on the key is found.
  3. What is a primary key, foreign key, and composite key?
    A primary key is one which is unique and used to describe a single record. Almost always it is indexed for fast retrieval. A foreign key is a key reference to a primary key within another table. A composite key is a key which requires two or more columns to define the key.
  4. What is SQL Server? What other database types exist?
    SQL is a relational database created by Microsoft. Others include DB2, Oracle, and mySQL
  5. What are common SQL types?
    Int, char, varchar, bit, binary, blob, nchar, datetime, timestamp, decimal, text, Boolean, float, double, date, time, year
  6. What’s an index and why is it important? What types exist?
    Two types exist, clustered and non-clustered. Only one clustered can exist on a table which is a valued type, usually the primary key and usually in succession (ordered). The non-ordered indexes are reference types and are not as quick as a clustered but are often used for quick retrieval, updates, etc.
  7. What is normalization and denormalization? When would you use one over the other?
    Normalization is the process of massaging the data to improve data integrity and eliminate redundancies. Denormalization is the flattening of the data and is almost exclusively used in reporting as it produces very quick results without having to reference additional tables.
  8. What are database objects? Give several examples.
    Database objects are objects located directly within the database; examples can include procedural database objects which are stored procedures, user defined functions, and triggers but not scripts as these are external to the application itself.
  9. What’s a trigger?
    An event which is placed on an INSERT, DELETE, or UPDATE
  10. What are the different join types? Describe each.
    An INNER JOIN is one which both sides of the table meet the condition. A LEFT JOIN is one in which all elements in the left side are returned and those in the right are either present or displayed as NULL values. RIGHT is same as LEFT but reversed. Two others are used, albeit infrequently, including CROSS JOIN AND UNION/UNION ALL.
  11. Define a user defined function. What are some characteristics.
    Custom function which takes 0-n arguments and returns either a single scalar value or a table value. Some characteristics is that it cannot call a stored procedure nor do any modification changes to the database such as an INSERT or DELETE.
  12. Define a stored procedure. What are some characteristics?
    Custom database object which is compiled and stored in the database for fast execution. Unlike the function, it isn’t compiled on the fly, it can take 0-n arguments, and may or may not return a scalar value or table. In addition, it contain complex flow logic, perform modification changes to the database, can call other stored procedures, can contain error handling, transaction processing, and more.
  13. What’s the difference between an Index and a Key?
    An Index is a structural mechanism which allows easy, quick retrieval of records whereas a key is a record identifier.
  14. How can we preserve data integrity or SQL injection attacks into the database?
    Filtering data such as column constraints work on the columns themselves, however, SQL Injection attacks should be doing filtering at the client level by preventing dynamic SQL calls and the use of stored procedures to make sure data types and proper values are being sent to the user.
  15. What are 10+ common built in string manipulation functions?
    LTRIM(), TRIM(), LEN(), RIGHT(), SUBSTRING(), REPLACE(), REVERSE(), INDEX(), CONCATE(), COALESCE(), ISDATE(), ISNULL(), LOWER(), UPPER(), DAY(), MONTH(), YEAR(), MIN(), MAX(), FLOOR()
  16. What is an Identity column? How is this different than a Primary Key?
    Column generated by the database itself and may or may not be unique. Whereas a Primary Key is a unique identifier, an identity can be one type of primary key, that is, the identity column may not be automatically generated from the database but input by the user such as a SSN would.
  17. Write a CASE example.
    • SELECT 
    •      ID,
    •      CASE VENDORID
    •           WHEN 1 THEN ‘A’
    •           WHEN 2 THEN ‘B’
    •           ELSE ‘C’
    •      END AS VENDORCHECK
    • FROM LEADS
  18. Write a begin-end block with a transaction check.
    BEGIN TRY BEGIN TRAN (….) COMMIT TRAN END TRY BEGIN CATCH ROLLBACK TRAN END CATCH
  19. Write a script to create a table called Lead. Use a primary key, dob, created field. Using a comment section, how would we do this if we wanted to create a temporary instance or a global temporary instance of this?
    • /* Use # before LEAD name for local temp table and ## for a global temp version */
    • CREATE TABLE LEAD
    • (
    •    ID INT NOT NULL IDENTITY PRIMARY KEY,
    •    NAME VARCHAR(30) NOT NULL,
    •    SEX CHAR(1) NOT NULL DEFAULT ‘M’,
    •    DOB DATE,
    •    CREATED DATETIME NOT NULL DEFAULT GETDATE()
    • )
  20. Write a query that uses two aggregate functions and a minimum Price field greater than 0.
    SELECT NAME, COUNT(NAME), SUM(Price) FROM INVOICE GROUP BY Name HAVING SUM(Price) > 0 ORDER BY Name ASC;
  21. Write a query that uses an alias for tables and an inner join.
    SELECT L.Name AS ‘Client Name’, I.InvoiceId AS ‘Invoice #’ FROM Leads L INNER JOIN INVOICE I ON L.InvoiceId = I.Id;
  22. Write an query to edit the name on a Lead table.
    UPDATE Leads SET Name = ‘Frank’ WHERE Id = 313;
  23. Write a query to insert a new record into the Lead table.
    INSERT INTO Leads (name, dob) VALUES (‘Frank’, ‘1971-10-1’);
  24. Write a query to insert 2 new records into the Lead table.
    INSERT INTO Leads (name, dob) VALUES (‘Frank’, 2), (‘Dorthy’, 3);
  25. Write a query to remove a record from the table.
    DELETE FROM Leads WHERE id = 31;
  26. Write a statement to drop a table and to truncate a table. What’s the difference?
    • DROP TABLE Leads; TRUNC TABLE Leads;
    • The difference is that dropping a table updates the log with every change so on very large tables this can take hours to delete and update every record whereas on a truncate, the log isn’t updated, the pointers are just removed and so this takes a millisecond. It is very dangerous to do a truncate as it can’t be recovered from; however, it is useful depending on the circumstance.
  27. Write a query to grab the best five unique salesmen.
    SELECT TOP 5 DISTINCT name FROM Leads WHERE SUM(sales) > 500;
  28. How do we check between dates in SQL? Get current date?
    • WHERE DOB BETWEEN ‘2017-01-01’ AND ‘2018-12-31’
    • SELECT GETDATE();
  29. Declare a varchar and an integer value which has a value of 15;
    DECLARE @firstname AS VARCHAR(30) ;
  30. Write a query that returns a data set with all names that start with M and at least 3 characters long. What are the two symbols used to perform this query?
    • SELECT Name WHERE name LIKE ‘M__%’;
    • /* The % sign is used as a wild card meaning many and the underscore is used to refer to any one character.
  31. Create a new table which is copied from another table.
    SELECT * INTO LeadsCopy FROM Leads;
  32. Write a query to change an integer value into a print statement. Write it using a different change function.
    • SELECT ‘The children are ‘ + cast(age as varchar) + ‘ years old.’;
    • SELECT ‘The children are ‘ + convert(varchar, age) + ‘years old.’;
  33. Show the symbols for greater than, less than or equal to, equal and not equal. What about to test if something is null?
    A > B; A <= B; A = B; A <> B;

    SELECT ID, NAME FROM LEADS WHERE MODIFIED IS NULL;
  34. Write a query to display how many days old the lead is using the DOB field.
    SELECT name, datediff(day, dob, getdate()) as ‘ days old’ FROM Leads;
  35. What are the relationship types used to describe two tables interaction with one another? Give an example of how each would be used at a school.
    One-to-one (each student should have one address), one-to-many (each student can have multiple teachers or multiple report cards), and many-to-many (each student can have multiple classes and each class can have multiple students).
  36. What is the difference between IS NULL and ISNULL?
    The IS NULL condition refers to a column which contains a NULL value. If we return a data set with all values greater than zero and a NULL value is present in this field as opposed to 0.00 then it wouldn’t be returned, to include it we would use ‘OR IS NULL’ expression. ISNULL() is a function which takes two required parameters of the form ISNULL(expression, value) which means to test the expression and if it contains something, then return it, otherwise if null, return the value in the value area.
  37. What are optional parameters? How do they work?
    Parameters with a default value of NULL are optional parameters meaning it may or may not be sent.
  38. How would we call a stored procedure with 2 parameters from the query window?
    EXEC spListOfVendors ‘USA’, 5000;
  39. Write a function which returns the udf_GetAge(Id) value as a table.
    SELECT Name, Id, dbo.udfGetAge(Id);
  40. How do we throw an error in SQL? How can we check?
    • THROW 50001, ‘Not a valid Id’, 1;
    • We can check by using a TRY CATCH block or by using the @@ERROR <> 0 or @@Identity check.

    • Write code to check for an error and write a message to user.
    • IF @@ERROR <> 0
    •    BEGIN
    •       PRINT N’An error occurred: ‘ + ERROR_MESSAGE();
    •       RETURN 0;
    •    END
    • GO
  41. How is concurrency handled in SQL? Why is this important?
    Several types of errors can exist when two individuals try to modify data in the database concurrently and these create concurrency issues. To prevent this, an administrator typically changes the locking mechanism behavior of the database as a whole coupled with programmers who write transactional updates to the system. Doing this prevents the four types of concurrency errors including phantom reads, nonrepeatable reads (on datasets), dirty reads, and lost updates.
  42. What is a view and why do we use it?
    A view is a virtual table in that the data is not stored directly like a table but is still accessible. It can be used to restrict access (subset of a table) or to abstract complexity (combining of multiple tables) while also offering a bit of security.
  43. Can a view be created like a stored procedure? If so, how?
    Yes… simply by returning the results of a query. SELECT id, name FROM Leads WHERE dob >= ‘2000-01-01’;
  44. Write a stored procedure returning a dataset and accepting 2 parameters.
    jQuery112409895917431100423_1606929746416?
  45. Write a stored procedure which returns an output parameter.
    ???
  46. Write a user defined function which returns how many years old a person is using their birthday.
    ???
  47. What’s a clustered index vs. a non-clustered index?
    Every table can include multiple indexes, however, only one type of clustered index can exist on a table as this is the index used to refer to a specific (value type) record. Non-clustered indexes are reference types which contain pointers to their value thus take longer to process.
  48. What is done to a column to improve performance of queries?
    Most common is to add a clustered index (ie, primary key) to a table followed by one or more non-clustered indexes for those columns which are commonly referenced in queries. A candidate for consideration for an index column would be one which is (a) frequently called, (b) contains many distinct values, or (c) is updated frequenty.
  49. What are the two files created when you first create a database and what are their functions?
    The MDF file is created which contains the actual data and an LDF file is created which will contain all the changes as it is a log file of every change to the database.
  50. What is usually created to run lots of code at different times of the night or perform numerous types of jobs?
    Scripts are created for extra large jobs or to run batch jobs done at night, etc.
  51. Create a copy of the Leads table into a temp table. How long does this table exist?
    SELECT * INTO #LeadsCopy FROM Leads; /* The table exists as long as the current local session is active */
  52. Write a dynamic SQL statement.
    EXEC (‘SELECT * FROM LEADS;’);
  53. What is a deadlock?
    Occurs when two users try to simultaneously access the same record by placing a lock on the other party, yet, both are waiting for the other and so neither can complete their action.
Author
mateotete
ID
353870
Card Set
Prep Database SQL Server Queries
Description
Questions on database queries and SQL Server.
Updated