MySQL rename column - mysql

This is a homework question I had but I just wasn't sure if I got the correct answer. The question was:
Write a SQL statement to count the number of rows in the relation R(A, B, C) and rename the result column as num
My answer:
COUNT(*) AS num
Is this correct or do I have to use ALTER?

No, you've got it right. ALTERis used to change existing database objects (for example the name of a table - it's a data definition statement (DDL)). Using ASgives your result an alias, so this statement:
SELECT COUNT(*) AS num FROM TABLE_A
would count the number of rows in the table and output the result in a column named num. Note that the count is not for distinct rows unless you specify it, or use agroup byclause, so if there are duplicate rows they would all get counted.

Yeah, you got the right answer. Using alias is way in renaming fieldname in using SQL Statement.
SELECT COUNT(*) AS num FROM TABLE

Related

mysql sql weird issue?

return multiple data
why?
mysql sql :
select * from t_book where id=(select round(max(id)*rand()) from t_book)
As suggested by #Tarek you might have duplicated id values. To find out which you can run this query:
SELECT id, COUNT(*) c FROM t_book GROUP BY id HAVING c > 1;
On the assumption that "id" is a unique primary key value, it shouldnt return multiple values. In the returned values do all of the "id" fields match, or is it returning multiple varying ids?
You have a Syntax error,
The function Round takes the form:
ROUND(N,[D]);
The problem is not with your id column's uniqueness.
select round(max(id)*rand()) from t_book
This will return various number of ids, at least in mysql 5.6. I don't know why, but it's really weird.
You can try this, for selecting a random record from your table:
select * from t_book order by rand() limit 1;
If you stick with this round-max-random method, keep in mind that round can return 0 too and it's unlikely that you have a 0 id.
First I thought this is caused by duplicate id values. You can try this fiddle, and see what happens: http://sqlfiddle.com/#!9/7fc510/1.
For multiple runs I got 0, 1 or 2 result records.

what is defined behavior of group by column name and number in mysql

when exucute the sql statement list below in mysql, there is only one row returned. And I looked up the mysql document and didn't find the defined behavior of the statement. Is there any syntax error in this statement?
select * from Deal group by id and 1;
Demo on sqlfriddle
Look at what happens when you use the following:
select *, id and 1 as newCol from Deal
Fiddle
newCol equals 1 for each row. That's because mysql evaluates that as a boolean. This explains why you only return a single result with group by, you are grouping by the same value in every record.
Perhaps you are wondering what happens when you group by a number with a comma instead of using and:
select * from Deal group by id, 2
More fiddle
That groups by both the id and the second field in your table (price).

Group by statement column name resolution

I have a query like this (more columns in reality)
select
custom_amend_column_function(colname) as colname
from source_table
group by colname
I've used this construct a lot.It appears to have always used the output from the function rather than the input to group data by.
Now for the first time today I have run this statement directly into a new table like this:
create table new_table as
select
custom_amend_column_function(colname) as colname
from source_table
group by colname
Curiously by adding the first line, I am getting an error message that my query is using an ambiguous column name in the group statement.
As group by can use new column names (ie. the below works) I always expected that group by will first use the columns defined in the select statement and then look at the underlying table(s) if it cannot find the names.
select
custom_amend_column_function(colname) as new_colname
from source_table
group by new_colname
Am I right? Is the error message right? I cannot find any place this is documented either for the SQL standard or for MySQL.
I know I could avoid this by just creating a new column name, but I want to figure this out as I may need to review existing queries if it is indeed ambiguous.
To trace the problem do an
EXPLAIN EXTENDED SELECT ...
On your query. Beside the normal output this will give you a warning containing the query as it is seen by the optimizer. All implicit renaming is done here, so you can see why the column name is ambiguous.
I think you can solve this by saying
... GROUP BY 1
instead of providing the column name in the group by.

Select Left(columnA,2) or right(columnA,1)

Is there a way in MySql to use an either or in a select column. For instance
select left(columnA,2) or right(columnA,1) as columnAlias, sum(columnB)
from table
where ((left(columnA,2) in ('aa','bb','cc')) or (right(columnA,1) in ('a,','b','c')))
group by columnAlias
what I have is a table where either the first 2 characters of the column or the last character of the column indicates the facility. I need to sum the values by facility. A union gets me part way there then I could loop through the resulting dataset and sum things up in the code (or do a stored proc to return the sums), but I am wondering if there is a way to just get it from the query.
I've tried using the union query as an on the fly temp table and doing the select and group on that but if there are no records returned from either of the select statments then it throws a "column columnA cannot be null error.
Also tried with the syntax above, but not getting the results I am expecting. Any other ways to do this through the query?
using a CASE would prob be your best bet here.
http://dev.mysql.com/doc/refman/5.0/en/case-statement.html

What does it mean by select 1 from table?

