Clarification on database architecture question - sql

I'm working on a quiz for this internship and one question is worded strangely. I'm hoping that one of you could help me find clarification.
Context: I've just created a flat-file table (database), and added 4 columns (UserId,firstname,lastname,email). I filled each column with 15 rows of made-up data.
The question states "Query all rows in the firstname column that start with the letter B and ordered by the lastname column in descending order."
I'm not sure what they're asking for, does this make sense to you?

The question is asking you to query the table, selecting the firstname column and all data that starts with the letter 'B'. And then ordered by the lastname. It's a fairly basic query:
SELECT t.firstname
FROM tablename t
WHERE t.firstname like 'B%'
ORDER BY t.lastname DESC;
EDIT: I did forget the DESC;

The query consists in retrieving first names and last names of rows where the firstname starts with the letter B, and then to order the resulting set using the lastname field in descending order.
The query in sql would be like:
SELECT firstname, lastname FROM users WHERE firstname LIKE 'B%' ORDER BY lastname DESC;

Related

Ambiguous column name - whats wrong with the syntax here?

I cant seem to figure out what is wrong with the SQL here, when an asterisk (*) is included in the SELECT statement. eg:
SELECT firstname, lastname, createdon, * from Person
Where firstname like '%J%'
Order By createdon desc
I get 'Ambiguous column name 'CreatedOn'. error.
However without the (*) where its not returning the remainder of the columns it works fine.
Any suggestion or workaround?
createdon is in the returned dataset twice, once from the explicit call, and once from the *. As such there are 2 columns with the name createdon and so ORDER BY createdon is ambiguous; do you want to order by the first column named createdon or the second one (the fact that they would have same value is irrelevant, as SQL Server just sees 2 columns with the same name).
Really, you shouldn't be using SELECT * and should be defining all your columns; I don't see a need to return 3 of columns twice. But what you can do if you "must" have 2 copies of the same column is to prefix the one in the ORDER BY with the table name/alias; this would then refer to the column "in" the table, not the one in the result set (of which there are 2). I use an alias here:
SELECT P.firstname,
P.lastname,
P.createdon,
* --Replace this with the actual columns you need, don't be lazy
FROM dbo.Person P
WHERE P.firstname like '%J%'
ORDER BY P.createdon DESC;
In your query, you are selecting "createdon" column twice and but ordering the results by "one of them. The SQL interpreter doesn't understand which "createdon" column it needs to sort the result and so Ambiguous column name is returned. You can solve this by using aliasing one of the "createdon" in the selected statement.
im not sure but try with that
SELECT firstname, lastname, createdon createdon2, * from Person
Where firstname like '%J%'
Order By createdon desc

SQL Query with records starts with and contain with

QUESTION: I need to develop a query that looks for certain records that starts with a search term and records that contains the search term. Furthermore, both subsets should be sorted by a certain column, whereas the resultant set shouldn't be sorted. Records starting with term should come above the contains term records.
Example: I have students table and I want all students whose names start with "Jhon". Students having the first name "Jhon" should come first and after then all those students whose last name is "Jhon".
What I have are as following:
Got all records starting with the search term and save it into a temptable_A , than got all records all records containing the search term and excluding results that are already in temptable_A and save into temptable_B. Now both temptable should have respected results, so I dump tempTable_B into tempTable_A, believing that the new records are append at last of the table. But they are not, they are inserted in and are sorted, where are I haven't applied sorting.
I have done the same with a merge statement and it does the same thing, but no fruitful result.
I have tried Union between both sub queries (Start with and contains) but the resultant dataset always doesn't show the start with records on top.
Scenario:
Students Table with column
Id | Student
select * FROM students where name like 'jhon%'
UNION
select * FROM students where name like '%jhon%'
Use an order by. For instance:
select s.*
from students
where name like '%jhon%'
order by charindex('jhon', name);
This orders by how far down 'jhon' is in the string. If you just want the ones that start 'jhon' first, you can use a case expression:
order by (case when name like 'jhon%' then 1 else 2 end)
You can do this with a case expression in the ORDER BY clause:
select * from students where Name like '%jhon%' -- select all students containing john
order by
case -- order by place of match first
when Name like 'john%' then 0
when Name like '%john%' then 1
end,
Name -- then order by Name

Count specific column in DB2

I have a table contact with three columns e.g. name, surname and age.
I would like to count the number of entries from the specific column surname.
How looks the select statement in DB2 to achieve this?
You can change the column name using as :
select count(surname) as surname_count
from contact c;
I assume you want to perform a
select count(surname)
from contact
group by surname
but you need to put some effort into the question and prove you have already researched a bit beforehand

