Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I came across this line of code in a SQL Report I am trying to fix. Could someone tell me what is the purpose of this.
```
DATEADD(dd, - DATEDIFF(dd, d.TxnDateTime, 1), 1) As TxnDate
```
To me it seems like it would cancel itself out. | It's removing the `TIME` portion of the `DATETIME` without changing the data type.
You can observe the different behavior here: [SQL Fiddle](http://sqlfiddle.com/#!3/1fa93/10746/0)
Again, not sure why you'd need to preserve the `DATETIME` type while removing the time, unless it predates the `DATE` datatype. | It was probably written for SQL Server 2005, when `CONVERT(DATE` was just a glimmer in some Microsoft employee's eye, and when we had to use cumbersome, inefficient and hard-to-explain workarounds to remove the time portion of a `DATETIME`.
People still use those cumbersome, efficient, and hard-to-explain methods, of ... | Why would someone use this? | [
"",
"sql",
"sql-server-2008",
"t-sql",
"datediff",
"dateadd",
""
] |
I want to run a mass update statement that selects the min and max of a column. The issue is that there are multiple columns with null values. If `NULL` then I want to set the `MinValue` to `0`.
I have the following statement, but I am getting errors with the `SELECT` and `ELSE`:
```
UPDATE Table1 SET MaxValue = (
... | Here are some immediately obvious adjustments that you need to make:
```
UPDATE Table1 SET MaxValue = (
SELECT MAX(column1) FROM Table2),
MinValue = (CASE
WHEN (SELECT MIN(column1) FROM Table2) IS NOT NULL -- subquery in parentheses per John Gibb's comment and IS NOT NULL rather than <> NULL
... | How about this?
```
UPDATE a
SET a.MaxValue = b.max_val,
a.MinValue = COALESCE(b.min_val, 0)
FROM Table1 a
CROSS JOIN
(
SELECT MAX(column1) max_val,
MIN(column1) min_val
FROM Table2
) b
``` | SQL Update Statement with a Case with Select Inside | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a MySql table(pin\_codes).
At first I want to select exactly 200 rows from this table and export them, then I want to delete this 200 rows.
If the IDs of this table was continuous, I could do this:
```
SELECT * FROM pin_codes WHERE id<200 and id>1;
DELETE FROM pin_codes WHERE id<200 and id>1;
```
But IDs are ... | ```
Select * from pin_codes order by id limit 200
```
will give you first 200 rows based on id and then you can delete those 200 id's
```
Delete from pin-codes order by id limit 200
```
to delete first 200 rows
Also it is best practice to use column name instead of \* (Query Optimization) | Do something like this:
```
delete from t1 order by id limit 5;
```
[Example](http://sqlfiddle.com/#!2/8cba7/1/0) | Select and Delete exactly x rows from MySql table | [
"",
"mysql",
"sql",
"select",
"sql-delete",
""
] |
```
+----------+---------+------------+-----------+
| MEMRECNO | RECSTAT | IDSRCRECNO | IDNUMBER |
+----------+---------+------------+-----------+
| 556787 | D | 5 | 956645789 |
| 123456 | A | 5 | 956645789 |
| 546578 | A | 5 | 462454322 |
| 262441 | A | ... | Is that what are you looking for?
I just added a `WHERE` clause to your inner query:
```
SELECT idnumber
WHERE recstat <> 'D'
FROM table GROUP by idnumber
HAVING count(idnumber) >= 2
``` | I would do this like:
```
with data as (
select 556787 memrecno, 'D' recstat, 5 idsrcrecno, 956645789 idnumber from dual union all
select 123456 memrecno, 'A' recstat, 5 idsrcrecno, 956645789 idnumber from dual union all
select 546578 memrecno, 'A' recstat, 5 idsrcrecno, 462454322 idnumber from dual union ... | Oracle Query to Find Records If Count >= 2 and unique in column | [
"",
"sql",
"oracle",
"select",
"count",
"having",
""
] |
I want to select the last answer for a specific question. My current solution selects only the Question from "Nutzer1237", but i want the last Answer from "Nutzer1234" too.

```
SELECT pid, frage, antwort, user, created_at
FROM antwortenverlauf
WHERE... | you should have read the answer of @fancyPants
```
SELECT pid, frage, antwort, user, created_at
FROM antwortenverlauf a1
WHERE frage = 'Risiko: Wie empfinden Sie die Kommunikation mit dem Kunden?'
AND (user, created_at) IN (SELECT user, MAX( created_at )
FROM antwortenverlauf a2
... | In the **[official manual](http://dev.mysql.com/doc/refman/5.5/en//example-maximum-column-group-row.html)** there are 3 examples how to solve this.
> *Task: For each article, find the dealer or dealers with the most*
> expensive price.
>
> This problem can be solved with a subquery like this one:
```
SELECT article, ... | Select one specfic row from each user by a different time | [
"",
"mysql",
"sql",
""
] |
I'm beginner in sql. I have a question, how can I import the database from sql file. I tried option "import a script file" but it doesn't work. I attach a screenshots and my sql file
[screenshot](http://i41.tinypic.com/ac61c3.jpg)
[sql file](http://pastebin.com/zNzUbPZn)
Thank you in advance for your help | To get started, you will need:
```
A .sql script file containing a CREATE TABLE command
MySQL Query Browser or phpMyAdmin
Other MySQL database tools will require similar steps.
An empty MySQL database already created
```
MySQL Query Browser is part of the MySQL GUI Tools available at
<http://mysql.com/>. These same s... | Just open a terminal,
login to mysql
use database,
source file/to/dump.sql | Import database from sql file | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
I have one table created like this
Table:
```
key value
1 10000
1 10001
2 10001
```
And I want to select key 2 because it has 10001 but not 10000. Is there a simple way? I tried using joins but I have no idea how to make join select only missing value. | Assuming you're looking for `key`s that don't have all of the available `value`s, you can do that by comparing the number of `DISTINCT value`s for each key to the number of `DISTINCT value`s in the entire table.
```
SELECT `key` FROM `table`
GROUP BY `key`
HAVING COUNT(DISTINCT value) < (SELECT COUNT(DISTINCT value) ... | You can simply do this:
```
SELECT DISTINCT t1.`key`
FROM tablename t1
WHERE t1.`key` NOT IN(SELECT `key`
FROM tablename
WHERE value = 10000);
```
* [**SQL Fiddle Demo**](http://www.sqlfiddle.com/#!2/a3350/15) | SQL: Select key based on missing value | [
"",
"mysql",
"sql",
""
] |
Suppose I have a table in Postgres called `listings` that looks like this:
| id | neighborhood | bedrooms | price |
| --- | --- | --- | --- |
| 1 | downtown | 0 | 189000 |
| 2 | downtown | 3 | 450000 |
| 3 | riverview | 1 | 300000 |
| 4 | riverview | 0 | 250000 |
| 5 | downtown | 1 | 325000 |
| 6 | riverview | 2 | 350... | First compute the average with the aggregate function [`avg()`](https://www.postgresql.org/docs/current/functions-aggregate.html):
```
SELECT neighborhood, bedrooms, avg(price)
FROM listings
GROUP BY 1,2
ORDER BY 1,2;
```
Then feed the result to the `crosstab()` function (provided by the additional module [tablef... | Another solution that implement with filter:
```
SELECT neighborhood,
avg(price) FILTER (WHERE bedrooms = 0) AS "0",
avg(price) FILTER (WHERE bedrooms = 1) AS "1",
avg(price) FILTER (WHERE bedrooms = 2) AS "2",
avg(price) FILTER (WHERE bedrooms = 3) AS "3"
FROM listings
GROUP BY neighborhood;
``` | Create a pivot table with PostgreSQL | [
"",
"sql",
"postgresql",
"pivot-table",
"aggregate-functions",
""
] |
I have two tables
* `Country` with `countryid` and `countryname`
* `City` with `cityid` and `cityname`
I want to extract city names based on the `countryid` I select.
I'm very new to sql database and please help me with direct query if you can.
Thank you very much. | According to the table structure which you showed, this query is not possible. You need to add a 'country\_id' to the cities table so that you know in which country is each city. Once this has been done, your query would be
```
select cities.cityname, countries.countryname
from cities inner join countries on countries... | First you should have countryid in city table as a country can have many cities. Then you can write.
```
select A.cityname from city A
where
A.countryid in (select B.countryid from country B)
```
Please check this link if you want to find out more.
[SQL: Select from one table matching criteria in another?](https... | Sql query for extracting info from one table based on other | [
"",
"sql",
""
] |
It seems ok but am getting exception please correct me.
```
declare
var_number number;
begin
var_number := 10;
if var_number > 100 then
dbms_output.put_line(var_number||' is greater than 100');
elseif var_number < 100 then
dbms_output.put_line(var_number||' is less than 100');
els... | The keyword for Oracle PL/SQL is "ELSIF" ( no extra "E"), not ELSEIF (yes, confusing and stupid)
```
declare
var_number number;
begin
var_number := 10;
if var_number > 100 then
dbms_output.put_line(var_number||' is greater than 100');
elsif var_number < 100 then
dbms_output.put_line(var_n... | The IF statement has these forms in `PL/SQL`:
```
IF THEN
IF THEN ELSE
IF THEN ELSIF
```
You have used `elseif` which in terms of PL/SQL is wrong. That need to be replaced with `ELSIF`.
So your code should appear like this.
```
declare
var_number number;
begin
var_number := 10;
if va... | PLS-00103: Encountered the symbol when expecting one of the following: | [
"",
"sql",
"oracle",
"plsql",
"syntax-error",
""
] |
I'm using MySql 5 and I would like to know if it's possible to get the follow values using sql syntax.
Get value nodes which are include in group 1 and also in group 2 and 3.
```
Hosts | groups
1 1
1 2
1 3
2 1
3 1 ----->for this example host 1 and 3 are the value which I need
... | The answer with `group by hosts having count(distinct groups) = 3` is frequently mentioned, and it does give the right answer. But the following query also works, and usually performs much better if you have an appropriate index. The index should be on `(hosts,groups)` if I recall.
```
SELECT t1.hosts
FROM MyTable AS ... | You should be able to get the result using a combination of `WHERE`, `GROUP BY` and `HAVING`:
```
select hosts
from yourtable
where groups in (1, 2, 3)
group by hosts
having count(distinct groups) = 3;
```
See [SQL Fiddle with Demo](http://sqlfiddle.com/#!2/4746e/1) | SQL syntax to get row value with common column values | [
"",
"mysql",
"sql",
"relational-division",
""
] |
I simply want to have a SQL statement to `GROUP BY`, however I would want it to try and choose one row if that row is available.
For example, I have this statement:
```
SELECT *
FROM `translations`
WHERE `lang` = "pl" OR `lang` = "en"
GROUP BY `key`
```
In this statement, I am trying to select all where the `lang` i... | You can phrase this as a `union all` statement. My assumption is that the `key`,`lang` pair uniquely identifies one row (otherwise you can still do the `group by` to get one row per key).
The idea is to select all rows with `lang = 'pl'`. Then select the rows where `lang = 'en'` that have no corresponding row with `'p... | Not an optimal, but it should give the desired result :
```
SELECT a.*
FROM
(
SELECT * FROM `translations` where `lang` = "pl"
UNION ALL
SELECT * FROM `translations` a where `lang` = "en"
WHERE NOT EXISTS (SELECT NULL FROM `translations` b WHERE b.lang="pl")
)a GROUP BY `key`
``` | How do I group by and "prefer" a row | [
"",
"mysql",
"sql",
"group-by",
""
] |
<http://sqlfiddle.com/#!3/78273/1>
```
create table emptb1
(
id int,
name varchar(20),
dept int
)
insert into emptb1 values (1,'vish',10);
insert into emptb1 values (2,'vish',10);
insert into emptb1 values (3,'vish',30);
insert into emptb1 values (4,'vish',20);
create table depttb1
(
id int,
name varchar(20)
)
inse... | You say "*In above query I'm assuming it should take only dept=30 because order d.id desc will give only top 1st id which is 30 and then it should return employees with dept id = 30*".
That's not how it works. Here's your query (reformatted a little for clarity):
```
select e.id, e.name, a.id
from emptb1 e
cross ap... | To exand on Damien's comment, the inner query:
```
select top 1 * from depttb1 d
where d.id = e.dept
order by d.id desc
```
is going to run for every row in the outer query:
```
select e.id, e.name, a.id
from emptb1 e
```
So you will always get a match from the inner query for each row. I think you were expecting t... | SQL Server cross apply not working? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"cross-apply",
""
] |
Afternoon,
I am trying to convert a number padded with zeros to one that resembles a monetary amount in MS SQL.
Here is an example of what I have, and what I want.
Have:
00000000000039570
Want:
395.70
So far I have managed to get rid of the leading zeros with the below code.
```
SUBSTRING ([Balance], PATINDEX ('%[... | You can convert the string to a float and divide by 100:
```
select cast('00000000000039570' as float)/100
```
If you want a string representation:
```
select str(cast('00000000000039570' as float)/100, 15, 2)
```
EDIT:
In light of the comment from dasblinknight, the following is preferable given the size of the s... | I am not a master of MSSQL but it seems to me after what you did this should work:
```
SUBSTRING([BALANCE], 0, LEN([BALANCE]) - 2) + '.' + SUBSTRING([BALANCE], LEN([BALANCE]) - 2, 2)
``` | sql server moving number decimal place | [
"",
"sql",
"sql-server",
"decimal",
""
] |
I have an SQL statement that looks so:
```
select FY_CD, PD_NO, INPUT, SUM(HOURS)
from LABOR_TABLE
group by PD_NO, INPUT;
```
Returning this:
```
FY_CD|PD_NO| INPUT | HOURS
2008 1 Actuals 61000
2008 1 Baseline 59000
2008 2 Actuals 54000
2008 2 Baseline 59000
2008 3 Actuals... | You can actually calculate it directly by using `CASE` to check the value of `Input`,
```
SELECT FY_CD,
PD_NO,
'Variance' INPUT,
SUM(CASE WHEN Input = 'Actuals' THEN HOURS ELSE -1 * HOURS END) HOURS
FROM LABOR_TABLE
GROUP BY PD_NO
```
* [SQLFiddle Demo](http://sqlfiddle.com/#!2/b3fcf/... | You can use subqueries to divide the table into two parts and then join the parts so that the Actuals and Baselines are on the same row (by PD\_NO). Then it's just simple subtraction.
```
SELECT Baseline.FY_CD
, Baseline.PD_NO
, SUM(Baseline.HOURS - Actuals.Hours)
FROM ( SELECT * FROM L... | SQL Subtract Column Values Based on Second Column Value with Group By Statement | [
"",
"sql",
"group-by",
"subtraction",
""
] |
I am looking for a way of dealing with the following situation:
1. We have a database server with multiple databases on it (all have the same schema, different data).
2. We are looking for a way to query across all the databases (and for it to be easy to configure, as more databases may be added at any time). This dat... | It's not going to be the cleanest solution ever, but you could define a view on a "Master database" (if your individual databases are not going to stay constant) that includes the data from the individual databases, and allows you to execute queries on a single source.
For example...
```
CREATE VIEW vCombinedRecords ... | You must specify the database name before any database object.
Single database:
```
SELECT * FROM [dbo].[myTable]
```
Multiple dabases:
```
SELECT * FROM [DB01].[dbo].[myTable]
UNION ALL
SELECT * FROM [DB02].[dbo].[myTable]
UNION ALL
SELECT * FROM [DB03].[dbo].[myTable]
``` | Query across multiple databases on same server | [
"",
"sql",
"sql-server",
""
] |
hope this makes sense. I have a table that has a bunch of records in it. Each record has a uniqueID and a localID called pro. UniqueID's never repeat but there can be multiple records with the same localID. I'm trying to build a query where, even though there may be 15 records with the same localID, just show me 1 of t... | If you are ok with getting the largest ID then this would work.
```
SELECT
MAX(id) AS id,
pro
FROM ProLookup
WHERE pro LIKE '%" & replace(q,"'","''") & "%'"
GROUP BY pro
``` | Perhaps `SELECT TOP 1 id, pro FROM ProLookup WHERE pro LIKE '%" & replace(q,"'","''") & "%'"`
What is exactly wrong with your query? i.e. giving an error or incorrect data.
Is the extra " at the end necessary? SQL Server doesn't especially like double quotes so if that is being passed to the query you may need to rem... | selecting from a table based on a distinct column | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have simple SQL query.. on Oracle 10g. I want to know the difference between these queries:
```
select * from employee where id = 123 and
to_char(start_date, 'yyyyMMdd') >= '2013101' and
to_char(end_date, 'yyyyMMdd') <= '20121231';
select * from employee where id = 123 and
start_dat... | The latter is almost certain to be faster.
* It avoids data type conversions on a column value.
* Oracle will estimate better the number of possible values between two dates, rather than two strings that are representations of dates.
Note that neither will return any rows as the lower limit is probably *intended* to ... | One of the **biggest flaw** when you converting, casting or transforming to expression (i.e. "NVL", "COALESCE" etc.) **columns** in **WHERE clause** is that **CBO will not be able to use index on that column**. I slightly modified your example to show the difference:
```
SQL> create table t_test as
2 select * fro... | performance difference between to_char and to_date | [
"",
"sql",
"oracle10g",
""
] |
In the accepted answer to this question [How can I loop through all rows of a table? (MySQL)](https://stackoverflow.com/questions/5817395/how-can-i-loop-through-all-rows-of-a-table-mysql) the following code was posted:
```
INSERT INTO table_B(ID, VAL) VALUES(ID, VAL) FROM table_A LIMIT i,1;
```
I want to select from ... | Your immediate error is caused by fact that your [`SELECT INTO`](http://dev.mysql.com/doc/refman/5.5/en/select-into.html) syntax is wrong. `INTO` clause should go before `FROM`.
A syntactically correct version of your procedure might look like
```
DELIMITER $$
CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE i INT DEFAUL... | You cannot use variables with LIMIT. To loop through the rows use CURSOR instead.
Try to see if you use SQL's set based approach (using normal SQL statements). Using loops / cursors should be a last resort as you usually get much better performance using normal SQL commands. | Syntax error while looping through all rows of a table in a stored procedure | [
"",
"mysql",
"sql",
"stored-procedures",
"cursor",
""
] |
I have my request where co.DATE\_UTILISATION is an integer can be null :
```
SELECT COUNT(DISTINCT co.NUMERO) as TOTAL ,
co.DATE_UTILISATION,
cast(NULL as int) as TEST
FROM FOIATST.coupons as co
LEFT OUTER JOIN FOIATST.operateurs as op ON co.OPERATEUR = op.CODE
WHERE co.SOCIETTE = 999
AND co.DATE_DEB_VALIDITE = ... | The problem is that you are grouping by one column but selecting another.
Try this:
```
SELECT COUNT(DISTINCT co.NUMERO) as TOTAL ,
co.DATE_UTILISATION,
cast(NULL as int) as TEST
FROM FOIATST.coupons as co
LEFT OUTER JOIN FOIATST.operateurs as op ON co.OPERATEUR = op.CODE
WHERE co.SOCIETTE = 999
A... | When using GROUP BY, all columns in your SELECT list must either be aggregate functions or in the GROUP BY clause.
```
SELECT COUNT(DISTINCT co.NUMERO) as TOTAL ,
co.DATE_UTILISATION,
cast(NULL as int) as TEST
FROM FOIATST.coupons co
LEFT JOIN FOIATST.operateurs op ON co.OPERATEUR = op.CODE... | DB2 can't select a column who contains nullable values | [
"",
"sql",
"db2",
""
] |
I was wondering which is best practice. Lest say I have a table with 10+ columns and I want to select data from it.
I've heard that 'select \*' is better since selecting specific columns makes the database search for these columns before selecting while selecting all just grabs everything. On the other hand, what if t... | I think these two questions [here](https://stackoverflow.com/questions/3639861/why-is-select-considered-harmful) and [here](https://stackoverflow.com/questions/1960036/best-to-use-when-calling-a-lot-of-fields-in-mysql/1960043#1960043) have satisfactory answers.
\* is not better, actually it is slower is one reason that... | ### It is best practice to explicitly name the columns you want to select.
As Mitch just said the performance isn't different. I even heard that looking up the actual columns names when using `*` is slower.
But the advantage is that when your table changes then your select does not change when you name your columns. | SQL select * vs. selecting specific columns | [
"",
"sql",
"sql-server",
""
] |
I would like to get the average or at least the sum of 200,000 rows from mySQL database. This is how I am querying the database but the amount is too large for me to query because I cannot afford to overload the server.
```
SELECT user_id, total_email FROM email_users
WHERE email_code = 1
LIMIT 200000
SELECT SUM(tota... | You can do this with a subquery:
```
SELECT SUM(total_email), AVG(total_email)
from (SELECT eu.*
FROM email_users eu
WHERE eu.email_code = 1
LIMIT 200000
) eu
```
Some notes. First, using `limit` without an `order by` gives indeterminate results. You could (in theory) run this query twice and ... | How about something like this assuming you just want any 200K records from the DB where email\_code=1
```
SELECT SUM(total_email), AVG(total_email) FROM email_users
WHERE user_id IN
(
SELECT user_id
FROM email_users
WHERE email_code = 1 LIMIT 200000
)
```
or
```
SELECT SUM(total_email), AVG(total_email) FROM... | MySQL: Getting average or sum from 200,000 rows | [
"",
"mysql",
"sql",
"sum",
""
] |
I would like to have columns that look like this:
```
KILL, DEATH, WIN, playerName
```
this is the resultset that it should be applied on

and this is the query that i use to get that resultset:
```
SELECT SUM(amount) as amount, type.name as type, ... | If these are the only three values you want to show as column you can do so,this will give you the count of types
```
SELECT SUM(amount) as amount,
SUM(`type`='KILL') AS `KILL`,
SUM(`type`='DEATH') AS `DEATH`,
SUM(`type`='WIN') AS `WIN`,
gamemode_statistics.Name as playerName
FROM gamemode_statistics
INNER JOIN ty... | You're looking for a pivot query, and MySQL doesn't support them directly. For a simple 3-column result, it's not too bad, but this cannot be made to work as a general solution for `n`-way arbitrary columns:
```
SELECT
SUM(IF type='KILL', amount, 0) AS KILL,
SUM(IF type='DEATH', amount, 0) AS DEATH
etc..
F... | Use some row values as column SQL | [
"",
"mysql",
"sql",
""
] |
My requirement is like select top 5 rows from sql, if it contains only 2 rows then by default it shows some text say 'no data' in remaining 3 rows. Same for all conditions.
**For i.e. Select top 5 rows, but it contains only 3 rows then query will return**
Row1
Row2
Row3
No Data
No Data | Please try:
```
select top 5 Col
from(
select 0 srt, Col from YourTable
union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col
)x
order by srt
``` | ```
/* assuming the column width is 8 characters and datatype is varchar */
DECLARE @NoDataTable AS TABLE(column1 VARCHAR(8))
DECLARE @i AS INT
SET @i = 0
WHILE(@i<5)
BEGIN
insert into @NoDataTable (column1)
values('No Data');
set @i = @i+1
end
select top 5 *
from
(
select column1 from Test... | Get top number of rows anyway | [
"",
"sql",
"sql-server",
""
] |
I'm trying to determine if there is a better way to do this in SQL. My goal is to run one query which returns two values that are to be used for another query. See below
```
select *
from table2
where col1 =
( select col1
from table1
where id = 123 )
and col2 =
( select col2
from table1
... | You can do
```
select *
from table2
where (col1, col2) = (select col1, col2
from table1
where id = 123)
``` | ```
SELECT DISTINCT a.*
FROM table2 a
INNER JOIN table1 b
ON a.col1 = b.col1
AND a.col2 = b.col2
WHERE b.id = 123
``` | Cleaning up and simplifying a nested SQL statement | [
"",
"sql",
"oracle",
"subquery",
""
] |
I have a table, called Table1 which has 2 columns colA, which contains ints and colB, which contains strings.
colA has duplicate values. colA and colB together make a row unique.
I want to find the number of rows between 2 rows which are ordered by colA.
I have all the details of the 2 rows.
The following is the sql... | first some data preparation
```
create table TEST
(
A int,
B varchar(10)
);
insert into TEST (A,B) values
(9,'B0');
insert into TEST (A,B) values
(10,'B1');
insert into TEST (A,B) values
(10,'B2');
insert into TEST (A,B) values
(20,'B3');
insert into TEST (A,B) values
(100,'B4');
insert into TEST (A,B... | This is a bit long for a comment. First observation, the `order by` clause is totally unnecessary, because you are returning only one row (the `count(*)`).
Second, if a row is uniquely identified only by a combination of `colA` and `colB`, then there is no consistent definition of the rows between two values of `ColA`... | get count between 2 known rows | [
"",
"sql",
"sqlite",
""
] |
I am trying to import / restore a PostgreSQL database in pgAdmin on a Mac. I am doing this on a new machine that did not previously have a database on it. I installed and set up pgAdmin on the machine just recently and created a database with no files in it.
Specifically, I am trying to figure out *where* to enter the... | I have worked in WINDOWS , I can tell you what i did, you may get the point and do it in MAC .the pg\_restore command and others like this i.e pg\_dump and others are ther commands which can be run from the pgsql terminal which can be found in the postgres installation folder or may be in the start menu .
From the pgs... | > Specifically, I am trying to figure out where to enter the restore
> commands found on various forums.
This is a misunderstanding. pgAdmin is a GUI. You are referring to command line invocations. You do *not* need pgAdmin to run those. Just open a shell and execute the commands. But read [the manual on `pg_restore` ... | Restoring Database in PGAdmin | [
"",
"sql",
"database",
"postgresql",
"import",
"restore",
""
] |
I have a table in a database that I made using an "auto-increment" primary key. Only now I went back and deleted some of the rows.
The problem is, that I would like the table to be 1->X without any holes in the numbered column (in other words it should be 1,2,3,4,5,6,7,8,9,10 - but now it's more like 1,2,3,7,8,10.
Is... | Use a user defined variable, which is incremented during every row, and an `order by` to prevent duplicate id's \*during the update process:
```
SET @x := 0;
UPDATE mytable SET
id = (@x := @x + 1)
ORDER BY id;
```
See an [SQLFiddle](http://sqlfiddle.com/#!2/e2217/2) | ```
UPDATE yourtable t
JOIN (SELECT id oldid, @id := @id + 1 newid
FROM yourtable
JOIN (SELECT @id := 0) var
ORDER BY oldid) newid
ON t.id = oldid
SET t.id = newid
```
The `ORDER BY` and `ON` conditions are needed to prevent it from temporarily creating duplicate keys, which causes an error.
[DEMO](... | mysql - How can I correct an auto-increment field that has deleted rows (1,2,3,4,5 - is now 1,3,5) but I want it to be 1,2,3 | [
"",
"mysql",
"sql",
""
] |
I've been looking around this, but I can not go forward and is stopping a project that I'm into.
My issue (I think) is very simple, but because I'm not familiar with postgresql I'm stuck in page 1.
I've this table:
```
"id";"date";"name";"seller";"order";"result"
"1";"2013-12-10 11:09:28.76";"adam";"mu";1;"5"
"1";"20... | `CASE` statements are the poor man's surrogate for a proper `crosstab()` function:
```
SELECT a.id
,max(CASE WHEN myorder = 1 THEN result END) AS result_1
,max(CASE WHEN myorder = 2 THEN result END) AS result_2
,max(CASE WHEN myorder = 3 THEN result END) AS result_3
FROM mytab
GROUP BY id
ORDER B... | This is not exactly what you want but it creates an **array** for results field for each id. Similar to group\_concat in MySQL
```
SELECT id, array_agg(result)
FROM table
GROUP BY id
``` | Query issue (row values to columns) in PostgreSQL | [
"",
"sql",
"database",
"postgresql",
"pivot",
""
] |
I'd like to select two columns in a table and a count of associated rows from another.
Basically, I got two tables:
Table `rem` :
```
rem_id (Int, AI, Index) | rem_name (Varchar)
```
Table `map` :
```
rem_id (Int, AI, Index) | data (Text)
```
I want to get the two columns of the table `rem` and how many data entri... | ```
SELECT rem.rem_id,
rem.rem_name,
COUNT(map.rem_id) as cnt
FROM rem
LEFT JOIN map ON map.rem_id = rem.rem_id
GROUP BY rem.rem_id, rem.rem_name
```
Use a `left join` to connect the tables, group by the `rem` columns and then you can count for each `rem` record. | ```
SELECT rem_id,rem_name,(SELECT COUNT(map.rem_id) FROM map
WHERE map.rem_id = rem.rem_id) FROM rem;
``` | Select some columns and a count | [
"",
"sql",
"postgresql",
""
] |
I have `SELECT` query based on `IN()` clause, where I want to feed that clause with other queries like:
```
SELECT *
FROM item_list
WHERE itemNAME
IN (
SELECT itemNAME
FROM item_list
WHERE itemID = '17'
AND (itemSUB ='1' OR itemSUB ='0')
ORDER BY itemSUB DESC
LIMIT 1,
SELECT itemNAM... | User Goat CO deleted good answer:
```
SELECT *
FROM item_list
WHERE itemNAME
= ( SELECT itemNAME
FROM item_list
WHERE itemID = '17'
AND (itemSUB ='1' OR itemSUB ='0')
ORDER BY itemSUB DESC
LIMIT 1)
OR itemName
= ( SELECT itemNAME
FROM item_list
WHERE itemID = '57'
AND (it... | The syntax you are looking for is `union all` rather than `limit`:
```
SELECT *
FROM item_list
WHERE itemNAME
IN (
SELECT itemNAME
FROM item_list
WHERE itemID = '17'
AND (itemSUB ='1' OR itemSUB ='0')
ORDER BY itemSUB DESC
LIMIT 1 union all
SELECT itemNAME
FROM item_list
W... | SQL queries inside IN() clause | [
"",
"sql",
"in-clause",
""
] |
Please ignore if its very basic question as i am not good in SQL and have to develop query i google and couldnt get my desired result.
I have two tables
Product
```
ProductID, ProductName, Descritpion
2010 A xyz
2011 B uyt
2012 C jkj
```
And Sales like below
... | Here's a slightly different answer than the existing ones;
```
SELECT Product.ProductName, TotalSales.TotalSaleCount, TotalSales.SaleDate
FROM Product
JOIN (SELECT ProductId, SaleDate, COUNT(*) as TotalSaleCount
FROM Sales
GROUP BY ProductId, SaleDate) TotalSales
ON TotalSales.ProductId = Product.id
```
... | Just join on the `Product` table:
```
SELECT productname, COUNT(*)
FROM Sales
JOIN Product ON Sales.productid = Product.producyid
WHERE saledate = TRUNC(SYSDATE - 1)
GROUP BY ProductName
``` | GroupBy with count on two tables | [
"",
"sql",
"oracle",
"join",
""
] |
I have a very simple example for the summation of two numbers.
```
CREATE OR REPLACE FUNCTION add(a integer, b integer) RETURNS integer AS
$$
SELECT $1+$2;
$$ LANGUAGE 'sql';
```
My question is how to define a range `b` `10:20`, whose values will counted up by one until the end of the range (20) is reached.
The re... | > I didn't use loops like FOR EACH before (especially in the LANGUAGE sql).
There are no loops in SQL. (The only exception being [RECURSIVE CTEs](http://www.postgresql.org/docs/current/interactive/queries-with.html).) Functions with [`LANGUAGE sql`](http://www.postgresql.org/docs/current/interactive/xfunc-sql.html) (n... | I think you are looking for the function `generate_series()`, documented [here](http://www.postgresql.org/docs/9.1/static/functions-srf.html).
So,
```
select generate_series(1, 3)
```
Will return three rows:
```
1
2
3
```
You can use these numbers in arithmetic expressions. | How to use a range of values in a PostgreSQL function and to loop with a distinct interval | [
"",
"sql",
"function",
"postgresql",
"loops",
"plpgsql",
""
] |
Hello guys i had seprate 12 queries and some c# code to get the data formatted on the page, but now we are converted those pages to the SSRS reports. I have built the stored procedure which is combination of the 12 queries and some new additional queries to format the data as we want on the ssrs report. Now the new sto... | I think, you can try replace this
```
SELECT * FROM (
SELECT @Year AS 'Year',Company, Customer,SUM(Jan) AS Jan, SUM(Feb) AS Feb, SUM(Mar) As Mar, SUM(Apr) AS Apr, SUM(May) AS May, SUM(Jun) AS Jun, SUM(Jul) AS Jul, SUM(Aug) AS Aug, SUM(Sep) AS Sep, SUM(Oct) AS Oct, SUM(Nov) AS Nov, SUM(Dec) AS Dec
,(SUM(Jan... | Check this out
```
CREATE PROCEDURE [dbo].[GetHistoryByYear_Get]
-- Add the parameters for the stored procedure here
@Year AS VARCHAR(4),
@PreYear AS VARCHAR(4)
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT *
INTO #tempCustVol
FROM
(
SELECT *
, Jan + Feb + Mar + ... | Query optimization? | [
"",
"sql",
"sql-server",
"stored-procedures",
"query-optimization",
"query-performance",
""
] |
I need your help about the query below which takes more than 2 min to return a result:
```
SELECT
p.weight,
o.login,
o.date,
o.s_address,
o.s_city,
o.s_county,
o.s_state,
o.s_country,
o.s_zipcode,
o.phone,
c.categoryid,
c.category,
o.orderid,
p.produ... | Besides any other problems your query is having, or indices it may need, it's doing more work than it needs to; here's a slightly tweaked version which *might* run faster:
```
SELECT
p.weight,
o.login,
o.date,
o.s_address,
o.s_city,
o.s_county,
o.s_state,
o.s_country,
o.s_zi... | Most likely thing to help you would be to make sure you have an index on xcart\_orders.orderid if you are sure that part of the query is making it slower. | OR clause slowing down SQL query | [
"",
"mysql",
"sql",
"performance",
""
] |
I have a query that contains a `WHERE` clause with a `CASE` statement in it (See code below), somehow it doesn't seem to work.
```
select * FROM
details
where orgcode in
(case when orgtype='P' then
(SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List])
els... | How about
```
select * FROM details
where (orgtype <> 'P' AND orgcode = 0)
or orgcode in
(
SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List]
)
``` | Or try this:
```
SELECT * FROM details
WHERE details.orgcode IN
( SELECT DISTINCT
(CASE WHEN details.orgtype='P'
THEN [GPOS_Extract].[dbo].[GP8288List].PCode
ELSE 0 END)
FROM [GPOS_Extract].[dbo].[GP8288List] )
``` | How to use case statement inside where clause of sql 2000 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"sql-server-2008-r2",
""
] |
Does Oracle has similar datatype to [SQL Server's `RowVersion`](http://technet.microsoft.com/en-us/library/ms182776.aspx)?
When you insert or update a row, the corresponding Version column(which is of type `RowVersion`) gets updated automatically.
*[MSDN says about RowVersion](http://technet.microsoft.com/en-us/libra... | The simple answer is No - but it's easy to create one yourself with a NUMBER column and a trigger to set/update it.
A simple example for Oracle 11gR2:
```
CREATE SEQUENCE global_rowversion_seq;
ALTER TABLE mytable1 ADD rowversion NUMBER;
ALTER TABLE mytable2 ADD rowversion NUMBER;
CREATE TRIGGER mytable1_biu
BE... | Oracle has SCN (System Change Numbers): <http://docs.oracle.com/cd/E11882_01/server.112/e10713/transact.htm#CNCPT039>
> A system change number (SCN) is a logical, internal time stamp used by Oracle Database. SCNs order events that occur within the database, which is necessary to satisfy the ACID properties of a transa... | SQL Server : RowVersion equivalent in Oracle | [
"",
"sql",
"sql-server",
"oracle",
"rowversion",
""
] |
I wanna update a column of a table:
```
UPDATE product prod
SET prod.prod_supplier_id = (SELECT s.prod_supplier_id
FROM supplier s
WHERE s.prodno = prod.prodno
)
```
the `SELECT s.prod_supplier_id
FROM supplier s
WHE... | You need to filter the rows to be updated in the WHERE clause as well:
```
UPDATE product prod
SET prod.prod_supplier_id = (SELECT s.prod_supplier_id
FROM supplier s
WHERE s.prodno = prod.prodno
)
WHERE EXISTS (SELEC... | first of all create a back up table:
```
CREATE TABLE productBAK AS SELECT * FROM product;
```
now you can use update query like this:
```
UPDATE product prod
SET prod.prod_supplier_id = (SELECT s.prod_supplier_id
FROM supplier s
WHERE s.prodno = prod.... | oracle: update a column with not null value | [
"",
"sql",
"oracle",
""
] |
this is my first question on stackoverflow, I hope someone can help me.
I am making a website similar to facebook.
heres my sql.
```
readsql = "SELECT * FROM post INNER JOIN ubuser ON (post.pos_USERID = ubuser.usr_ID) WHERE ubuser.usr_ID == '"session("ID")"'"
```
and heres the error im getting
> Microsoft VBScr... | Needs to be
```
readsql = "SELECT * FROM post INNER JOIN ubuser ON (post.pos_USERID = ubuser.usr_ID) WHERE ubuser.usr_ID = '" & session("ID") & "'"
```
Problem is your syntax, strings need to be terminated with double quotes `"` and concatenated correctly using ampersand `&` in VBScript. Also remove the `==` and repl... | String concatenation required `&`:
```
readsql = "SELECT * FROM post INNER JOIN ubuser ON (post.pos_USERID = ubuser.usr_ID) WHERE ubuser.usr_ID = '" & session("ID") & "'"
```
Also use only one `=` in your query. | Expected end of statement sql and sessions | [
"",
"sql",
"sql-server",
"session",
"vbscript",
"asp-classic",
""
] |
I am writing a stored procedure that uses dynamic sql. I would like be able to conditionally add the first join criteria if The UserGroup is `<>` 'Initial'. The following is not the actual code, it is just to show my issue
```
SELECT A FROM MyTable
IF UserGroup <> 'Initial THEN
INNER JOIN Table1 ON MyTable.A = ... | You can use dynamic sql
```
declare @Query varchar(max)
set @Query = ' SELECT A
FROM myTable
'
if (UserGroup <> 'Initial')
Begin
set @Query = @Query +'INNER JOIN Table1 ON MyTable.A = Table1.A'
End
exec(@Query)
``` | Here an example of how you can get the same result using outer joins:
```
SELECT A
FROM MyTable
LEFT JOIN Table1 T1
ON (UserGroup <> 'Initial' AND MyTable.A = T1.A)
INNER JOIN Table1 T2 ON MyTable.B = T2.B
INNER JOIN Table1 T3 ON MyTable.C = T3.C
WHERE (UserGroup <> 'Initial' AND T1.A IS NOT NULL) OR UserGroup ... | Using a Case statement to conditionally modify the number of joins | [
"",
"sql",
"dynamic",
""
] |
i have a huge table (200mln records). about 70% is not need now (there is column ACTIVE in a table and those records have value N ). There are a lot of multi-column indexes but none of them includes that column. Will removing that 70% records improve SELECT (ACTIVE='Y') performance (because oracle has to read table blo... | It's really impossible to say without knowing more about your queries.
At one extreme, access by primary key would only improve if the height of the supporting index was reduced, which would probably require deletion of the rows and then a rebuild of the index.
At the other extreme, if you're selecting nearly all act... | Partitioning, putting the active='NO' records in a separate partition, might be a good option.
<http://docs.oracle.com/cd/B19306_01/server.102/b14223/parpart.htm> | deleting rows will improve select performance in oracle? | [
"",
"sql",
"performance",
"oracle",
""
] |
I have a parent table, call it `parents`. Each parent has some number of children in a second table, called `children`. A typical left join would be something like this:
```
select *
from parents p
left join children c
on p.id = c.parent_id
```
But this returns every child row and repeats all the parent information... | ```
SELECT A.* FROM
(
SELECT p.*, c.child_id, some_field_of_children
FROM parents p
LEFT JOIN children c ON p.id = c.parent_id
) A
WHERE A.child_id = ( SELECT MIN(B.child_id) FROM children B WHERE B.parent_id = A.parent_id)
```
I assume that children table has 'child\_id' as its PK that we can use to get th... | Freehand SQL:
Select \*
from Parent p
cross join Child c
where c.Id = (select max(c2.id) from Child c2 where c2.ParentId = p.Id)
Something like that will get 1 child with the current Parent and join the two.
If you want it return stuff if there are no children, ann:
or not exists(select max(c3.id) from Child c3 where... | Joining parent with one example of child | [
"",
"mysql",
"sql",
""
] |
When inserting data into a SQL Server table, is it possible to specify which column you want to insert data to?
For a table with
I know you can have syntax like this:
```
INSERT INTO MyTable (Name, col4_on, col8_on, col9_on)
VALUES ('myName', 0, 1, 0)
```
But the above syntax becomes unwieldy when you have lots of ... | I figured out a way around this but it's rather hacky and only works for tables which has columns with unique values:
```
INSERT INTO MyTable (Name)
VALUES ('myName')
UPDATE MyTable
SET col4_on=0, col8_on=1, col9_on=0
WHERE Name = 'myName'
```
This could be expanded into a multiple row insert as follows:
```
INSERT ... | You must specify the column names. However, there is one exception. If you INSERTing *exactly* the same number of columns as the target table has *in the same order* as they are in the table, use this syntax:
```
INSERT INTO MyTable
VALUES ('val1A', 'val4A', 'val8A')
```
Note that this is a fragile way of performing ... | SQL: How to insert data into a table with column names | [
"",
"sql",
"sql-server",
""
] |
TL/DR:
I run this query = `"Select * from test where id = 0"` and it returns all the rows.
Here is my code below:
```
CREATE TABLE IF NOT EXISTS `test` (
`id` varchar(20) NOT NULL,
`desc` varchar(100) NOT NULL,
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test` (`id`, `desc... | You're performing an arithmetic comparison on a text field. MySQL will coerce the values in your ID column to a numeric value and compare it with zero. `AA`, when coerced, equals zero. | ```
SELECT COUNT(*) FROM test WHERE id = '0'
```
You need to compare with a string, because comparing with a number will convert the table data to a number, and non-numeric strings convert to 0. | MySQL column = 0 returns true | [
"",
"mysql",
"sql",
""
] |
I have the following SQL:
```
SELECT SUM(theNumberCol) qty, TRUNC(theDateCol, 'WW') weekDate
FROM theTable
GROUP BY TRUNC(theDateCol, 'WW');
```
This works fine for finding the sum of theNumberCol for each week. The problem is that the week seems to start on a Tuesday. For example "12/17/2013 8:56:05 AM" is truncated... | Take 7 days away from the truncated date and then find the next Saturday from that date:
[SQL Fiddle](http://sqlfiddle.com/#!4/84436/5)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE theTable ( theNumberCol, theDateCol ) AS
SELECT 1, TO_DATE( '20131202 23:15:52', 'YYYYMMDD HH24:MI:SS' ) FROM DUAL
UNION ... | There are two different calculations available: classic oracle, which calculates week=int(dayOfYear+6)/7, and iso mode, which uses [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601). Format WW uses the classic calculation, while format IW uses the ISO standard.
So as you see, WW does not start the week on any fixed day... | How to change the day that Oracle TRUNC uses to start the week | [
"",
"sql",
"oracle",
""
] |
Supose you have two tables with the exactly the same columns.
```
Table1:
Name Type AveSls
A 2 20
B 4 10
C 1 15
Table2:
Name Type AveSls
D 2 8
E 3 15
F 1 12
```
How do i combine the two tables in SQL server 2008 with a SQL satement s... | You can simply use `UNION ALL` (to get all rows even if they repeat in both tables) or `UNION` to get non-repeating rows.
```
SELECT name,
type,
avesls
FROM table1
UNION ALL
SELECT name,
type,
avesls
FROM table2
```
Read more about `UNION` on [MSDN](http://technet.microsoft.com... | You need to use the [UNION](http://technet.microsoft.com/en-us/library/ms180026.aspx) operator.
it's very simple to use:
```
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
```
See the following useful links:
1. [SQL UNION Operator](http://www.w3schools.com/sql/sql_union.asp)
2. [Intro... | Combining two tables with SQL | [
"",
"sql",
"sql-server-2008",
""
] |
I have two queries and I believe I need to put query number two in the `FROM` statement of query number one could you tell me the best way to do this please?
**QUERY1**
```
SELECT PARTNO_AUD, PARTNO_ING, COSTSET_AUD,
ITEMVER_AUD, PROCNO_AUD, PROCVER_AUD, PROCSTAGE_AUD,
ALLITEM_AUD, COSTERR,
... | I am assuming all you want to do is join both the table to see output together
```
SELECT
PARTNO_AUD,
PARTNO_ING,
COSTSET_AUD,
ITEMVER_AUD,
PROCNO_AUD,
PROCVER_AUD,
PROCSTAGE_AUD,
ALLITEM_AUD,
COSTERR,
dbo.SSI_DAVL_FUNC('COSTERR', COSTERR, 'E') AS DESCRIPTION,
QTY
... | something like:
```
SELECT PARTNO_AUD, PARTNO_ING, COSTSET_AUD,
ITEMVER_AUD, PROCNO_AUD, PROCVER_AUD, PROCSTAGE_AUD,
ALLITEM_AUD, COSTERR,
dbo.SSI_DAVL_FUNC('COSTERR', COSTERR, 'E') AS DESCRIPTION
FROM dbo.MBI030
inner join dbo.MBB020 on PARTNO_AUD = PARTNO_B02PAR and PARTNO_ING = PAR... | Sub Query in the from clause in SQL | [
"",
"sql",
"subquery",
""
] |
Just going crazy on what's wrong here.
all I am trying to do is : ***"Take two columns from one table and insert in to other table"***

The query that I use is this:
```
insert into Component_Capacitor values (Component_Capacitor.itemNo, Component_... | I don't use SQL Server, but I think you need to remove the word "values" from your statement.
```
insert into Component_Capacitor (Component_Capacitor.itemNo, Component_Capacitor.itemDescription)
select [Item No#], [Item Description] from dbo.Sheet1$ where
[Item Description] LIKE 'CAP %' ;
``` | Replace column names & table names properly. This should work.
```
INSERT INTO DBO.COMPONENT_CAPACITOR (ITEMNO, ITEMDESCRIPTION)
SELECT A.ITEMNO, A. ITEMDESCRIPTION FROM SHEET A
WHERE ITEMDESCRIPTION LIKE 'CAP%'
``` | Inserting table data in to another table | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"t-sql",
""
] |
I have a million odd rows where most start
```
'http://www.' or 'https://www.'
```
but occasionally they start with no 'www.' - this may be correct but the website owner wants consistency throughout the data and thus I need to update the table to always have 'www.'
I'm struggling with the SQL to do this. I tried:
`... | You can try this query:
```
UPDATE the_million SET url=REPLACE(url, 'http://', 'http://www.')
WHERE url NOT LIKE 'http://www.%' AND url NOT LIKE 'https://www.%'
UPDATE the_million SET url=REPLACE(url, 'https://', 'https://www.')
WHERE url NOT LIKE 'http://www.%' AND url NOT LIKE 'https://www.%'
```
Search & replace ... | try this
```
select * from the_million where URL not like 'http://www.%'
``` | Mysql SQL to update URLs that do not have www | [
"",
"mysql",
"sql",
""
] |
I have a MySQL table. the column are ID, ChId, TotalView...
Suppose I want to get all the rows which have Totalview -5 then me to all +5 then me. I want to search in table for people who get similar views.
How I can write a query to get the all rows.
```
select * from test where test.chid = 1 and totalview are (-5 t... | You may try this query
```
SELECT * FROM test WHERE totalview> (current-5) AND totalview< (current+5);
``` | get your currentview in a subquery and use it in the search criteria
```
SELECT * FROM test, (SELECT totalview AS currentview FROM test WHERE child =1) t1
WHERE (totalview <= ( currentview +5 )
``` | how to get the rows from mysql that is-5 or +5 then the current row? | [
"",
"mysql",
"sql",
"database",
""
] |
I am having an issue with MySQL. I want to have dynamic columns based on the rows. Here are the details
```
SELECT `marks`.`id` , `marks`.`studentID` , `marks`.`subjectID` , `marks`.`mark`
FROM `Mark` `marks`
LEFT OUTER JOIN `Student` `students` ON ( `students`.`id` = `marks`.`studentID` )
WHERE (
`students`.`classID`... | You can't have dynamic columns, at least without dynamically generating the SQL. You can build the SQL in a stored procedure as per this answer
[MySQL pivot table query with dynamic columns](https://stackoverflow.com/questions/12598120/mysql-pivot-table-query-with-dynamic-columns)
Alternatively it might be simpler to... | According to you desired output, I' assuming there are 2 rows for each `studentID` and each of 2 rows has subjectID 1 or 2.
Could you try this?
**Using JOIN**
```
SELECT t1.studentID, t1.mark AS subject_1, t2.mark AS subject_2
FROM
(
SELECT `marks`.`studentID` , `marks`.mark
FROM `Mark` as `marks`
LEFT O... | Convert Rows to Columns in MySQL Dynamically | [
"",
"mysql",
"sql",
"yii",
"pivot",
""
] |
Im running a cleanup job(every hour) on a table which constantly grows in rows.The job ran for about a week without any problems. Today i saw that the job started locking the entire table.
Is this expected behaviour ? Could it be that after a specific ammount of rows that need to be deleted it locks the entire table i... | One possibility is that you need to index the column by which you are searching the table for rows to delete. If you do not have an index, then SQL Server will acquire many more locks while it searches for the rows to delete.
I highly recommend deleting small chunks of rows in a loop. As others have pointed out, if yo... | If your query affects 5000 rows or more in the same table, that table gets locked during the operation. This is standard SQL Server behavior. Basically every DELETE causes a lock on that row and every 5000 row locks on the same table cause a Lock Escalation from row to table. | Delete statements locks table | [
"",
"sql",
"sql-server",
""
] |
I'm trying to write an RQL query that does the equivalent of this sql:
```
select * from some_table t where t.property in (1, 2, 3, 4 ...)
```
I'm not sure if RQL supports this though. In the oracle docs, there's an example of how to do this on the ID property of a repository item:
```
ID IN { "0002421", "0002219", ... | this is possible through querybuilder api(see example below). I'm not sure why this is not available through plain RQL though.
```
QueryExpression thePropertyExpression =
theQueryBuilder.createPropertyQueryExpression("postalCode");
String [] zipcodeArray = {"22185", "22183"};
QueryExpression theValueExpressi... | From the [ATG Documentation](http://docs.oracle.com/cd/E24152_01/Platform.10-1/ATGRepositoryGuide/html/s0305rqlgrammar01.html) the RQL Grammar includes a specific comparison query for `ID IN` so changing `ID` to another property will not parse properly thus your `ParseException`.
Looking further down the Grammar docum... | ATG RQL query like SQL 'property in (x, y, z)' | [
"",
"sql",
"atg",
""
] |
I have a MySQL table:
```
create table tbl (
amount int
);
insert into tbl (amount) values (1);
insert into tbl (amount) values (2);
insert into tbl (amount) values (3);
insert into tbl (amount) values (4);
```
My goal is a report of how many values are in the following buckets, by using a case statment.
Bucket A... | You can do this using aggregation:
```
select (case when amount in (0, 1) then 'Bucket A'
when amount in (2, 3,4, 5) then 'Bucket B'
when amount in (6, 7, 8, 9) then 'Bucket C'
end) as bucket, count(*) as `count`
from tbl
where amount in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
group by (case w... | ```
select
"Bucket A" as "Bucket", sum(case when amount in (0,1) then 1 else 0 end) as "Count" from tbl
UNION
select "Bucket B", sum(case when amount in (2,3,4,5) then 1 else 0 end) from tbl
UNION
select "Bucket C", sum(case when amount in (6,7,8,9) then 1 else 0 end) from tbl;
```
Like this? [sqlfiddle](http://sqlfi... | In MySQL how to rewrite a query using a case statement? | [
"",
"mysql",
"sql",
""
] |
I think I'm doing the below SQL correctly but apparently not. My dbo.AttendeesLedger.SessionId is sometimes null, and those null values never appear in the result.
```
SELECT
dbo.AttendeesLedger.Id,
dbo.AttendeesLedger.SessionId,
dbo.AttendeesLedger.AttendeesId,
dbo.Attendees.Id,
dbo.Sessions.Id
FROM
dbo.... | That is a known thing with integers. 0 and Null is not the same thing and
because you join to other tables it will not include null unless you explicitly say
it should
Add " or dbo.AttendeesLedger.SessionId is null " to see them.
More details on this :
<http://www.w3schools.com/sql/sql_null_values.asp>
This might al... | Most likely your `INNER JOIN` is filtering out those results. I mean, the `LEFT JOIN` keeps all the values in the left but the `INNER JOIN` will only keep those values that make the first `ON` condition `true`. Whenever the first condition is `false` then those results will not be displayed... even if you use a `LEFT J... | Nulls not appearing when SessionId is null | [
"",
"sql",
"sql-server",
""
] |
Say I have the following table:
```
Tree Park Slide
1 1 1
1 1 1
1
1 1
```
What kind of code would I use to remove the rows that have empty columns such that I would just have the following result
```
Tree Park Slide ... | Use `DELETE` to delete a row and check it with `IS NULL` in the `WHERE` clause.
```
DELETE FROM dbo.TableName
WHERE Tree IS NULL OR Park IS NULL OR Slide IS NULL
```
If you also want to delete rows where one of these columns is not null but empty text(if it's a `varchar` column):
```
DELETE FROM dbo.TableName
WHERE ... | If you mean *physically deleting* then just put that in your `WHERE`:
```
DELETE FROM {table}
WHERE Tree IS NULL
OR Park IS NULL
OR Slide IS NULL
```
Or take advantage of the fact that `{null} + n = {null}` and just do:
```
DELETE FROM {table}
WHERE (Tree+Park+Slide) IS NULL
```
But I would *definitely* add ... | How to remove an entire row if one column is empty | [
"",
"sql",
""
] |
I am running the follwoing SQL query:
```
SELECT * FROM COUNTRIES WHERE USERTYPE = 'PREMIUM' ORDER BY SALES DESC;
```
The output of this query yields a list of countries.
Now I need to populate a field in another table which is like TOP\_SALES\_COUNTRY, SECOND\_TOP\_SALES\_COUNTRY and THRID\_TOP\_SALES\_COUNTRY for ... | You could use any of the following:
**Option 1:**
```
SELECT TOP number|percent column_name(s)
FROM table_name;
```
**Option 2:**
```
SELECT column_name(s)
FROM table_name
LIMIT number;
```
**Option 3:**
```
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
``` | `SELECT * FROM COUNTRIES WHERE USERTYPE = 'PREMIUM' ORDER BY SALES DESC limit 0,1;` to get the first row | How to select one record from a SELECT query in MySQL | [
"",
"mysql",
"sql",
"select",
""
] |
I am receiving an xml into my stored procedure as follows:
```
<records>
<record>Name="Charles" Number="8" CustomerId ="3" Date="12/17/2013 12:00 AM"/>
</records>
```
So I read the data as follows: in my procedure and insert
```
INSERT INTO CustomerNumbers (Name, Number, CustomerId)
SELECT xtable.item.... | ```
DECLARE @xml XML;
SET @xml = '<rows>
<row Name="Charles" Number="8" CustomerId ="3" Date="12/17/2013 12:00 AM"/>
<row Name="Mary" Number="7" CustomerId ="6" Date="12/19/2013 12:00 AM"/>
<row Name="Miriam" Number="10" CustomerId ="10" Date="12/18/2013 12:00 AM"/>
... | My rule of thumb is that if I hit "one table", I push directly into that table.
If I hit 2 or more, I shred the xml into a #temp (or @variable) table, and then do Insert/Update/Upsert(Merge) from that #temp table.
If I have more than 1 destination table, then I do my shredding outside of the BEGIN TRAN/COMMIT TRAN. T... | Handling XML using SQL to Create or Update multiple tables | [
"",
"sql",
"sql-server",
"xml",
""
] |
When I check if a value is NULL I usually use '=',
This doesn't work somehow but 'is null' works.
Why's that? What is the difference? | ```
WHERE myvalue = null
```
will never be true. Since even if "myvalue" is undefined ("null"), the database can't determine that it equals null (since null by definition means "unknown" and two "unknowns" can't be equal to each other).
```
WHERE myvalue IS null
```
is more straight-forward. This checks whether "myv... | Have a look at :
[SQL is null and = null](https://stackoverflow.com/questions/9581745/sql-is-null-and-null)
Basically, null can be thought of as no value or no value know.
A comparison operator (eg =) is effectively asking if an unknown or non existent value is equal to another unknown or non existent value. The only ... | SQL: What's the difference between '=' and 'is'? | [
"",
"sql",
""
] |
I have a problem with some P-SQL syntax. I have reduced the code sample to its minimum below.
The following works:
```
CREATE OR REPLACE FUNCTION MyFunction(LINE_ID SMALLINT)
RETURN VARCHAR2 IS
tmp VARCHAR2(4000);
BEGIN
tmp := CAST(LINE_ID AS VARCHAR2);
RETURN(tmp);
END MyFunction;
/
```
However, I need ... | You can't specify `NUMBER` precision and scale for a function's parameter. Just declare it like this:
```
CREATE OR REPLACE FUNCTION MyFunction2(LINE_ID NUMBER)
``` | The function you're looking for is `TO_CHAR`:
```
tmp := TO_CHAR(LINE_ID);
``` | How do I CAST a NUMBER to VARCHAR2 in Oracle? | [
"",
"sql",
"oracle",
"plsql",
"casting",
""
] |
I am just wondering if someone could help me with the following. I am using VB. NET and SQL Server and want to include some error handling in my code.
I am doing a SQL SUM command which returns fine with no problems providing there is a match in the database. But when there is no match to the String I have specified I... | A pure SQL solution can rely in coalesce or isnull for this simple query just returning a single aggregate column.
```
SELECT COALESCE(SUM ([TotalTime]), 0) FROM [Line1Log] WHERE ([State] = 'Test')
``` | Try to change dbCount1 to nullable integer
```
Dim dbCount1 As Nullable(Of Integer)
```
Or
```
Dim dbCount1 As Integer?
``` | How to handle Conversion from type 'DBNull' to type 'Integer' is not valid | [
"",
"sql",
"vb.net",
""
] |
I need to use a case type of logic in my query. Database Used: Oracle 11g
The present query looks like:
```
SELECT name
FROM merchant m
WHERE NOT EXISTS (
SELECT 1
FROM settlement s
WHERE s.sid = m.mid
AND s.rpt_id IN ('111','112','202')
)
```
There is another column SRID which takes precedence ove... | I think you want the [coalesce function](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617), which returns the first non-null value. Unfortunately I don't have access to an Oracle system to confirm.
```
select NAME
from merchant m
where NOT EXISTS (
SELECT 1 from SETTLEMENT s
... | Please use
```
NVL(s.SRID, s.SID) = m.MID
```
instead of
```
s.SID = m.MID
```
in the where condition. | SQL - Where Clause to Use Case Logic | [
"",
"sql",
"oracle",
""
] |
Someone help me out before i fall into depression.
I'm creating a Simple licencing voting system. When a licence is received, it has to be **Approved** or **Rejected** by a committee. This committee consists of 5 members and the voting process is based on a majority vote(Meaning that every application received needs a... | My attempt at readability:
```
WITH votes AS (
SELECT
LicenceApplicationID,
CommitteeApprovalStatusName Vote
FROM CommitteeApproval A
INNER JOIN CommitteeApprovalStatus S ON
S.CommitteeApprovalStatusID = A.CommitteeApprovalStatusID
)
SELECT
LicenceApplicationID,
Approve,
Reject,
CASE
WHE... | Try with this:
```
SELECT LicenceApplicationID, COUNT(UserID) AS votes,
CASE WHEN CommitteeApprovalStatusID = 1 THEN 'Aprove' ELSE 'Rejected' END AS Status
FROM CommitteeApproval
WHERE CommitteeApprovalStatusID in (1, 2)
GROUP BY LicenceApplicationID, CommitteeApprovalStatusID
HAVING COUNT(UserID) < 3
... | Trouble implementing T-SQL GROUP BY clause | [
"",
"sql",
"sql-server",
"t-sql",
"group-by",
"aggregate-functions",
""
] |
I am trying to count the number of records in a table.
The table is called affiliations and only has 4 columns (2 of which are foreign keys)
I want to count the number of records where the affiliated column is 0 and the business\_id is related to a particular account\_email.
I know how to do this query using the IN k... | The first query from the question with `IN` clause is not equivalent to the second with `EXIST`.
To convert the first query with `IN`, you must use a dependent subquery:
```
SELECT COUNT(1) FROM affiliations a1
WHERE EXISTS (
SELECT 1 FROM affiliations a2
WHERE account_email = 'address@domain.ext'
A... | I'd use exists, but also remember to correlate the subquery to the primary table as below.
```
SELECT COUNT(1) FROM affiliations a
WHERE exists (
SELECT 1
FROM affiliations a1
WHERE account_email = 'address@domain.ext'
and a1.business_id=a.business_id
) AND affiliated = 0
``` | A better / more efficient way to write this query | [
"",
"mysql",
"sql",
""
] |
How to optimize this query? I have tried using `LEFT JOIN` clause but still take at least 3 seconds.
```
SELECT DISTINCT MBLNR
FROM MKPF
WHERE MANDT='368'
AND XBLNR = '0150525913'
AND MBLNR NOT IN ( SELECT DISTINCT SMBLN FROM MSEG WHERE XBLNR_MKPF = '0150525913' )
```
After using `LEFT JOIN`, still takes 3 ... | The correct left outer join formulation of the first query is:
```
SELECT DISTINCT A.MBLNR
FROM MKPF A LEFT JOIN
MSEG B
ON B.SMBLN = A.MBLNR AND AND B.XBLNR_MKPF = '0150525913'
WHERE A.XBLNR = '0150525913' and A.MANDT='368' and B.SMBLN is null;
```
Depending on the sizes of the tables, 3 seconds might be re... | While intuitive, "not in" is slow. So, change this:
```
AND MBLNR NOT IN
( SELECT DISTINCT SMBLN FROM MSEG WHERE XBLNR_MKPF = '0150525913' )
```
to
```
AND MBLNR IN
(SELECT DISTINCT MBLNR
FROM MKPF
WHERE MANDT='368'
AND XBLNR = '0150525913'
except
SELECT DISTINCT SMBLN
FROM MSEG
WHERE XBLNR_MKPF = '0150525913' ... | Optimizing query still takes a bit long time | [
"",
"sql",
"db2",
""
] |
I would like to check which user performed insertions in specific table on MS SQL Server 2008. I am aware of some logging info being stored, but I don't know how to access it. I would be grateful with provided specific info on my question and also with general pointer where and what to look for if I ever need other inf... | Are you talking about retrieving this from the transaction logs?
This isn't ideal as you have no guarantee that the relevant rows will still be available in the active log and it is less efficient to query but something like the below would do it (returns `USER_NAME()` rather than the likely more useful `SUSER_NAME()`... | You can try out ApexSQL Log to read the transaction log. Trial is fully functional for 14 days, add available data sources and filter only INSERT statements. Bottom line is that you can allows viewing transaction log data in read-friendly format
Also you can check out undocumented function [fn\_dblog](http://raresql.c... | Check who performed insertion in table on MS SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have the below requirement to fulfill. How to achieve this simplistically.
There is an inflation rate table as below
```
2009, 5%
2010, 5%
2011, 5%
2012, 5%
2013, 5%
```
I need to first get
```
2009, 5%, 5
2010, 5%, 5.25 - which is 5% over 5
2011, 5%, 5.5125 - which is 5% over 5.25
2012, 5%, 5.788125 ... | I think the best way to do this on SQLserver is to use a common table expression with recursion.
I'm not 100% sure because I can't test it here, but something along these lines as the example below. Btw I assume the rates in the table are stored as fractions, so 5% is 1.05 and 10.25% is 1.1025 etc.
```
WITH MyCompound... | Lacking a `PRODUCT()` statement, the query becomes a little more complex than would be required otherwise, but this should work well; it uses common table expressions for each step, and logarithmic sums to simulate `PRODUCT()`.
```
WITH cte1 AS (
SELECT a.year, 5 * EXP(SUM(COALESCE(LOG(b.rate),0))) rate
FROM infla... | inflation calculation in MS SQL | [
"",
"sql",
"sql-server",
"join",
""
] |
I have this query
```
SELECT username FROM paymentValue
```
I can sum `paymentValue` for username like
```
SELECT username, SUM(paymentValue) WHERE username = 'john'
```
But how to select sums for all usernames to get return like:
john, 146
marry, 3456
anna, 2043 | use the 'group by' clause
```
select username, sum(paymentvalue) as sumofpayments from thetable
group by username
``` | ```
SELECT username, SUM(paymentValue)
FROM TableName
GROUP BY username
```
to JOIN with another table
```
SELECT username, SUM(paymentValue)
FROM TableName INNER JOIN SecondTable
ON TableName.RefrencingColumn = SecondTable.RefrencingColumn
WHERE username = 'john'
GROUP BY username
``` | SQL query - select usernames and sum their row | [
"",
"sql",
""
] |
```
<%
postit = request.querystring("thispost")
response.write(postit)
%>
```
`postit` is the variable. The `response.write` works and this is all above the SQL statement below.
This is the SQL however when I add the `postit` variable I get this error message:
```
delCmd.CommandText="DELETE * FROM post WHERE (pos_ID... | Add a parameter to the SQL:
```
delCmd.CommandText="DELETE * FROM post WHERE (pos_ID = ?)"
delCmd.Parameters.Append delCmd.CreateParameter("posid", adInteger, adParamInput) ' input parameter
delCmd.Parameters("posid").Value = postit
``` | Couple of things that will help you in the future
1. Use `Option Explicit` to avoid hiding issues that will come back to bite you later on
2. Use `ADODB.Command` object, which is very versatile enabling to do a range of database calls, from simple dynamic SQL statements to Stored Procedures without the risk of SQL inj... | How to use ASP variables in SQL statement | [
"",
"sql",
"asp-classic",
""
] |
I have a table as below.
```
DATE_WORKED COUNTRY
1-Nov-13 United Kingdom
4-Nov-13 United Kingdom
5-Nov-13 India
6-Nov-13 India
7-Nov-13 India
8-Nov-13 United Kingdom
11-Nov-13 United Kingdom
12-Nov-13 India
13-Nov-13 India
14-Nov-13 India
15-Nov-13 United Kingdom
18-Nov-13 United Kingdom
... | Using [Tabibitosan](https://forums.oracle.com/message/3996302):
```
SQL> create table mytable (date_worked,country)
2 as
3 select to_date('1-Nov-13','dd-Mon-yy'), 'United Kingdom' from dual union all
4 select to_date('4-Nov-13','dd-Mon-yy'), 'United Kingdom' from dual union all
5 select to_date('5-Nov-13',... | Somewhat more complicated than @RobVanWijk's answer:
```
with v_data as (
select to_date('2013-11-01', 'YYYY-MM-DD') as date_worked, 'UK' as country from dual union all
select to_date('2013-11-04', 'YYYY-MM-DD') as date_worked, 'UK' as country from dual union all
select to_date('2013-11-05', 'YYYY-MM-DD') as dat... | Oracle : min max values within a repeating group | [
"",
"sql",
"oracle",
""
] |
I am passing one password value for either 2 or 3 or 4 or 'n' number of usernames.
How to pass the user\_id dynamically to the update query ?
```
update user_table
set column_password = 'password value'
where user_id in ( )
``` | First create the function using this code:
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[SplitIDs]
(
@List varchar(5000)
)
RETURNS
@ParsedList table
(
ID int
)
AS
BEGIN
DECLARE @ID varchar(10), @Pos int
SET @List = LTRIM(RTRIM(@List))+ ','
SET @Pos = CHARINDEX(',',... | **CREATE A Function**
```
CREATE FUNCTION [dbo].[FnSplit]
(
@List nvarchar(2000),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table (Id int identity(1,1), Value nvarchar(100))
AS
BEGIN
While(Charindex(@SplitOn,@List)>0)
Begin
Insert Into @RtnValue (value)
Select Value = ltrim(rtrim(Substring(@List,... | Dynamically updating column value in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
As the title of the question says, I would like to find all pairs of employees who have the same birthday date each year, such as each row of the result table must show a pair of employees and each pair of employees must appear only once in the result table.
My query, as follows, finds only pairs of people with the sa... | The problem is you are joining on the actual date. You can either join on DAY/MONTH or just remove the join:
```
SELECT DISTINCT E1.empno,
E1.firstnme,
E1.lastname,
E1.birthdate,
E2.empno,
E2.firstnme,
E2.lastname,
... | Don't use <> for the empno comparison, use > or <, this will keep the pairs from showing up twice.
```
select e1.*, e2.*
from employee e1
inner join employee e2 on month(e2.birthdate)=month(e1.birthdate)
and day(e2.birthdate)=day(e1.birthdate) and e2.empno > e1.empno
``` | Find all pairs of employees who have the same birthday date each year | [
"",
"sql",
""
] |
I'm currently working on a project with a MySQL Db of more than 8 million rows. I have been provided with a part of it to test some queries on it. It has around 20 columns out of which 5 are of use to me. Namely: `First_Name, Last_Name, Address_Line1, Address_Line2, Address_Line3, RefundID`
I have to create a unique b... | The solutions that seem obvious to me....
Don't use a random value - use a hash:
```
UPDATE yourtable
SET refundid = MD5('some static salt', First_Name
, Last_Name, Address_Line1, Address_Line2, Address_Line3)
```
The problem is that if you are using an integer value for the refundId then there's a good chance of... | Try using the following:
```
UPDATE `tempTable` x SET RefundID = FLOOR(RAND()*POW(10,11))
WHERE exists (SELECT 1 FROM tempT y WHERE First_Name is not NULL and x.First_Name=y.First_Name);
``` | Update with Subquery never completes | [
"",
"mysql",
"sql",
"sql-update",
"subquery",
""
] |
Hi I have this table Cars:
```
MODEL nvarchar(20)
STYLE nvarchar(20)
ENGINE nvarchar(5)
CAPACITY smallint
MAX_SPEED smallint
PRICE smallmoney
MARKET nvarchar(20)
COMPETITOR nvarchar(20)
```
And I would like to split it into 3 tables via SQL query:
Cars:
```
MODEL nvarchar(20)
STYLE nvarchar(20)
MAX_SPEED smallint
P... | Easiest way. Select... Into will create new tables:
```
SELECT DISTINCT
ENGINE,
CAPACITY
INTO Engine
FROM CARS
SELECT DISTINCT
MARKET,
COMPETITOR
INTO Market
FROM CARS
```
Then just drop the defunct columns from the original table. Eg
```
ALTER TABLE Cars DROP COLUMN ENGINE
ALTER TABLE Cars DROP CO... | Run this....
```
create table Engine
(
EngineId int identity(1,1) not null primary key,
Engine nvarchar(5) not null,
Capacity smallint not null
)
go
insert into Engine
(Engine, Capacity)
(select distinct Engine,Capacity from Cars)
go
alter table Cars
add EngineId int null
go
update Cars
set Cars.EngineI... | How to split table into multiple tables using SQL | [
"",
"sql",
"sql-server",
""
] |
In Amazon Redshift I'm looking to convert the current timestamp to have 0 seconds. That is go from this:
```
2013-12-17 12:27:50
```
to this:
```
2013-12-17 12:27:00
```
I have tried the following:
```
SELECT dateadd(second, -(date_part(second, getdate())), getdate());
ERROR: function pg_catalog.date_add("unknown... | It's easiest to use the [`date_trunc()` function](http://docs.aws.amazon.com/redshift/latest/dg/r_DATE_TRUNC.html), but that will work only while selecting:
```
SELECT date_trunc('minute', TIMESTAMP '2013-12-17 12:27:00');
```
You may preprocess data before loading data into the redshift DB, or use intermediary table... | Check [date\_trunc()](http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC)
```
SELECT date_trunc('minute', TIMESTAMP '2013-12-17 12:27:00');
``` | Remove seconds from current date in Redshift (PostgreSQL) | [
"",
"sql",
"postgresql",
"amazon-redshift",
""
] |
Another SQL Query issue that i am having. If anyone could help it would be appreciated.
No errors are thrown (using the Try syntax) however it is not updating the database.
```
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\\$$$$\$$$$\$$$$.accdb';")
Dim str As S... | In the one you have that works you have cmd.Parameters.AddWithValue("@ID", textbox6.Text) which is linking to a text box. The one that does not work has cmd.Parameters.AddWithValue("@ID", SysID.Text) which you say links to a label. I can't see why that would make a difference but could you try a read-only textbox just ... | `OleDbCommand` does not support named parameters. Use this instead:
```
update FDSL set Hostname=?, Owner=? where ID=?
```
And add the parameters in the order that they appear in the query.
However you *should* be getting an error in that case, so something else may be swallowing the exception. | Why will MS Access DB not update? | [
"",
"sql",
"vb.net",
"ms-access",
""
] |
I want to check there is any duplicate record for that row.
means as per table structure
> if( C1\_CADNO=C2\_CADNO or C1\_CADNO=C3\_CADNO or C2\_CADNO=C3\_CADNO )
> then
> display that record
And my Table having 10 columns like C1\_CADNO.....C10\_CADNO
[My Table Structure](https://i.stack.imgur.com/D9T8M.png) | Move it to the `WHERE` clause:
```
SELECT t.* FROM TableName t
WHERE ( C1_CADNO = C2_CADNO
OR C1_CADNO = C3_CADNO
OR C2_CADNO = C3_CADNO )
```
> but my table having 10 columns like
> C1\_CADNO,C2\_CADNO,C3\_CADNO.....C10\_CADNO –
Then this SQL is made for you:
```
SELECT t.* FROM TableName t
WHERE ( t.C... | Try this:
```
SELECT * FROM T WHERE
C1_CADNO IN (C2_CADNO,C3_CADNO,C4_CADNO,...C10_CADNO)
OR
C2_CADNO IN (C3_CADNO,C4_CADNO,...C10_CADNO)
OR
C3_CADNO IN (C4_CADNO,...C10_CADNO)
OR
C4_CADNO IN (C5_CADNO,...C10_CADNO)
...
OR
C8_CADNO IN (C9_CADNO,...C10_CADNO)
OR
C9_CADNO = C10... | check duplicate records for particular row in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have this SQL statement:
```
SELECT
(CASE
WHEN EXISTS
(SELECT *
FROM votes
WHERE votes.user_id = 0
AND votes.post_id = posts.id
AND votes.vote = 0) THEN 0
WHEN EXISTS
... | Yes, you can select `votes.vote` directly, like this:
```
SELECT
COALESCE(
(
SELECT MIN(votes.vote)
FROM votes
WHERE votes.user_id = 0 AND votes.post_id = posts.id
AND votes.vote in (0, 1)
GROUP BY votes.user_id, votes.post_id
)
, 2
) AS vote_by_me
... | This would seem to simplify the query:
```
SELECT (CASE WHEN v.votes0 > 0 THEN 0
WHEN v.votes1 > 0 THEN 1
ELSE 2
END) AS vote_by_me,
p.*
FROM posts p left outer join
(select v.post_id, sum(v.vote = 1) as vote1, sum(v.vote = 0) as vote0
from votes v
where v.user... | SQL simplication | [
"",
"mysql",
"sql",
""
] |
I have the following Data flow 
I need to insert rows into flat files and table using ado.net connector

and I always get this error
```
[ADO NET Destination [2]] Error: An exceptio... | Use the Odbc Data Provider and save yourself a headache. | Start the MySQL Server and login to it. Run the following commands as shown in the figure. By setting the mode to 'ANSI' makes the syntax more standard like as MySQL can cater to clients using other SQL modes. This is why the above error is returned although the syntax itself appears correct. In fact a create statement... | Insert into Table Mysql | [
"",
"mysql",
"sql",
"ssis",
""
] |
I hope I've put the query together correctly below. I've simplified from something much, much bigger. But my question should be clear enough from the example.
In the innermost query, `nest1`, let's say the results come back with three entries for invoice 123. The invoice was created (1), then two cash deposits were ma... | It's forcing you to re-run the aggregates, because you are putting group by in each step of the query. If you remove `group by id` from all but the innermost query, you won't have to re-do the aggregation.
Try writing it like this:
```
SELECT id, cash_deposit, paid_off_date, job_phase, cust_id
FROM
(
SELECT id AS... | ```
SELECT i.id, SUM(i.cash_deposit), MAX(i.paid_off_date), MAX(j.job_phase), MAX(c.cust_id)
FROM invoice i
JOIN job j ON j.id = i.id
JOIN customer c ON c.invoice = i.id
GROUP BY id
``` | Why do aggregates in subqueries have to be aggregated again? | [
"",
"sql",
"sql-server",
"subquery",
"aggregates",
""
] |
I am looking for a way to count the number of columns in a table in Hive.
I know the following code works in Microsoft SQL Server. Is there a Hive equivalent?
```
SELECT COUNT(*),
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'database_name'
AND TABLE_SCHEMA = 'schema_name'
AND TABLE_NAME = 'table_na... | Try this
```
SHOW COLUMNS (FROM|IN) table_name [(FROM|IN) db_name]
``` | Try this, it will show you the columns of your table:
```
DESCRIBE schemaName.tableName;
``` | Count Number of Columns In Hive | [
"",
"sql",
"sql-server",
"count",
"hive",
"distinct",
""
] |
We have two 2 tables:
```
tbl_projekte [uid,werbemittel,projekt_name,kunden_id]
tbl_kunden [uid, kunden_name]
```
We are using this statement to select recordsets from tbl\_projekte:
```
SELECT * FROM tbl_projekte WHERE werbemittel ='12' ORDER BY kunden_id ASC
```
How do we get the SQL statement to ORDER BY kunden... | Yes, you need a join for this
```
SELECT p.*
FROM tbl_projekte p
INNER JOIN tbl_kunden k on k.uid = p.kunden_id
WHERE p.werbemittel ='12'
ORDER BY k.kunden_name ASC
``` | If You want to order by customer name, then do it this way:
```
SELECT p.uid, p.werbemittel, p.projekt_name
FROM tbl_projekte p
LEFT JOIN tbl_kunden k ON k.uid = p.kunden_id
WHERE werbemittel ='12'
ORDER BY k.kunden_name ASC
``` | Do we need a JOIN for this SQL statement? | [
"",
"mysql",
"sql",
""
] |
Hi all champions out there
I am far from a guru when it comes to high performance SQL queries and and wonder in anyone can help me improve the query below. It works but takes far too long, especially since I can have 100 or so entries in the IN () part.
The code is as follows, hope you can figure out the schema enoug... | Restructure your query to use a join instead of a subselect. Also, use an INNER JOIN instead of a LEFT JOIN to the Payment table. This is justified, since you have a WHERE filter that would filter rows without a match in the Payment table anyway.
```
SELECT inv.amount
FROM invoice inv
INNER JOIN invoiceRelation ir ON... | One way to improve performance is to have a good index on relevant columns. In your example, an index on `inv.invoiceI`D would probably speed up the query quite a bit.
Also on `pay.paymentID`
Try this and see if it helps:
```
ALTER TABLE invoice ADD INDEX invoiceID_idx (invoiceID);
```
and
```
ALTER TABLE Payment ... | Improve performance mySQL query | [
"",
"mysql",
"sql",
""
] |
Please refer the below examples and kindly let me know your ideas.
```
declare @EmployeeStartDate datetime='01-Sep-2013'
declare @EmployeeEndDate datetime='15-Nov-2013'
select DateDiff(mm,@EmployeeStartDate, DateAdd(mm, 1,@EmployeeEndDate))
```
Output = `3`
expected output = `2.5`
Since I have only 15 days in Nov, S... | Try this
```
SELECT CASE WHEN DATEDIFF(d,'2013-09-01', '2013-11-15')>30 THEN DATEDIFF(d,'2013-09-01', '2013-11-15')/30.0 ELSE 0 END AS 'MonthDifference'
```
OR
```
SELECT DATEDIFF(DAY, '2013-09-01', '2013-11-15') / 30.436875E
``` | DateDiff compares the values of the column you specify to work out the difference, it doesn't compare both dates and give you an exact difference. You've told it to compare the Month values, so thats all it's looking it.
<http://technet.microsoft.com/en-us/library/ms189794.aspx>
The Technet article details the return... | Month difference between two dates in sql server | [
"",
"sql",
"sql-server",
""
] |
A few posters have asked similar questions on here and these have taken me 80% of the way toward reading text files with sql queries in them into R to use as input to RODBC:
[Import multiline SQL query to single string](https://stackoverflow.com/questions/2003663/r-language-import-multiline-sql-query-to-single-string)... | Are you sure you can't just use it as is? This works despite taking up multiple lines and having a comment:
```
> library(sqldf)
> sql <- "select * -- my select statement
+ from BOD
+ "
> sqldf(sql)
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
```
This works too:
... | I had trouble with the other answer, so I modified Roman's and made a little function. This has worked for all my test cases, including multiple comments, single-line and partial-line comments.
```
read.sql <- function(filename, silent = TRUE) {
q <- readLines(filename, warn = !silent)
q <- q[!grepl(pattern = ... | SQL query with comments import into R from file | [
"",
"sql",
"r",
""
] |
I have a data set of contracts and the nationalities of people working on them. A sample is as follows.
```
Contract Country
GTT001 DE
GTT001 DE
GTT001 US
BFF333 US
BFF333 US
BFF333 DE
HHH222 GB
HHH222 GB
HHH222 GB
```
I need a query that will count the number of people working on each con... | ```
DECLARE @Pivotcols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @Pivotcols = STUFF((SELECT distinct N',' + QUOTENAME([Country])
from [Contract]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @Pivotcols
set @query = N'SELECT ... | You want to use GROUP BY using both contract and then country. This will give you a list like this:
```
Contract Country Count
GTT001 DE 2
GTT001 US 1
BFF333 US 2
BFF333 DE 1
HHH222 GB 3
```
Then you want to pivot those values to get it into the format you want. Th... | Count if or Count where in SQL | [
"",
"sql",
"ms-access",
""
] |
i have stored procedure that InsertNewFlag this stored procedure works to check if specified condition record exist that upadte table with multiple (If..Else If) and if not exist that table insert query executed.
here i include this stored procedure code:
```
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCE... | Try this,
```
UPDATE [FileSystem].[dbo].[tbl_Post_History_Status]
SET
[IsRead] =(CASE WHEN NOT @IsRead IS NULL THEN @IsRead ELSE [IsRead] END),
[IsImportant] =(CASE WHEN NOT @IsImportant IS NULL THEN @IsImportant ELSE [IsImportant] END),
[IsTrashed] =(CASE WHEN NOT @IsTrashed IS NULL THEN @IsTrashed EL... | Replace all null checking to like this
```
IF Not @IsRead Is Null --Instead of IF @IsRead <> NULL
BEGIN
.....Other CODE
END
ELSE IF Not @IsImportant Is Null --Instead of ELSE IF @IsImportant <> NULL
BEGIN
.....and SO ON
``` | how to update table with multiple if..else statetemt | [
"",
"sql",
"t-sql",
""
] |
So here is my situation. I have 1 query that gets results grouped by date then I union all a second query that gets the totals (no grouping by date). My issue is I am calculating the average of fields and when I want to total up the average my numbers don't add up.
Here is my [SQLFiddle](http://sqlfiddle.com/#!2/aa3a9... | THe first part of the query can probably be written as:
```
SELECT t.end,
AVG(CASE WHEN t.start != t.end THEN TIMESTAMPDIFF(DAY, t.start, t.end) ELSE 1
END) as averageTime
FROM store t
GROUP BY t.end;
```
Presumably, you want the averages of the averages -- rather than the overall average. I assume ... | Your question is not clear. But, I suppose you need Average. As @samD mentioned,
the second part of you query can be written as
SELECT
'Total',
AVG(CASE WHEN (t.start != t.end) THEN TIMESTAMPDIFF(DAY, t.start, t.end) ELSE 1 END) as averageTime
FROM store t | Getting total using Union All | [
"",
"mysql",
"sql",
""
] |
I have been doing a bit of searching for a while now on a particular problem, but I can't quite find this particular question
I have a rather unusual task to achieve in SQL:
I have two tables, say A and B, which have exactly the same column names, of the following form:
```
id | column_1 | ... | column_n
```
Both t... | Yes you can do that with a query like this:
```
WITH Diffs (Id, Col) AS (
SELECT
a.Id,
CASE
WHEN a.Col1 <> b.Col1 THEN 'Col1'
WHEN a.Col2 <> b.Col2 THEN 'Col2'
-- ...and so on
ELSE NULL
END as Col
FROM TableOne a
JOIN TableTwo b ON a.I... | You can do this with an `unpivot` -- assuming that the values in the columns are of the same type.
If your data is not too big, I would just recommend using a bunch of `union all` statements instead:
```
select a.id, 'Col1' as column
from a join b on a.id = b.id
where a.col1 <> b.col1 or a.col1 is null and b.col1 is ... | Compare the data in two tables with same schema | [
"",
"sql",
"sql-server",
"database",
""
] |
I have these 2 tables:
```
table1
uid points
5 13
7 9
12 5
17 3
1 1
2 2
3 1
table2
uid points
9 21
13 17
15 11
17 7
12 6
2 2
1 3
22 1
```
I need a query to return top 5 users have points
Target result:
```
uid points
9 21
13 17
5 13
12 11
1... | ```
SELECT al.uid as UID , SUM(al.points) AS total_points FROM (SELECT points, uid FROM table1
UNION ALL
SELECT points,uid FROM table2) al group by al.uid
``` | Try This
```
select uid, (table1.points + table2.points) as c from table1
Left join table2 on table1.uid = table2.uid
order by (table1.points + table2.points) desc limit 5
``` | Sum from different fields in different MySQL tables | [
"",
"mysql",
"sql",
""
] |
I am working on automating some data that I receive from Germany. The Date format comes in as DD.MM.YYYY and I need it to be MM/DD/YYYY.
I am building an import package using SSIS and I added a derived column to change the date format.
I first tried to use
```
(DT_DATE) [CalendarDay]
```
but I keep getting an error... | 1) Source :- Flat file use DT\_date for Date column
2) Derived Column :- Replace this with using
SUBSTRING([Column 2],4,4) + "/" + SUBSTRING([Column 2],5,2) + "/" + SUBSTRING([Column 2],7,2)
and use DT\_DATE IN Datatype
3) Destination :- Use datetime as datatype for date
Run it
Thanks! | Try instead:
-- Issue with date column... use DT\_Date and then in derived column use substring to include
```
// so date will become 2009/02/05 and then transfer data to destination...
```
it will work out..
Thanks!
Nilesh | Convert Date from Excel Import | [
"",
"sql",
"excel",
"date",
"ssis",
""
] |
I have a mysql database with a table **entites** with multiple fields in it like entity\_title, entity\_description, ... . In the table there are also 3 foreign keys **user\_id**, **region\_id** an **category\_id**.
In my Index View I would like to show all the entities in a table (show the title, description, ... , t... | Your problem is
> I think MySql connector probably doesn't support multiple active result sets and because of that the setting in connection string didn't help you.
***So Please try this way instead of your code***
**Edit :**
```
query.Include("User").Include("Region").Include("Category").ToList();
```
Let me know... | **UPDATE**
OK, so from your stack trace it looks like the "`open DataReader associated ...blah`" was a red-herring. Maybe that was visual studio and its intellisense visual debugger thingy trying to show you the values contained in your dbset but a connection was still open or something like that.
To me, it looks lik... | There is already an open DataReader associated with this Connection which must be closed first + asp.net mvc | [
"",
"mysql",
"asp.net",
"sql",
"asp.net-mvc",
"entity-framework",
""
] |
I want to generate date value since 1/1/2011 - 31/12/2011 on sql query.
Example
My Table A
```
Field A Field B Field C
1 01/01/2011 125
2 03/01/2011 100
3 05/01/2011 50
```
I want to result :
```
Field A Field B Field C
1 01/01/2011 125
... | Under SQL Server, you can create a table-valued function rather than creating a temporary table, as this is reusable between queries:
```
-- List all of the dates between startdate and enddate (inclusive)
CREATE FUNCTION [dbo].[DatesBetween] (
@startdate date,
@enddate date
) RETURNS @ret TABLE (Date date) AS ... | If your "Field B" is formatted as Date, you can use the function DATEDIFF(Day,StartDate,EndDate)
you can also change the "DATEDIFF(Day" to Year, Month or any other part you like.
hope this helps. | How to generate date in SQL Query? | [
"",
"sql",
"date",
"insert",
"dateadd",
""
] |
I have a table
```
id value
1 a
2 a
3 b
4 b
5 b
6 c
```
My id is primary.
I have total 2 a , 3 b and 1 c. So I want to count total repeat value in each primary id which matches on it
I want this format
```
id value_count
1 2
2 2
3 3
4 3
5 3
6 1
``` | Try this query:
```
SELECT a.id, b.valueCnt
FROM tableA a
INNER JOIN (SELECT a.value, COUNT(a.value) valueCnt
FROM tableA a GROUP BY a.value) AS B ON a.value = b.value;
```
Check the [**SQL FIDDLE DEMO**](http://www.sqlfiddle.com/#!2/68a89/1)
**OUTPUT**
```
| ID | VALUECNT |
|----|----------|
| 1 | ... | Try This
```
select id, value_count from tablename as a1
join (select count(*) as value_count, value from tablename group by value) as a2
on a1.value= a2.value
``` | count value for each unique id | [
"",
"mysql",
"sql",
"select",
"count",
"group-by",
""
] |
I basically have a very simple query like such
```
SELECT accounts . * , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive
ORDER BY COUNT(receive) DESC
```
I've tried changing it to the following and it's ... | First: **remove the space between the table and the `*`**: `accounts.*`.
Second: You cannot use `where` on aggregate expressions. You need to use `having`:
```
SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GRO... | To filter *before* a `GROUP BY` clause, use `WHERE`, to filter *afterwards*, use `HAVING`. Since the aggregation of the `count` occurs during the grouping, it gives an error in the `WHERE` clause - it's simply not known yet at that point of execution. Change to:
```
SELECT accounts.* , COUNT(receive) as total_counts
F... | Filtering grouped results on COUNT of a number of rows | [
"",
"mysql",
"sql",
""
] |
We have a client that is going to use the AlwaysOn Availability feature of SQL Server 2012.
They want to have the BizTalk WCF-SQL port connect to the read-only replica.
The [documentation](http://technet.microsoft.com/en-us/library/hh213417.aspx#ReadOnlyAppIntent) on the subject say that the connection has to be made ... | There is no way of doing this via the WCF-SQL adapter.
We have had to go with an external helper class to create the connection with a connection string and query the database.
Update: A Blog written by a colleague on the issue [Can I use a BizTalk WCF-SQL send adapter with a SQL 2012 Always on Database?](http://conne... | I think you'll need to go WCF-Custom + sqlBinding to specify a connection string. | How do you configure a BizTalk WCF-SQL adapter to get data from a SQL Server 2012 "always on" replica database? | [
"",
"sql",
"sql-server",
"wcf",
"biztalk",
"biztalk-2013",
""
] |
I have table Groups,
```
ID NUMBER
STATUS VARCHAR2(20 BYTE)
```
I am able to count the number of status as following.
```
select g.status, count(*) from groups g group by g.status;
STATUS COUNT(*)
-------------------- ----------
OK 2
NOK 1
```
... | Try this
```
SELECT A.status, COUNT(DISTINCT G.ID) statusCnt
FROM (SELECT 'OK' status FROM DUAL
UNION
SELECT 'NOK' status FROM DUAL
UNION
SELECT 'PENDING' status FROM DUAL
UNION
SELECT 'REJECTED' status FROM DUAL
) AS A
LEFT JOIN groups G ON A.status = G.STATUS
GROUP BY A.... | If exists a table with list of states you can write your query in this way:
I suppose your state registry has called STATES
```
SELECT
states.status,
(select count(*) from groups g where g.status = states.status)
FROM states
```
Alternatively:
```
SELECT
s.status, count(*)
FROM states s
LEFT OUTER JOIN ... | SQL Count non existing item | [
"",
"sql",
"postgresql",
"select",
"count",
"left-join",
""
] |
Im trying to use an SQL statement to insert the current date into an access table.
Ive got
```
DoCmd.RunSQL "INSERT INTO tblImportedData (dtmReportDate) VALUES Now();"
```
This isnt working. Anybody know what im doing wrong? | You need to put `Now()` between brackets like this:
```
INSERT INTO tblImportedData (dtmReportDate) VALUES (NOW())
``` | You need to put parenthesis around your list of values, even though there's only one column you're inserting into:
```
DoCmd.RunSQL "INSERT INTO tblImportedData (dtmReportDate) VALUES (Now());"
``` | Insert todays date into Access table using SQL | [
"",
"sql",
"vba",
"ms-access",
""
] |
I have a submission page that I need to limit the number of attempts that a user can try in a specific time period.
There is a stored procedure that is called that checks for certain data in database1 and also logs the IP address and the date/time the form was submitted into database2.
All I need to do is check how m... | The problem is that you instantiate your `SqlDataAdapter` using command text only (passing the query but not parameters) so it doesn't have the parameter passed:
```
Dim ap As New SqlDataAdapter(comm.CommandText, sqlConnection1)
```
you should use the command instead and instantiate your command passing the connectio... | You might have an instance of SQL Server will be case sensitive. Can you check how IPAddress parameter is defined in `proc_ReverseTransferConsent_Find_Match` stored procedure? | VB.NET SQL limit submission attempts | [
"",
"asp.net",
"sql",
"vb.net",
""
] |
Suppose I have a string `1,2,3,` I would like to remove the last `,` or if the string looks like `,1,2,3,` or `,1,2,3` I would still like to get `1,2,3` as my result.
And please try to be a little explanatory in your answer. I do not just want to copy paste stuff without understanding it. Thank you. | One way to deal with "trimming" commas like that would be using a `CASE` statement:
```
CASE
WHEN str LIKE ',%,' THEN SUBSTRING(str, 2, LEN(str)-2)
WHEN str LIKE ',%' THEN RIGHT(str, LEN(str)-1)
WHEN str LIKE '%,' THEN LEFT(str, LEN(str)-1)
ELSE str
END
```
This is very much self-explanatory: the `C... | ```
declare @str varchar(20)=',1,2,3,'
select case
when @str like ',%,' then stuff(stuff(@str, 1, 1, ''),LEN(stuff(@str, 1, 1, '')),1,'')
when @str like ',%' then stuff(@str, 1, 1, '')
when @str like '%,' then stuff(@str, LEN(@str), 1, '')
else @str
end
``` | How to remove a specific character from a string, only when it is the first or last character in the string. | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.