I have seen many queries with something as follows.
Select 1
From table
What does this 1 mean, how will it be executed and, what will it return?
Also, in what type of scenarios, can this be used?
select 1 from table will return the constant 1 for every row of the table. It's useful when you want to cheaply determine if record matches your where clause and/or join.
SELECT 1 FROM TABLE_NAME means, "Return 1 from the table". It is pretty unremarkable on its own, so normally it will be used with WHERE and often EXISTS (as #gbn notes, this is not necessarily best practice, it is, however, common enough to be noted, even if it isn't really meaningful (that said, I will use it because others use it and it is "more obvious" immediately. Of course, that might be a viscous chicken vs. egg issue, but I don't generally dwell)).
SELECT * FROM TABLE1 T1 WHERE EXISTS (
SELECT 1 FROM TABLE2 T2 WHERE T1.ID= T2.ID
);
Basically, the above will return everything from table 1 which has a corresponding ID from table 2. (This is a contrived example, obviously, but I believe it conveys the idea. Personally, I would probably do the above as SELECT * FROM TABLE1 T1 WHERE ID IN (SELECT ID FROM TABLE2); as I view that as FAR more explicit to the reader unless there were a circumstantially compelling reason not to).
EDIT
There actually is one case which I forgot about until just now. In the case where you are trying to determine existence of a value in the database from an outside language, sometimes SELECT 1 FROM TABLE_NAME will be used. This does not offer significant benefit over selecting an individual column, but, depending on implementation, it may offer substantial gains over doing a SELECT *, simply because it is often the case that the more columns that the DB returns to a language, the larger the data structure, which in turn mean that more time will be taken.
If you mean something like
SELECT * FROM AnotherTable
WHERE EXISTS (SELECT 1 FROM table WHERE...)
then it's a myth that the 1 is better than
SELECT * FROM AnotherTable
WHERE EXISTS (SELECT * FROM table WHERE...)
The 1 or * in the EXISTS is ignored and you can write this as per Page 191 of the ANSI SQL 1992 Standard:
SELECT * FROM AnotherTable
WHERE EXISTS (SELECT 1/0 FROM table WHERE...)
it does what it says - it will always return the integer 1. It's used to check whether a record matching your where clause exists.
select 1 from table is used by some databases as a query to test a connection to see if it's alive, often used when retrieving or returning a connection to / from a connection pool.
The result is 1 for every record in the table.
To be slightly more specific, you would use this to do
SELECT 1 FROM MyUserTable WHERE user_id = 33487
instead of doing
SELECT * FROM MyUserTable WHERE user_id = 33487
because you don't care about looking at the results. Asking for the number 1 is very easy for the database (since it doesn't have to do any look-ups).
Although it is not widely known, a query can have a HAVING clause without a GROUP BY clause.
In such circumstances, the HAVING clause is applied to the entire set. Clearly, the SELECT clause cannot refer to any column, otherwise you would (correct) get the error, "Column is invalid in select because it is not contained in the GROUP BY" etc.
Therefore, a literal value must be used (because SQL doesn't allow a resultset with zero columns -- why?!) and the literal value 1 (INTEGER) is commonly used: if the HAVING clause evaluates TRUE then the resultset will be one row with one column showing the value 1, otherwise you get the empty set.
Example: to find whether a column has more than one distinct value:
SELECT 1
FROM tableA
HAVING MIN(colA) < MAX(colA);
If you don't know there exist any data in your table or not, you can use following query:
SELECT cons_value FROM table_name;
For an Example:
SELECT 1 FROM employee;
It will return a column which contains the total number of rows & all rows have the same constant value 1 (for this time it returns 1 for all rows);
If there is no row in your table it will return nothing.
So, we use this SQL query to know if there is any data in the table & the number of rows indicates how many rows exist in this table.
If you just want to check a true or false based on the WHERE clause, select 1 from table where condition is the cheapest way.
This means that You want a value "1" as output or Most of the time used as Inner Queries because for some reason you want to calculate the outer queries based on the result of inner queries.. not all the time you use 1 but you have some specific values...
This will statically gives you output as value 1.
I see it is always used in SQL injection,such as:
www.urlxxxxx.com/xxxx.asp?id=99 union select 1,2,3,4,5,6,7,8,9 from database;
These numbers can be used to guess where the database exists and guess the column name of the database you specified.And the values of the tables.
it simple means that you are retrieving the number first column from table ,,,,means
select Emply_num,Empl_no From Employees ;
here you are using select 1 from Employees;
that means you are retrieving the Emply_num column.
Thanks
The reason is another one, at least for MySQL. This is from the MySQL manual
InnoDB computes index cardinality values for a table the first time that table is accessed after startup, instead of storing such values in the table. This step can take significant time on systems that partition the data into many tables. Since this overhead only applies to the initial table open operation, to “warm up” a table for later use, access it immediately after startup by issuing a statement such as SELECT 1 FROM tbl_name LIMIT 1
This is just used for convenience with IF EXISTS(). Otherwise you can go with
select * from [table_name]
Image In the case of 'IF EXISTS', we just need know that any row with specified condition exists or not doesn't matter what is content of row.
select 1 from Users
above example code, returns no. of rows equals to no. of users with 1 in single column