Extract info from one table based on data from antoher

I am kind of new to SQL and I made a couple of tables to practice. The columns may have some unrelated categories but I don't know what else write...
Anyway, basically what i want to do is get info from two tables based on the first and last name from one table.
Here are my tables:
Order
Host
I want create a query to pull the ticket number, height, order, subtotal and total by first and last name. The only orders I want to pull are from John Smith And Sam Ting. So in the end, I want my extraction to have the following columns:
Ticket Number
First Name
Last Name
Height
Order
Subtotal
Total
Any help or direction would be awesome!
With the assumption the tables both have unique Ticket_Numbers and that will provide a one-to-one mapping between then.
SELECT
Order.Ticket_Number,
First_Name,
Last_Name,
Height,
Order,
Subtotal,
Total
FROM Order
JOIN Host on Host.Ticket_Number = Order.Ticket_Number
WHERE
(First_Name = 'John' AND Last_Name = 'Smith')
OR (First_Name = 'Sam' AND Last_Name = 'Ting')
You need to "call" the table name first, and then the column. After that you need to use the "join" for the 2 tables. And finally you need the "where". I didn't look for the details so you need to check the "names".
SELECT Order.Ticket_Number, Order.First_Name, Order.Last_Name, Order.Height, Order.Order, Cost.Subtotal, Cost.Total
FROM Order
INNER JOIN Cost
where First_Name="Jhon" and Last_Name="blablabla"
or
First_Name="SecondGuy" and Last_Name="blablabla"

How to randomize order of data in 3 columns

I have 3 columns of data in SQL Server 2005 :
LASTNAME
FIRSTNAME
CITY
I want to randomly re-order these 3 columns (and munge the data) so that the data is no longer meaningful. Is there an easy way to do this? I don't want to change any data, I just want to re-order the index randomly.
When you say "re-order" these columns, do you mean that you want some of the last names to end up in the first name column? Or do you mean that you want some of the last names to get associated with a different first name and city?
I suspect you mean the latter, in which case you might find a programmatic solution easier (as opposed to a straight SQL solution). Sticking with SQL, you can do something like:
UPDATE the_table
SET lastname = (SELECT lastname FROM the_table ORDER BY RAND())
Depending on what DBMS you're using, this may work for only one line, may make all the last names the same, or may require some variation of syntax to work at all, but the basic approach is about right. Certainly some trials on a copy of the table are warranted before trying it on the real thing.
Of course, to get the first names and cities to also be randomly reordered, you could apply a similar query to either of those columns. (Applying it to all three doesn't make much sense, but wouldn't hurt either.)
Since you don't want to change your original data, you could do this in a temporary table populated with all rows.
Finally, if you just need a single random value from each column, you could do it in place without making a copy of the data, with three separate queries: one to pick a random first name, one a random last name, and the last a random phone number.
I suggest using newid with checksum for doing randomization
SELECT LASTNAME, FIRSTNAME, CITY FROM table ORDER BY CHECKSUM(NEWID())
In SQL Server 2005+ you could prepare a ranked rowset containing the three target columns and three additional computed columns filled with random rankings (one for each of the three target columns). Then the ranked rowset would be joined with itself three times using the ranking columns, and finally each of the three target columns would be pulled from their own instance of the ranked rowset. Here's an illustration:
WITH sampledata (FirstName, LastName, CityName) AS (
SELECT 'John', 'Doe', 'Chicago' UNION ALL
SELECT 'James', 'Foe', 'Austin' UNION ALL
SELECT 'Django', 'Fan', 'Portland'
),
ranked AS (
SELECT
*,
FirstNameRank = ROW_NUMBER() OVER (ORDER BY NEWID()),
LastNameRank = ROW_NUMBER() OVER (ORDER BY NEWID()),
CityNameRank = ROW_NUMBER() OVER (ORDER BY NEWID())
FROM sampledata
)
SELECT
fnr.FirstName,
lnr.LastName,
cnr.CityName
FROM ranked fnr
INNER JOIN ranked lnr ON fnr.FirstNameRank = lnr.LastNameRank
INNER JOIN ranked cnr ON fnr.FirstNameRank = cnr.CityNameRank
This is the result:
FirstName LastName CityName
--------- -------- --------
James Fan Chicago
John Doe Portland
Django Foe Austin
select *, rand() from table order by rand();
I understand some versions of SQL have a rand() that doesn't change for each line. Check for yours. Works on MySQL.