SQL Flashcards
Given a table Employee having columns empName and empId, what will be the result of the SQL query below?
select empName from Employee order by 2 desc;
“Order by 2” is only valid when there are at least two columns being used in select statement. However, in this query, even though the Employee table has 2 columns, the query is only selecting 1 column name, so “Order by 2” will cause the statement to throw an error while executing the above sql query.
Write a SQL query to find the 10th tallest peak (“Elevation”) from a “Mountain” table. Assume that there are at least 10 records in the Mountain table. Explain your answer.
SELECT DISTINCT TOP (10) Elevation FROM Mountain ORDER BY Elevation DESC
What is a NULL value? what are the differences with zeros or a blank space
A field with a NULL value is a field with no value. A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation. Assume, there is a field in a table is optional and it is possible to insert a record without adding a value to the optional field then the field will be saved with a NULL value.
As I mentioned earlier, Null value is field with no value which is different from zero value and blank space.
Null value is a field with no value.
Zero is a number
Blank space is the value we provide. The ASCII value of space is CHAR(32).
How do you return just a limit amount of lines from a sql table?
You can use sql select top (or LIMIT or ROWNUM Clause)
Is the command JOIN an inner JOIN?
yes
What can you use in a WHERE clause to search for a specified pattern in a column??
LIKE
SELECT * FROM Customers
WHERE CustomerName LIKE ‘_r%’;
There are two wildcards often used in conjunction with the LIKE operator:
% - The percent sign represents zero, one, or multiple characters
_ - The underscore represents a single character
How do you add a column to a table?
The ALTER TABLE statement is used to modify the columns of an existing table. When combined with the ADD COLUMN clause, it is used to add a new column.
ALTER TABLE table_name
ADD column_name datatype;
How to order elemets in a quey
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
SELECT column1, column2, …
FROM table_name
ORDER BY column1, column2, … ASC|DESC;
Can you use = or != operator to look for NULL values?
Not you have to use the
IS NULL or
IS NOT NULL
operator
Table is as follows:
ID C1 C2 C3
1 Red Yellow Blue
2 NULL Red Green
3 Yellow NULL Violet
Print the rows which have ‘Yellow’ in one of the columns C1, C2, or C3, but without using OR.
SELECT * FROM table WHERE ‘Yellow’ IN (C1, C2, C3)
What is an index in an SQL database?
A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of data. Data can be stored only in one order on disk. To support faster access according to different values, faster search like binary search for different values is desired. For this purpose, indexes are created on tables. These indexes need extra space on disk, but they allow faster search according to different frequently searched values.
Get all the attributes from the table
SELECT * FROM STUDENT WHERE ROLL_NO>2;
How would you get two attributes from a table in SQL?
If we want to retrieve attributes ROLL_NO and NAME of all students, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT;
Write a SQL query using UNION ALL (not UNION) that uses the WHERE clause to eliminate duplicates. Why might you want to do this?
You can avoid duplicates using UNION ALL and still run much faster than UNION DISTINCT (which is actually same as UNION) by running a query like this:
SELECT * FROM mytable WHERE a=X UNION ALL SELECT * FROM mytable WHERE b=Y AND a!=X
The key is the AND a!=X part. This gives you the benefits of the UNION (a.k.a., UNION DISTINCT) command, while avoiding much of its performance hit.
How can you remove rows from. a table?
The DELETE statement is used to delete records (rows) in a table. The WHERE clause specifies which record or records that should be deleted. If the WHERE clause is omitted, all records will be deleted.
DELETE FROM table_name
WHERE some_column = some_value;
How would you query attributes in order?
SELECT * FROM STUDENT ORDER BY AGE ASC;
SELECT * FROM STUDENT ORDER BY AGE DESC;
Tell us more about the GROUPBY clause?
What is it used for?
GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
- The GROUP BY clause groups records into summary rows.
- GROUP BY returns one records for each group.
- GROUP BY typically also involves aggregates: COUNT, MAX, SUM, AVG, etc.
- GROUP BY can group by one or more columns.
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;
if you want the custumer id and the country you need a groupby otherwise you can call this without groupby and get total count.
example with join
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
BETWEEN Operator
The BETWEEN operator can be used to filter by a range of values. The range of values can be text, numbers or date data. The given query will match any movie made between the years 1980 and 1990, inclusive.
SELECT * FROM movies WHERE year BETWEEN 1980 AND 1990;
In a database what are Table, Field, Record and column, what do they refer to?
A table is a database object used to store records in a field in the form of columns and rows that holds data.
A field in a Database table is a space allocated to store a particular record within a table.
A record (also called a row of data) is an ordered set of related data in a table.
A column is a vertical entity in a table that contains all information associated with a specific field in a table.
How do you remove an element from a table?
You can use the DELETE command.
DELETE FROM table_name WHERE some_condition;
table_name: name of the table some_condition: condition to choose particular record.
Where of course is used to selectively delete stuff
What is wrong with this SQL query? Correct it so it executes properly.
SELECT Id, YEAR(BillingDate) AS BillingYear FROM Invoices WHERE BillingYear >= 2010;
The expression BillingYear in the WHERE clause is invalid. Even though it is defined as an alias in the SELECT phrase, which appears before the WHERE phrase, the logical processing order of the phrases of the statement is different from the written order. Most programmers are accustomed to code statements being processed generally top-to-bottom or left-to-right, but T-SQL processes phrases in a different order.
The correct query should be:
SELECT Id, YEAR(BillingDate) AS BillingYear FROM Invoices WHERE YEAR(BillingDate) >= 2010;
AS Clause:
Columns or tables in SQL can be aliased using the AS clause. This allows columns or tables to be specifically renamed in the returned result set. The given query will return a result set with the column for name renamed to movie_title.
SELECT name AS ‘movie_title’ FROM movies;
What do you mean by foreign key?
A Foreign key is a field which can uniquely identify each row in another table. And this constraint is used to specify a field as Foreign key. That is, this field points to primary key of another table. This usually creates a kind of link between the two tables.
CREATE TABLE Orders ( O_ID int NOT NULL, ORDER_NO int NOT NULL, C_ID int, PRIMARY KEY (O_ID), FOREIGN KEY (C_ID) REFERENCES Customers(C_ID) )
How does aliases work in SQL?
Aliases are the temporary names given to table or column for the purpose of a particular SQL query
Aliases are created to make table or column names more readable. The renaming is just a temporary change and table name does not change in the original database. Aliases are useful when table or column names are big or not very readable. These are preferred when there are more than one table involved in a query
SELECT column FROM table_name as alias_name;
SELECT column as alias_name FROM table_name;
What is a primary key?
A primary key is a combination of fields which uniquely specify a row. This is a special kind of unique key, and it has implicit NOT NULL constraint. It means, Primary key values cannot be NULL.
What is the difference between BETWEEN and IN operators in SQL?
The BETWEEN operator is used to fetch rows based on a range of values.
For example,
SELECT * FROM Students WHERE ROLL_NO BETWEEN 20 AND 30;
IN
The IN operator is used to check for values contained in specific sets.
For example,
SELECT * FROM Students WHERE ROLL_NO IN (20,21,23);
Given a table name A with a column x —— 2 -2 4 -4 -3 0 2
Write a single query to calculate the sum of all positive values of x and he sum of all negative values of x.
select sum(case when x>0 then x else 0 end)sum_pos,sum(case when x<0 then x else 0 end)sum_neg from a;
Is SQL executed in the logical order?
No as long as the result is the same as the logical order the optimizer according to the schema and how data are saved on disk is free to use the order it wants
Write a query to insert/update Col2’s values to look exactly opposite to Col1’s values.
Col1Col2
10
01
01
01
10
01
10
10
update table set col2 = case when col1 = 1 then 0 else 1 end
Or if the type is numeric:
update table set col2 = 1 - col1
JOIN clause and format
The JOIN clause allows for the return of results from more than one table by joining them together with other results based on common column values specified using an ON clause. INNER JOIN is the default JOIN and it will only return results matching the condition specified by ON.
SELECT * FROM books JOIN authors ON books.author_id = authors.id;
How do you add a row to a table? command and examples
The INSERT INTO statement is used to add a new record (row) to a table.
It has two forms as shown:
Insert into columns in order.
Insert into columns by nam
– Insert into columns in order: INSERT INTO table_name VALUES (value1, value2); – Insert into columns by name: INSERT INTO table_name (column1, column2) VALUES (value1, value2);
WITH Clause
The WITH clause stores the result of a query in a temporary table (temporary_movies) using an alias.
Multiple temporary tables can be defined with one instance of the WITH keyword.
How would you create a table with columns constraints?
What constrains are available?
Column constraints are the rules applied to the values of individual columns:
PRIMARY KEY constraint can be used to uniquely identify the row.
UNIQUE columns have a different value for every row.
NOT NULL columns must have a value.
DEFAULT assigns a default value for the column when no value is specified.
There can be only one PRIMARY KEY column per table and multiple UNIQUE columns.
CREATE TABLE student
( id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
grade INTEGER NOT NULL,
age INTEGER DEFAULT 10
);
Using the BETWEEN operator, write a query that selects all information about movies whose name begins with the letters ‘D’, ‘E’, and ‘F’.
SELECT *
FROM movies
WHERE name BETWEEN “D” and “G”;
How do you get only a unique list of attributes wih no repetitions?
SELECT DISTINCT ADDRESS FROM STUDENT;
How do you get the Nth-highest salary from the Employee table in SQL
SELECT salary from Employee order by salary DESC LIMIT 2,1