Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm facing a database that keeps the ORDERING in columns of the table.
It's like:
```
Id Name Description Category OrderByName OrderByDescription OrderByCategory
1 Aaaa bbbb cccc 1 2 3
2 BBbbb Aaaaa bbbb 2 1 2
3 cccc... | It can make sense for many reasons but mainly when you don't want to follow the "natural order" given by the `ORDER BY` clause.
This is a scenario where this can be useful :
[SQL Fiddle](http://sqlfiddle.com/#!3/ce569/1)
**MS SQL Server 2008 Schema Setup**:
```
CREATE TABLE Table1
([Id] int, [Name] varchar(15),... | I think it makes little sense for two reasons:
1. Who is going to maintain this set of values in the table? You need to update them every time any row is added, updated, or deleted. You can do this with triggers, or horribly buggy and unreliable constraints using user-defined functions. But why? The information that s... | SQL Server: Use a column to save order of the record | [
"",
"sql",
"sql-server",
"database",
"database-design",
"relational-database",
""
] |
I want to create a query that will return all the route\_id, that contain both stop variables.
```
| route_stop_id | route_id | stop_id | time (in sec) |
———————————————————————————————————————————————————————————————————————
| 1 | 1 | 1 | 3:24pm |
| 2 ... | use this one (edited)
```
SELECT t1.route_id
FROM route_stop_list t1 join route_stop_list t2 on t1.route_id=t2.route_id
where t1.stop_id=1 AND t2.stop_id=2
```
explanation
i am joining the 2 tables first(your table with itself). t1 and t2 are just aliases(nicknames) for the tables so that you can refer to them lat... | Please try:
```
SELECT route_id
FROM route_stop_list
WHERE stop_id IN (1, 2)
GROUP BY route_id
HAVING COUNT(DISTINCT stop_id)=2
``` | SQL Statement filtering | [
"",
"sql",
""
] |
I got a question from <http://sqlzoo.net/wiki/SUM_and_COUNT_Quiz#quiz0>, the 4th one. I chose the second option, but it turned out the fifth option is the right answer. I don't know why this sql sentence is wrong. Can anyone tell me the reason? Thank you in advance.
the sql sentence is shown below:
```
SELECT region,... | You can't use SUM(area) in WHERE clause.
For that to be valid you had to use HAVING after the GROUP BY:
```
SELECT region, SUM(area) FROM bbc GROUP BY region HAVING SUM(area) > 15000000;
``` | To understand why take a look at a logical query processing order which roughly looks like
1. FROM
2. **WHERE**
3. GROUP BY
4. HAVING
5. SELECT
6. ORDER BY
`WHERE` comes before `GROUP BY` therefore you can't use aggregate functions directly in it. That what the `HAVING` clause is for. | sql error about where and group by | [
"",
"sql",
""
] |
I have two tables -
Table 1: `Types`
```
ID | Type
---+------
1 | type1
2 | type2
3 | type3
4 | type4
5 | type5
6 | type6
```
Table 2: `Details`
```
ID | Type | EventName | Cost
---+--------+-----------+------
1 | type1 | name1 | 500
2 | type1 | name2 | 500
3 | type2 | name3 | 500
4 | ty... | ```
SELECT t.Type, count(d.Type), sum(d.cost)
FROM Types t LEFT JOIN Details d ON t.Type=d.Type
group by t.Type,d.Type
``` | ```
SELECT
t.Type,
count(t.type) as Number,
sum(d.cost) as Cost
FROM
Types t
INNER JOIN Details d
ON t.type=d.type
GROUP BY t.type
``` | SQl Left Join with tables | [
"",
"sql",
"join",
"left-join",
""
] |
I have an SQL script in oracle which is almost complete but I am stuck on one last issue.
I have 2 database tables I am accessing data from, and inserting the new rows into a new table in my database.
One of the database tables has an account number column and a descriptor column, and each account number has 3 descrip... | The real answer is to learn about normal form and redesign this database. However you could do something hideous like:
```
Select
Account_Number,
max(Case
When Descriptor Like 'Company: %' then substr(Descriptor, 10, 1000)
end) Company_Description,
max(Case
When Descriptor Like 'Cost... | try this query:
```
create table mydb.test1 as
select distinct
account as Account_Number,
(select (case when t2.Description like 'Company%' then t2.description end) from testdb.table1 t2 where t1.account=t2.account and
case when t2.Description like 'Company%' then t2.description end is not null)as Company_Description... | Combine 2 column values in 1 to many into new row in new table - SQL | [
"",
"sql",
"database",
"oracle",
"one-to-many",
""
] |
I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
```
insert into `mytable` (`id`, `name`) values (10, `Fred`)
```
I want to be able to check to see if any other row in the table already has `name ... | First of all, your `id` field should be an `autoincrement`, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for `id` for each row.
If it's not the case, you should create a primary key for the table that includes **ALL**... | You could use something like this
```
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");
```
This will insert a new row, unless a row already exists with a duplicate key, it will update it. | Insert new row unless ONE of the values matches another row? | [
"",
"mysql",
"sql",
""
] |
I have a table and need to verify that a certain column contains only dates. I'm trying to count the number of records that are not follow a date format. If I check a field that I did not define as type "date" then the query works. However, when I check a field that I defined as a date it does not.
Query:
```
SELECT ... | If you defined the column with the Date type, it ***IS*** a Date. Period. This check is completely unnecessary.
What you may want to do is look for `NULL` values in the column:
```
SELECT SUM(case when Date_Field IS NULL THEN 1 ELSE 0 end) as 'Date_Error' FROM [table]
```
I also sense an additional misunderstanding ... | `ISDATE()` only evaluates against a STRING-like parameter (varchar, nvarachar, char,...)
To be sure, `ISDATE()`'s parameter should come wrapped in a cast() function.
i.e.
```
Select isdate(cast(parameter as nvarchar))
```
should return either 1 or 0, even if it's a MULL value.
Hope this helps. | SQL Server ISDATE() Error | [
"",
"sql",
"sql-server",
""
] |
I have a column in database that stores an array of numbers in a nvarchar string and the values look like this
`"1,5,67,122"`
Now, I'd like to use that column value in a query that utilizes IN statement
However, if I have something like
```
WHERE columnID IN (@varsArray);
```
it doesn't work as it sees @varsArray a... | You need dynamic SQL for that.
```
exec('select * from your_table where columnID in (' + @varsArray + ')')
```
### And BTW it is bad DB design to store more than 1 value in a column! | alternatively you can parse your variable with finding a split user defined function on the internet and enter each number into a temp table and then join the temp table
but the person who answered above is correct this is bad database design
create a table so you can join it based on some id, and all the answers wil... | Using a String Array in an IN statement | [
"",
"sql",
"t-sql",
""
] |
I have an MS Access (.accdb) table with data like the following:
```
Location Number
-------- ------
ABC 1
DEF 1
DEF 2
GHI 1
ABC 2
ABC 3
```
Every time I append data to the table I would like the number to be unique to the location.
I am accessing this table through MS Excel VBA - I woul... | I suspect that you are looking for something like this:
```
Dim con As ADODB.Connection, cmd As ADODB.Command, rst As ADODB.Recordset
Dim newNum As Variant
Const fLabel_Location = "O'Hare" ' test data
Set con = New ADODB.Connection
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.ac... | You need to add a new column to your table of data type `AutoNumber`.
[office.microsoft.com: Fields that generate numbers automatically in Access](http://office.microsoft.com/en-gb/access-help/fields-that-generate-numbers-automatically-in-access-HA001055067.aspx)
You should probably also set this column as your prima... | Generate a sequential number (per group) when adding a row to an Access table | [
"",
"sql",
"excel",
"vba",
"ms-access",
""
] |
How can i split a decimal value into two decimal values.
if the decimal number which has fractional part that is less than .50 or greater than .50 .it should split in such a way that first no should end with only .00 or .50. second value should contain the remaining factorial value.
```
ex. 19.97 should return 19.50 ... | You can "floor" to the highest multiple of 0.5 by multiplying by 2, calling `FLOOR`, then dividing by 2. From there just subtract that from the original value to get the remainder.
```
DECLARE @test decimal(10,7)
SELECT @test =19.97
SELECT
FLOOR(@test * 2) / 2 AS base,
@test - FLOOR(@test * 2) / 2 AS fracti... | ```
Declare @money money
Set @money = 19.97
Select convert(int,@money - (@money % 1)) as 'LeftPortion'
,convert(int, (@money % 1) * 100) as 'RightPortion'
``` | spliting a decimal values to lower decimal in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
SELECT image_id,
CASE image_id
WHEN 0 THEN (SELECT image_path
FROM images
WHERE image_id IN (SELECT default_image
FROM registration
WHERE reg_id IN (SELECT favo... | Maybe this:
```
SELECT image_id,
CASE image_id
WHEN 0 THEN (SELECT image_path
FROM images
WHERE image_id IN (SELECT default_image
FROM registration
WHERE reg_id IN... | You need to write condition like below :
```
SELECT image_id,
CASE image_id
WHEN 0 THEN (SELECT image_path
FROM images
WHERE image_id IN (SELECT default_image
FROM registration
... | multi case selection in a stored procedure | [
"",
"mysql",
"sql",
"sql-server",
"stored-procedures",
"case",
""
] |
I am attempting to set variables whose names are dynamic in a stored procedure:
```
DECLARE @var01 varchar(50)
DECLARE @var02 varchar(50)
...
DECLARE @var30 varchar(50)
DECLARE @sql = varchar(max)
DECLARE @loopcnter INT
-- (Inside some loop where the loopcounter increments each iteration)
...
SET @sql = 'S... | Well, it is not pretty, but you can do:
```
if @loopcntr = 1
set var01 = 'somevalue'
else if @loopcntr = 2
set var02 = 'whatever'
else if . . .
```
This should be sufficiently unpleasant that you might think of alternatives. Oh, here's a good one. Define a table variable and just add rows in for each value:
... | You can also use stored procedure sp\_executesql which allows passing parameters. Although
I recommend to use additional table to store variables. | SQL: Dynamic Variable Names | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
""
] |
this question I've found is driving me nuts, (edit:) because I'm trying to achieve this without the order by method.
I have a table:
**BookAuthors**(book, author)
```
book author
------ ---------
1 Joy McBean
2 Marti McFly
2 Joahnn Strauss
2 Steven Spoilberg
1 Quentin Toronto
3 ... | ```
SELECT cnt.book, maxauth.mx
FROM (
SELECT MAX(authors) as mx
FROM
(
SELECT book, COUNT(author) AS authors
FROM BookAuthors
GROUP BY book
) t
) maxauth JOIN
(
SELECT book, COUNT(author) AS authors
FROM BookAuthors
... | ```
select book, max(authors)
from ( select B.book, count(B.author) as authors
from BookAuthors B group by B.book )
table1;
```
I could not try this as i dont have mysql with me... You try and let me know... | max() value from a nested select without ORDER BY | [
"",
"mysql",
"sql",
"nested",
"subquery",
""
] |
The column is "CreatedDateTime" which is pretty self-explanatory. It tracks whatever time the record was commited. I need to update this value in over 100 tables and would rather have a cool SQL trick to do it in a couple lines rather than copy pasting 100 lines with the only difference being the table name.
Any help ... | If that's a one time task, just run this query, copy & paste the result to query window and run it
```
Select 'UPDATE ' + TABLE_NAME + ' SET CreatedDateTime = ''<<New Value>>'' '
From INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'CreatedDateTime'
``` | You could try using a cursor : like this
```
declare cur cursor for Select Table_Name From INFORMATION_SCHEMA.COLUMNS Where column_name = 'CreatedDateTime'
declare @tablename nvarchar(max)
declare @sqlstring nvarchar(max)
open cur
fetch next from cur into @tablename
while @@fetch_status=0
begin
--... | I have the same column in multiple tables, and want to update that column in all tables to a specific value. How can I do this? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a quite common case of two tables: 'Orders' placed and 'ItemsBought' for each order:
```
Orders: orderId, orderDate, [...]
ItemsBought: boughtId, orderId, itemId, [...]
```
Order can have one or more ItemsBought. Now, I want to select only those orders where users bought BOTH itemId=1 AND itemId=2.
Say, we ha... | Try something like this:
```
SELECT orderId
FROM ItemsBought
WHERE itemId IN (1,2)
GROUP BY orderId
HAVING COUNT(orderId) = 2;
```
This will only work if you can't have multiple items 1 or 2 in the same orderid.
`sqlfiddle demo` | I'm positive there is a more efficient way to do this but here's one simple solution. Basically just do an inner join on the two separate subqueries which pull back the lines you want.
The results will be the intersection between the two sets or in otherwords those orders where both items were found.
```
Select order... | Select orderId if it has both items bought | [
"",
"sql",
"ms-access",
"ms-access-2010",
""
] |
Using TSQL, what's the most efficient way to convert a datatype string formatted date 'mmm-dd-yyyy' to data type date format 'yyyy-mm-dd'
Example:
Original date: Jan-31-2013
Converted date: 2013-01-31
I was looking for the conversion in this document but no success. <http://msdn.microsoft.com/en-us/library/ms187928... | This solves your problem, not sure if there's a more efficient solution though?
```
declare @DateTime as varchar(max)
set @DateTime = 'Jan-31-2013';
select cast(substring(@DateTime,8,4) + '-' + substring(@DateTime,1,3) + '-' + substring(@DateTime,5,2) as date)
```
, 0)
```
Most effective way returned as char(10):
```
select convert(char(10),convert(date, replace('Jan-31-2013', '-', ' '), 0), 126)
``` | Using T-SQL, how to convert date format mmm-dd-yyyy to yyyy-mm-dd | [
"",
"sql",
"sql-server",
"t-sql",
"date",
""
] |
I have a table A with three columns a b c. I want to insert values in to columns a and b based on the join of column c with another table B
I am using the following query
```
MERGE INTO A
USING
(SELECT * FROM B) **B**
ON (B.c=A.c)
WHEN MATCHED THEN
INSERT(a,b) VALUES(local_varialble,'STRING');
```
I am getting the f... | What exactly are you trying to achieve here? You want to insert some data into table `A` when there is connection between rows in tables `A` and `B`, but you do not use any values from columns of the `B` column.
Merge won't work like the way you wrote it, because you **have to** have either an `UPDATE` or `DELETE` sta... | I think that you need to define first a "merge\_update\_clause" (see [merge documentation](http://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_9016.htm))
like this:
```
MERGE INTO A
USING (SELECT * FROM B) b
ON (B.c = A.c)
WHEN MATCHED THEN UPDATE SET ....
DELETE WHERE ...
WHEN NOT MATCHED TH... | Insert based on inner join oracle sql | [
"",
"sql",
"database",
"oracle",
"plsql",
"oracle11g",
""
] |
A simplified version of my MySQL db looks like this:
```
Table books (ENGINE=MyISAM)
id <- KEY
publisher <- LONGTEXT
publisher_id <- INT <- This is a new field that is currently null for all records
Table publishers (ENGINE=MyISAM)
id <- KEY
name <- LONGTEXT
```
Currently books.publisher holds values that keep getti... | There are a few problems here that might be helped by optimization.
First of all, a few thousand rows doesn't count as "big" ... that's "medium."
Second, in MySQL saying "I want to do this without indexes" is like saying "I want to drive my car to New York City, but my tires are flat and I don't want to pump them up.... | Your question title says ".. optimize ... query without using an index?"
What have you got against using an index?
You should always examine the execution plan if a query is running slowly. I would guess it's having to scan the `publishers` table for each row in order to find a match. It would make sense to have an i... | Can I optimize such a MySQL query without using an index? | [
"",
"mysql",
"sql",
"query-optimization",
""
] |
I'm creating a report using SQL to pull logged labor hours from our labor database for the previous month. I have it working great, but need to add logic to prevent it from breaking when it runs in January. I've tried adding If/Then statements and CASE logic, but I don't know if I'm just not doing it right, or if our s... | Just use AND as a barrier like this. In January, the second clause will be executed instead of the first one:
```
SELECT
...
FROM
...
WHERE
...
AND
(
(
(MONTH(current date) > 1) AND
(YEAR(ENTERDATE) = YEAR(current date) AND MONTH(ENTERDATE) = (MONTH(current date)-1))
-- this one gets us... | If your report is always going to be for the previous month, then I think the simplest idea is to declare the year and month of the previous month and then reference those in the Where clause. For example:
```
Declare LastMo_Month Integer = MONTH(DATEADD(MONTH,-1,getdate()));
Declare LastMo_Year Integer = YEAR(DATEADD... | How to add check for January in SQL statement | [
"",
"sql",
""
] |
I work with entity-attribute-value database model.
My product have many attribute\_varchars and attribute\_varchars have one attribute. An attribute has many attribute\_varchars and an attribute varchar has one product. Same logic apply to attribute\_decimals and attribute\_texts.
Anyway, i have the following query a... | In MySQL, you can do:
```
having rate > 5
```
MySQL has extended the `having` clause so it can work without a `group by`. Although questionable as a feature, it does allow you to reference aliases in the `select` clause without using a subquery. | With generated column like that, the best way is to made your query as a subquery, and do your filtering on the upper level like that:
```
SELECT *
FROM
(
SELECT
products.id,
(select value from attribute_texts where product_id = products.id and attribute_id = 1)
as description,
(select value f... | MySQL where clause targeting dependent subquery | [
"",
"mysql",
"sql",
"entity-attribute-value",
""
] |
So someone gave me a spreadsheet of orders, the unique value of each order is the PO, the person that gave me the spreadsheet is lazy and decided for orders with multiple PO's but the same information they'd just separate them by a "/". So for instance my table looks like this
```
PO Vendor State
123456/... | If I had to do it I would
* Import the raw data into a table named [TempTable].
* Copy [TempTable] to a new table named [ActualTable] using the "Structure Only" option.
Then, in a VBA routine I would
* Open two DAO recordsets, `rstIn` for [TempTable] and `rstOut` for [ActualTable]
* Loop through the `rstIn` recordse... | About about this:
1) Import the source data into a new Access table called SourceData.
2) Create a new query, go straight into SQL View and add the following code:
```
SELECT * INTO ImportedData
FROM (
SELECT PO, Vendor, State
FROM SourceData
WHERE InStr(PO, '/') = 0
UNION ALL
SELECT Left(PO, InStr(PO, '/'... | Split delimited entries into new rows in Access | [
"",
"sql",
"ms-access",
"vba",
"delimiter",
""
] |
Can you format a phone number in an postgreSQL query? I have a phone number column. The phone numbers are held as such: 1234567890. I am wondering if postgres will format to (123) 456-7890. I can do this outside the query, I am using php, but it would be nice if I was able to have the output of the query like (123) 456... | Use [SUBSTRING](http://www.postgresql.org/docs/9.1/static/functions-string.html) function
something like:
```
SELECT
'(' || SUBSTRING((PhoneNumber, 1, 3) + ') ' || SUBSTRING(PhoneNumber, 4,3) || '-' || SUBSTRING((PhoneNumber,7,4)
``` | This will work for you:
```
SELECT
'( ' || SUBSTRING(CAST(NUMBER AS VARCHAR) FROM 1 FOR 3) || ' ) '
|| SUBSTRING(CAST(NUMBER AS VARCHAR) FROM 4 FOR 3) || '-'
|| SUBSTRING(CAST(NUMBER AS VARCHAR) FROM 7 FOR LENGTH(CAST(NUMBER AS VARCHAR)))
FROM
YOURTABLE
```
Also, here is a [SQLFiddle](http://sqlfiddle.com/#!1... | formating a phone number in the postresql query | [
"",
"sql",
"postgresql",
""
] |
I need a SQL statement that will find all OrderIDs within a table that have an ActivityID = 1 but not an ActivityID = 2
So here's an example table:
OrderActivityTable:
```
OrderID // ActivityID
1 // 1
1 // 2
2 // 1
3 // 1
```
So in this example, OrderID - 1 has activity of 1 AND 2, so that ... | You can use an outer self-join for this:
```
SELECT *
FROM OrderActivityTable t1
LEFT JOIN OrderActivityTable t2
ON t1.OrderID = t2.OrderID AND t2.ActivityID = 2
WHERE t1.ActivityID = 1
AND t2.OrderID IS NULL
```
You can also use the `WHERE NOT IN` solution of Mike Christensen, or the correlated subquery solution of ... | Something like:
```
SELECT OrderID, ActivityID FROM OrderActivityTable
WHERE ActivityID = 1
AND OrderID NOT IN (select distinct OrderID from OrderActivityTable where ActivityID = 2);
```
This will select everything in `OrderActivityTable` where `ActivityID` is 1, but filter out the list of `OrderID` rows that contain... | SQL statement to get values that have one property but not another property | [
"",
"sql",
""
] |
I need to insert approximatlly 10 records.I am thinking foreach loop,do u think is it the best way to do that.whenn searching what is the best method to do that,I find something like this,
```
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ... | ```
INSERT INTO MyTable (FirstCol, SecondCol)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
GO
```
Both the `foreach` loop and the `union all` methods would be what is called "Row by Agonizing Row" approach | Just Create a single for inserting all the record..
Because foreach loop will hit the database 10 times and u will take more time and resources..
So better to make single query for all the 10..
```
INSERT INTO Table ( FirstCol, SecondCol) VALUES
( Value1, Value2 ), ( Value1, Value2 )...
``` | bulky insert record to database | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table-valued parameter like this
CREATE TYPE dbo.Loc AS TABLE(Lo integer);
My stored procedure looks like this:
```
ALTER PROCEDURE [dbo].[T_TransactionSummary]
@startDate datetime,
@endDate datetime,
@locations dbo.Loc readonly
... | There are some examples of how to do this at <http://msdn.microsoft.com/en-us/library/bb675163%28v=vs.110%29.aspx> (see the section titled "Passing a Table-Valued Parameter to a Stored Procedure
").
The simplest thing would seem to be filling a `DataTable` with the values the user selected and passing that to the stor... | ```
cnt = LSTlocations.SelectedItems.Count
' *** Set up the DataTable here: *** '
Dim locTable As New DataTable
locTable.Columns.Add("Lo", GetType(Integer))
If cnt > 0 Then
For i = 0 To cnt - 1
Dim locationanme As String = LSTlocations.SelectedItems(i).ToString
locid = RecordID("Locid", "Location_t... | while using table valued parameter how to pass multiple parameter together to stored prcocedure | [
"",
"sql",
"vb.net",
""
] |
I have a `Toplist` table and I want to get a user's rank. How can I get the row's index?
Unfortunately, I am getting all rows and checking in a for loop the user's ID, which has a significant impact on the performance of my application.
How could this performance impact be avoided? | You can use ROW.NUMBER
This is a example syntax for MySQL
```
SELECT t1.toplistId,
@RankRow := @RankRow+ 1 AS Rank
FROM toplist t1
JOIN (SELECT @RankRow := 0) r;
```
This is a example syntax for MsSQL
```
SELECT ROW_NUMBER() OVER(ORDER BY YourColumn) AS Rank,TopListId
FROM TopList
``` | You may also do something like this:
```
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS MyIndex
FROM TopList
``` | How can I get row's index from a table in SQL Server? | [
"",
"sql",
"sql-server",
"row",
"rank",
""
] |
I have a table in the database with records like following:
```
match_id | guess | result
125 | 1 | 0
130 | 5 | 0
233 | 11 | 0
125 | 2 | 0
```
my users choose a guess for each match and I have a function that calculate the result of the guess depending on the result of the m... | use these two query:
```
UPDATE `tahminler`
SET result=0
WHERE match_id='1640482'
AND tahmin IN ('1','2','3','4','5','6','7','9','10')
```
And then use this:
```
UPDATE `tahminler`
SET result=1
WHERE match_id='1640482'
AND tahmin IN ('8','11')
``` | You can do this, but it will be also ugly. Use [CASE()](http://dev.mysql.com/doc/refman/5.0/en/case.html) operator, like:
```
UPDATE tahminler
SET
result=CASE
WHEN tahmin IN ('1','2','3','4','5','6','7','8','9','10') THEN 0
WHEN tahmin IN ('8', 11) THEN 1
END
WHERE
match_id='1640482'
``` | MySQL Update query with multiple values | [
"",
"mysql",
"sql",
""
] |
I have Mysql Database, with two tables, one with two key values, and the second one related to it 1 to N.
the first table always have data, but the second table related to it may not have.
I need to always return data from the first one, independent if theres none in the second table.
Heres my query :
```
select a.*... | use [join](http://en.wikipedia.org/wiki/Join_%28SQL%29) syntax... to join tables.
In your case, a LEFT JOIN.
```
select a.*, b.* FROM disp_ofer a
Left join ofer_detl b
on b.disp_ofer_data = a.disp_ofer_data and b.esta_cod = a.esta_cod
WHERE
a.esta_cod = 'Lelis'
AND
a.disp_ofer_data = '2013-10-30 16:07:20'
``... | Always use the [`JOIN`](http://dev.mysql.com/doc/refman/5.0/en/join.html) syntax rather than listing multiple tables in the `FROM` statement. It's considered a better practice.
A `LEFT JOIN` will allow you to achieve this goal. The `NATURAL` keyword will perform then join on all columns that exists in both tables auto... | select from two tables and always return from one | [
"",
"mysql",
"sql",
"database",
""
] |
I'm trying to write a query that will tell me the number of each colors for `Female`.
```
White - 2
Blue - 5
Green - 13
```
So far I have the following query with some of my attempts commented out:
```
SELECT a.id AS aid, af.field_name AS aname, afv.field_value
FROM applications app, applicants a, application_fields... | ```
SELECT f1.field_name, count(*) as total
FROM application_fields f1
JOIN applications_fields_values v1
ON v1.application_field_id = f1.id
JOIN applications_fields_values v2
ON v1.applicant_id = v2.applicant_id
JOIN applications_fields f2
ON v2.application_field_id = f2.id
WHERE v1.field_value = ... | The query looks fine, just add the condition in the `WHERE` clause, adding in within `HAVING` should be done if you wish to filter out the results of based on grouping
Try this
```
SELECT
af.field_name AS aname,
count(afv.field_value) as totals
FROM
applications app,
applicants a,
application... | Trying to write a complex query to retrieve data | [
"",
"mysql",
"sql",
""
] |
Do Impala or Hive have something similar to PL/SQL's `IN` statements? I'm looking for something like this:
```
SELECT *
FROM employees
WHERE start_date IN
(SELECT DISTINCT date_id FROM calendar WHERE weekday = 'MON' AND year = '2013');
```
This would return a list of all the employees that started on a Monday in 201... | I should mention that this is one possible solution and my preferred one:
```
SELECT *
FROM employees emp
INNER JOIN
(SELECT
DISTINCT date_id
FROM calendar
WHERE weekday = 'FRI' AND year = '2013') dates
ON dates.date_id = emp.start_date;
``` | ```
select *
from employees emp, calendar c
where emp.start_date = c.date_id
and weekday = 'FRI' and year = '2013';
``` | Do Impala or Hive have something like an IN clause in other SQL syntaxes? | [
"",
"sql",
"hadoop",
"plsql",
"hive",
"impala",
""
] |
I have noticed that a table in my database contains duplicate rows. This has happened on various dates.
When i run this query
```
select ACC_REF, CIRC_TYP, CIRC_CD, count(*) from table
group by ACC_REF, CIRC_TYP, CIRC_CD
having count(1)>1
```
I can see the rows which are duplicated and how many times it excist... | ```
select max(id) as maxid, ACC_REF, CIRC_TYP, CIRC_CD, count(*)
from table
group by ACC_REF, CIRC_TYP, CIRC_CD
having count(*)>1
```
Edit:
I think this is valid in Sybase, it will find ALL duplicates except the one with the lowest id
```
;with a as
(
select ID, ACC_REF, CIRC_TYP, CIRC_CD,
row_number() over (pa... | It will only output the unique values from your current table along with the criteria you specified for duplicate entries.
This will allow you to do one step "insert into new\_table" from one single select statement.
Without having to delete and then insert.
```
select
id
,acc_ref
,circ_typ
... | Sybase removing duplicate data | [
"",
"sql",
"database",
"duplicates",
"sybase",
""
] |
Having an issue calculating money after percentages have been added and then subtracting , I know that 5353.29 + 18% = 6316.88 which I need to do in my tsql but I also need to do the reverse and take 18% from 6316.88 to get back to 5353.29 all in tsql, I might have just been looking at this too long but I just cant get... | 6316.88 is 118%, so to get back you need to divide 6316.88 by 118, then multiply by 100.
```
(6316.88/118)*100=5353.29
``` | ```
newVal = 5353.29(1 + .18)
origVal = newVal/(1 + .18)
``` | Percentage Plus and Minus | [
"",
"sql",
"t-sql",
""
] |
I've encountered here an inusited situation that I couldn't understand. Nor the documentation of the functions that I will write about has something to light up this thing.
I've a table with a field `titulo varchar2(55)`. I'm in Brazil, some of the characters in this field has accents and my goal is to create a simila... | The 'nlssort' function's documentation does not state that the output string will be a normalization of the input string, or that they will have same length. The purpose of the function is to return data that can be used to sort the input string.
See <http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions113.... | 1) Oracle distinguishes lengths in bytes and lengths in characters: `varchar2(55)` means 55 bytes, so 55 UTF-8 characters fit only if you are lucky: you should declare your field as `varchar2 (55 char)`.
2) Contortions like
```
replace(utl_raw.cast_to_varchar2(nlssort(
'FGHJTÓRYO DE YHJKS DA DGHQÇÃA DE ASGA XCVBGL EA... | Strange behavior of LENGTH command - ORACLE | [
"",
"sql",
"oracle",
""
] |
When I used this query above exception has thrown
```
SELECT FINQDET.InquiryNo,FINQDET.Stockcode,FINQDET.BomQty,FINQDET.Quantity,FINQDET.Rate,FINQDET.Required,FINQDET.DeliverTo,FSTCODE.TitleA AS FSTCODE_TitleA ,FSTCODE.TitleB AS FSTCODE_TitleB,FSTCODE.Size AS FSTCODE_Size,FSTCODE.Unit AS FSTCODE_Unit, ... | The table [Config]..FSTCODE is qualified with database name which works fine if you use alias. Otherwise you need to qualify full name as it is from different database | Looks like `FSTCODE` is a table in a different DB. In the first query, though the `JOIN` uses the DB name to identify the table, the `ON` statement does not. The second statement adresses this by using an `ALIAS`
You can also modify the first statement as
```
left outer join [Config]..FSTCODE
ON FINQDET.Stockcode=... | The multi-part identifier "tablename.column " could not be bound | [
"",
"sql",
"sql-server",
""
] |
Every day, the requests get weirder and weirder.
I have been asked to put together a query to detect which columns in a table contain the same value for all rows. I said "That needs to be done by program, so that we can do it in one pass of the table instead of N passes."
I have been overruled.
So long story short. ... | do you mean something like this?
```
WITH
TEST_CASE AS
(
SELECT 'X' A, 5 B, 'FRI' C, NULL D FROM DUAL UNION ALL
SELECT 'X' A, 3 B, 'FRI' C, NULL D FROM DUAL UNION ALL
SELECT 'X' A, 7 B, 'TUE' C, NULL D FROM DUAL
)
select case when min(A) = max(A) THEN 'A'
when min(B) = max(B) THEN 'B'
... | Optimizer statistics can easily identify columns with more than one distinct value. After statistics are gathered a simple query against the data dictionary will return the results almost instantly.
The results will only be accurate on 10g if you use ESTIMATE\_PERCENT = 100. The results will be accurate on 11g+ if you... | Detect all columns in an oracle table which have the same value in each row | [
"",
"sql",
"oracle",
"oracle10g",
""
] |
I have an array of words like this one:
```
$word1 = array('test1','test2','test3','test4','test5',...,'test20');
```
I need to search in my table every row that has at least one of these words in the `text` column. So far, I have this sql query:
```
SELECT * FROM TABLE WHERE text LIKE '$word1[0]' OR text LIKE '$wor... | If you use a table variable instead of a list to store your words then you can use something like:
```
DECLARE @T TABLE (Word VARCHAR(255) NOT NULL);
INSERT @T (Word)
VALUES ('test1'), ('test2'), ('test3'), ('test4'), ('test5'), ('test20');
SELECT *
FROM TABLE t
WHERE EXISTS
( SELECT 1
F... | You can use a SELECT like this without declaring an array:
```
SELECT * FROM TABLE WHERE text IN ('test1', 'test2', 'test3', 'test4', 'test5')
``` | How to minimize sql select? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need to check if two dates over lap with another two dates in my database.
My database looks like this
```
+----+--------------+------------+------------+
| id | code | StartDate | EndDate |
+----+--------------+------------+------------+
| 1 | KUVX-21-40 | 2013-10-23 | 2013-11-22 |
| 2 | UEXA286-12... | I believe the following condition matches every possible overlapping case.
```
WHERE
(
(ScopeStartDate <= EndDate AND ScopeEndDate >= StartDate)
)
```
except if you declare illogic timespans (for example, those which end before starting) | This is an old thread, but use BETWEEN. This is an excerpt from my timeclock, pls modify to your needs...
```
$qs = "SELECT COUNT(*) AS `count` FROM `timeclock` WHERE `userid` = :userid
AND (
(`timein` BETWEEN :timein AND :timeout OR `timeout` BETWEEN :timein AND :timeout )
... | MySQL check if two date range overlap with input | [
"",
"mysql",
"sql",
"datetime",
""
] |
I want to get all `data` in `id`'s 1-3 that are NOT in `id`'s > 6
I'm using id's for simplicity, but I'm really using timestamps.
```
CREATE TABLE test (
id bigint(20) NOT NULL AUTO_INCREMENT,
data varchar(3) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO test (id, data) VALUES... | ```
SELECT t1.data AS t1_data
FROM test t1
WHERE t1.id BETWEEN 1 AND 3
AND NOT EXISTS(
SELECT *
FROM test t2
WHERE t2.data = t1.data
AND t2.id > 6
);
``` | This is an example of a set-within-sets subquery. I like to approach these using aggregation with the `having` clause, because this is the most general approach. In your case:
```
select t1.data
from test t1
group by t.data
having sum(id between 1 and 3) > 0 and
sum(id > 6) = 0;
```
The conditions in the `hav... | Joining table to itself and selecting values that don't match | [
"",
"mysql",
"sql",
"join",
""
] |
I have this query:
```
SELECT Field1, OrderFor, Writeback, Actshipdate, Orderstatus, receivedate, receivetime
FROM orderinfo, shippinginfo
WHERE orderinfo.orderid = shippinginfo.orderid
AND shippinginfo.custid = '37782'
AND receivedate = DATE(NOW())
AND receivetime = ???????
```
I am using Sybase adaptive server any... | try this !!
```
SELECT Field1, OrderFor, Writeback, Actshipdate, Orderstatus, receivedate, receivetime
FROM orderinfo, shippinginfo
WHERE orderinfo.orderid = shippinginfo.orderid
AND shippinginfo.custid = '37782'
AND receivedate = DATE(NOW())
AND receivetime > DATEADD(HOUR, -1, GETDATE())
``` | Try below query:
```
SELECT Field1, OrderFor, Writeback, Actshipdate, Orderstatus, receivedate, receivetime
FROM orderinfo, shippinginfo
WHERE orderinfo.orderid = shippinginfo.orderid
AND shippinginfo.custid = '37782'
AND receivedate = DATE(NOW())
AND receivetime >= (sysdate-1/24);
``` | Get records from last hour | [
"",
"sql",
"sybase",
"sybase-asa",
""
] |
We are trying to select the first purchase for each customer in a table similar to this:
```
transaction_no customer_id operator_id purchase_date
20503 1 5 2012-08-24
20504 1 7 2013-10-15
20505 2 5 2013-09-05
20506 ... | You can simply treat the query you have come up with as an inner query. This will work on older version of SQL Server as well (you didn't specify version of SQL Server).
```
SELECT H.transaction_no, H.customer_id, H.operator_id, H.purchase_date
FROM Sales_Transactions_Header H
INNER JOIN
(SELECT customer_id, MIN(p... | You can use the [ROW\_NUMBER](https://learn.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql?view=sql-server-ver15) function to help you with that.
This is how to do it for your case.
```
WITH Occurences AS
(
SELECT
*,
ROW_NUMBER () OVER (PARTITION BY customer_id order by purchase... | Select first purchase for each customer | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
here's my query:
```
SELECT
p1.time_neu as Datum
count(p1.*) as Anzahl_Palette,
count(p2.*) as Anzahl_Stangen_Behaelter
FROM
00_Gesamt_Pickauf p1,
00_Gesamt_Pickauf p2
WHERE
p1.platz_von like '%-%-00-00' AND
p2.platz_von like ...
```
I've got trouble with the seco... | Try like this
```
SELECT
p1.time_neu as Datum
count(p1.*) as Anzahl_Palette,
count(p2.*) as Anzahl_Stangen_Behaelter
FROM
00_Gesamt_Pickauf p1,
00_Gesamt_Pickauf p2
WHERE
p1.platz_von NOT LIKE '%-00-00%' AND
p2.platz_von like ...
``` | ```
SELECT
p1.time_neu AS Datum
count(p1.*) AS Anzahl_Palette,
count(p2.*) AS Anzahl_Stangen_Behaelter
FROM
00_Gesamt_Pickauf p1,
00_Gesamt_Pickauf p2
WHERE
p1.platz_von like '%-%-%-%' AND
NOT (p1.platz_von like '%-%-00-00')
``` | SQL: Additional condition inside the 'like'-condition | [
"",
"mysql",
"sql",
"ms-access",
"sql-like",
""
] |
I'm new to databases and I'm thinking of creating one for a website. I started with SQL, but I really am not sure if I'm using the right kind of database.
Here's the problem:

What I have right now is the first option. So that means that, my query... | Your initial approach to having a `user_id, photo_id, photo_url` is correct. This is the normalized relationship that most database management systems use.
The following relationship is called "one to many," as a user can have many photos.

You may want to go as far as separat... | Your first example looks like a traditional relational database, where a table stores a single record per row in a standard 1:1 key-value attribute set. This is how data is stored in RDBMS' like Oracle, MySQL and SQL Server. Your second example looks more like a document database or NoSQL database, where data is stored... | What is this form of database called? | [
"",
"sql",
"database",
"database-design",
""
] |
The following two queries are returning different results. I understand the difference has to do with the way the time portions of the dates are being handled, but why is it working this way?
```
// QUERY ONE
select top 3 OrderDate
from Orders
where OrderDate >= '2013-11-01 04:00'
and OrderDate <= '2013-11-30 05:00'
o... | [Data type precedence](http://technet.microsoft.com/en-us/library/ms190309.aspx) is taking the data in your table, which starts as a date, and compares it as a datetime2(7). So your dynamic SQL version is actually running this:
```
WHERE column_as_datetime2 >= @parameter_as_datetime2
```
So, since `2013-11-01 00:00:0... | I bet the column `OrderDate` is of type `date`, not `datetime`.
So when you do this
```
where OrderDate >= '2013-11-01 04:00'
```
it converts `'2013-11-01 04:00'` to `date`, not `datetime`, and so it loses the time information. Therefore, the condition in the first query is interpreted as `'2013-11-01 00:00:00' >= '2... | sp_executesql returning different results than direct query | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am refactoring some old oracle sql statements containing plenty of conditions. Some are single conditions put into brackets. Now, does the brackets matter for single conditions? Is there a difference between the two examples below?
example 1
```
WHERE
(
A = B
AND B = C
)
AND ( A > 5 )
AND ( B ... | What about logic: you do need brackets if you have some OR logic, but in this case (only AND) it has no meaning. You can remove all brackets in your query.
And if we'll go deep: look the explain query analyze, you can see that interpreter puts brackets automatically even you missed it. | As far as I know there ain't any semantic differences.
In my experience usually this is either
* a relic of some old condition (maybe an `OR` was in that bracket somewhere in the past) or
* just the style of the dev working in this. | Single SQL conditions in brackets | [
"",
"sql",
""
] |
I have just started with `PL/SQL` and writing a simple fundamental code. I am not getting, what is wrong with the code.
```
DECLARE
role_test varchar(40) := 'Programmer';
BEGIN
update veer_test set project_id=1008420 where role=:role_test;
END;
```
I am getting `ORA-01008: not all variables bound`.
Earlier I tried:
... | Try:
```
DECLARE
role_test varchar(40) := 'Programmer';
BEGIN
update veer_test set project_id=1008420 where role=role_test;
END;
``` | If you want to use the same variable name as your column name, You can try with a procedure like this,
```
CREATE OR REPLACE PROCEDURE role_p(role VARCHAR2)
IS
BEGIN
UPDATE veer_test SET project_id=1008422 WHERE role = role_p.role;
END;
```
To Execute:
```
EXECUTE role_p('Programmer');
``` | Oracle "ORA-01008" Error. Variable Not Bound | [
"",
"sql",
"oracle",
"plsql",
""
] |
Short version: I need to return a query with 3 items from another table and adding it to the existing table.
Long version:
`Table A` contains the following information:
```
| ID | Name | Date | Comment |
--------------------------------
| 1 | AJ | 9/11 | Howdy |
| 2 | AW | 9/13 | Hi |
| 3 | AK ... | Not entirely sure what you are after as you have id's for each comment, then your output has a single row with an id (where does this id come from for your output?) but this may be able to be expanded upon:
```
SELECT
[1] AS COMMENT1,
[2] AS COMMENT2,
[3] AS COMMENT3
FROM
TABLE_A
PIVOT (MAX(COMMENT) FOR id IN ... | Please try this , it helpful to you
```
select b.id, b.comment as comment
, (select comment from ##temp1 where id = b.id+2 ) as comment1
, (select comment from ##temp1 where id = b.id+4 ) as comment2
from ##temp1 b where b.id=1
``` | SQL Server : return 3 items | [
"",
"sql",
"sql-server",
""
] |
```
SELECT * FROM `people` WHERE first_name like 'm%' and last_name like 'm%';
```
- this selects people with with the same first and last name, but that's for `m` only. How to select all such people from a to z (order by desc is not a matter)? | ```
SELECT * FROM `people` WHERE UPPER(LEFT(first_name, 1)) = UPPER(LEFT(last_name, 1))
```
Explanation: takes the leftmost 1 character of first name and of last name, converts them to uppercase, and compares them. | ```
SELECT * FROM people WHERE LEFT(first_name, 1) = LEFT(last_name, 1);
ORDER BY last_name, first_name
``` | mysql: select * where first and last name starts with the same letter | [
"",
"mysql",
"sql",
"select",
"where-clause",
""
] |
Lets say, I have employees, and I know what fruits they like.
```
fruits(name, fruit_name)
```
My question is: list all the employees which at least like the same fruits as Donald.
So how do I compare two set of values?
This is how I get the fruits which Donald likes:
```
Select name, fruit_name
from fruits
where ... | You can use self join to get your desired result-
I have tweaked your query a little to get the output-
```
select distinct e1.name from fruits e1,(Select name, fruit_name
from fruits
where initcap(name) like '%Donald%') e2
where e1.fruit_name = e2.fruit_name;
```
the above query returns employees for whom atleast on... | Two ways to do this:
# Using Collections
I find this gives the most comprehensible SQL but it does require defining a collection type:
```
CREATE TYPE VARCHAR2s_Table AS TABLE OF VARCHAR2(20);
```
Then you can just group everything up into collections and use a self join and `SUBMULTISET OF` to find the other names... | SQL - Compare two sets | [
"",
"sql",
"oracle",
""
] |
It can be needed for inserting and modifying of big amounts of data. | Disable all FKs:
```
EXEC sp_MSforeachtable @command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
GO
```
Enable all FKs:
```
EXEC sp_MSforeachtable @command1="ALTER TABLE ? CHECK CONSTRAINT ALL"
GO
```
Disable all triggers:
```
EXEC sp_MSforeachtable @command1="ALTER TABLE ? DISABLE TRIGGER ALL"
GO
```
Enable all trig... | To disable all FKs in a table:
```
ALTER TABLE Table2 NOCHECK CONSTRAINT ALL
```
To disable a single FK in a table:
```
ALTER TABLE Table2 NOCHECK CONSTRAINT FK_Table2_Table1
```
To enable them replace `NOCHECK` with `CHECK`. | How to turn off/on all the foreign keys and triggers in Microsoft SQL Server? | [
"",
"sql",
"sql-server",
""
] |
I am new in stored procedures.
```
ALTER PROCEDURE [dbo].[SP_MY_STORE_PROCEDURED]
(
@ID INT,
@NAME VARCHAR(50)
)
AS
BEGIN
UPDATE MY_TABLE
SET
WHEN
(( ID ) > 1)
THEN
ID=@ID
,
NAME = @NAME
END
```
I try to use when then for update my **ID** and `Name`
**If Id is greater than 1 i want to update otherwi... | I think this is what you are after:
```
ALTER PROCEDURE [dbo].[SP_MY_STORE_PROCEDURED]
(
@ID INT,
@NAME VARCHAR(50)
)
AS
BEGIN
UPDATE MY_TABLE
SET NAME = @NAME
WHERE ID = @ID
END
```
You do not need to check ID>1 since you are checking the equality with @ID. If you want to be sure that this doesn't happen... | I'm not sure exactly what you're trying to update. Are you trying to change the name on a user record with id = @ID?
```
ALTER PROCEDURE [dbo].[SP_MY_STORE_PROCEDURED]
(
@ID INT,
@NAME VARCHAR(50)
)
AS
BEGIN
UPDATE MY_TABLE
SET Name = @Name
WHERE Id = @ID and @ID > 1
END
``` | Sql Server Stored Procedure Case When in Update | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have a `item_prices` table with prices. Those prices vary at any time.
I want to display all items where date is highest
**ITEM\_prices**
```
id | Items_name | item_price | item_date
------------------------------------------
1 A 10 2012-01-01
2 B 15 2012-01-01
3 ... | when you can use native functions then why to go for any window function or CTE.
```
SELECT t1.*
FROM ITEM_prices t1
JOIN
(
SELECT Items_name,MAX(item_date) AS MaxItemDate
FROM ITEM_prices
GROUP BY Items_name
)t2
ON t1.Items_name=t2.Items_name AND t1.item_date=t2.Max... | One approach would be to use a CTE (Common Table Expression) if you're on SQL Server **2005 and newer** (you aren't specific enough in that regard).
With this CTE, you can partition your data by some criteria - i.e. your `Items_name` - and have SQL Server number all your rows starting at 1 for each of those "partition... | sql server select query a bit complex | [
"",
"sql",
"sql-server",
"select",
""
] |
We currently have a table that logs traffic through our service. We're looking for a way to do some diagnostics/alerts based on the traffic, but find that at 2am we don't have enough traffic to be reliable (1 fail at 2 am can be a 50% failure rate, but at 9am when people work up, 1 fail can be .01%).
We'd like to chec... | Using the last 300 records seems like the easiest thing to do:
```
SELECT top 300 t.*
FROM tbl t
order by date desc;
```
But you can do what you want with a single query:
```
select t.*
from (select t.*, row_number() over (order by date desc) as seqnum
from tbl t
) t
where seqnum <= 300 or Date >= DATEADD... | Not as neat as yours, but:
```
SET @RowCount = SELECT COUNT(*) FROM tbl WHERE Date >= DATEADD(M, -10, GETDATE());
IF @RowCount < 300
BEGIN
SELECT TOP 300 records order by Date Desc
END
ELSE
SELECT records WHERE Date >= DATEADD(M, -10, GETDATE())
END
``` | Query for last 10 minutes if > 300 records OR last 300 records | [
"",
"sql",
"sql-server",
""
] |
I have two tables as follows:
```
CREATE TABLE `keywords_by_city` (
`idKEYWORD` int(11) NOT NULL,
`CITY` varchar(45) NOT NULL);
CREATE TABLE `city` (
`idCITY_NAME` varchar(50) NOT NULL DEFAULT ''
);
```
I want to get a list of all the cities in which idKeyword=781 is not present.
I tried creating the query as... | You were close in your attempt. You just needed to swap the tables and put the keyword ID requirement into the join clause:
```
SELECT cty.`idCITY_NAME`
FROM `city` cty
LEFT JOIN `keywords_by_city` kbc ON cty.`idCITY_NAME` = kbc.`CITY` AND kbc.`idKEYWORD` = 781
WHERE kbc.`idKEYWORD` IS NULL
```
Also, it is standard p... | `t1 LEFT JOIN t2` means t1 table is outer and t2 table is inner of `NESTED LOOP JOIN`
something like this:
```
foreach (row in t1) {
if ((t1.col1 matches t2.col1) OR (t1.col1 doest not match t2.col2)) {
JOIN condition match.
}
}
```
so, your query changed like this:
```
SELECT cty.`idCITY_NAME`
FROM `c... | mySQL - difference between two tables | [
"",
"mysql",
"sql",
""
] |
I'm new to Ruby on Rails. I'm trying to determine the proper ruby query for the following SQL query. The following query works but I'm wondering what the most Railsy way to do this is.
```
@user_urls = Url.find_by_sql(["
select urls.*
from urls
join connections on connections.id = urls.connection_id
join users on u... | You can add an association in the User model:
```
#user.rb
has_many :urls, :through => :connections
@user_urls = @user.urls.where(marked_for_sending: true)
```
Other option:
```
@user_urls = Url.joins(:connection).where(connections: {user: @user}).where(marked_for_sending: true)
``` | You can use `joins` and `where` in rails
```
@user_urls = Url.joins("LEFT JOIN connections ON connections.id = urls.connection_id").joins(" LEFT JOIN users ON users.id = connections.user_id").where("urls.marked_for_sending =? AND users.id = ?", true, @user.id)
``` | Need help converting SQL Query to Ruby. | [
"",
"sql",
"ruby-on-rails",
"ruby",
""
] |
I have a table that has the following structure:
```
Account_No Contact Date
-------------------------
1 2013-10-1
2 2013-9-12
3 2013-10-15
3 2013-8-1
3 2013-8-20
2 2013-10-25
4 2013-9-12
4 ... | You can use DATEADD for the +/-30 days and compare against the time window:
```
DECLARE @ContactDates TABLE (
Account_No int
, Contact Date
)
-- Sample data
INSERT @ContactDates (Account_No, Contact)
VALUES
(1, '2013-10-01')
, (2, '2013-09-12')
, (3, ... | In SQL Server 2012, you would have the `lag()` and `lead()` functions. In 2008, you can do the following for values that are in the same calendar month:
```
select distinct account_no
from t t1
where exists (select 1
from t t2
where t1.account_no = t2.account_no and
date... | T-SQL Finding Accounts With Contact Dates within 30 days | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I created function and want to assign variable result of query:
```
CREATE OR REPLACE FUNCTION GetData
(
OUT outValue integer
)
AS $$
DECLARE
records "Records";
BEGIN
records := (SELECT "Value1" FROM "Records");
outValue := (SELECT sum("Value1") FROM records)
END;
$$ LANGUAGE plpgsql;
```
But, postgresql ... | You can create temporary table inside your function and use it for queries after populating:
```
create or replace function GetData()
returns integer
as $$
declare
outValue int;
begin
create temporary table records(Value1 int);
insert into records
select Value1 from Table1;
outValue := (select su... | If you just want to return a single value why not declare the function as `returns integer` and use something like this:
```
CREATE OR REPLACE FUNCTION GetData()
returns integer
AS $$
SELECT sum("Value1")::integer FROM "Records";
$$ LANGUAGE sql;
```
Btw: I would highly recommend to stop using quoted identifiers ... | How to declare variable with result of query? | [
"",
"sql",
"postgresql",
""
] |
I have 2 tables, `members` and `chat`.
I want to get all member ids which had chat with $user\_id, here we assume $user\_id = '5'
`chat` table is like:
```
id from to message
1 32 12 test
2 25 18 new message
3 5 86 another message
4 53 5 final mess... | The join clause has to contains one field from members and one field from chat. But you may prefer that way to write your query :
```
$q = "
SELECT CASE chat.to WHEN 5 THEN chat.from ELSE chat.to END as the_other_guy
FROM chat
WHERE chat.from = 5 OR chat.to = 5";
```
**EDIT:** Next time, please ask what you REALLY ne... | I think you 're looking for this one:
```
select chat.to from chat where chat.from=5
union
select chat.from from chat where chat.to=5
```
meaning every user\_id that user:5 has chatted with | get all rows matching for same value in 2 different columns | [
"",
"mysql",
"sql",
""
] |
In Oracle, is it possible to have a sub-query within a select statement that returns a column if exactly one row is returned by the sub-query and null if none or more than one row is returned by the sub-query?
Example:
```
SELECT X,
Y,
Z,
(SELECT W FROM TABLE2 WHERE X = TABLE1.X) /* but return null if 0 or more... | How about going about it in a different way? A simple LEFT OUTER JOIN with a subquery should do what you want:
```
SELECT T1.X
,T1.Y
,T1.Z
,T2.W
FROM TABLE1 AS T1
LEFT OUTER JOIN (
SELECT X
,W
FROM TABLE2
GROUP BY X,W
HAVING COUNT(X) = 1
) AS T2 ON T2.X = T1.X;
```
This will only return items... | Besides a `CASE` solution or rewriting the inline subquery as an outer join, this will work, if you can apply an aggregate function (`MIN` or `MAX`) on the `W` column:
```
SELECT X,
Y,
Z,
(SELECT MIN(W) FROM TABLE2 WHERE X = TABLE1.X HAVING COUNT(*) = 1) AS W
FROM TABLE1;
``` | SQL return exactly one row or null in a select sub-query | [
"",
"sql",
"oracle",
"subquery",
""
] |
I have no idea how to do this, and have not found any documentation on it, but I am 99% sure that it can be done. in other words if I have say a 5 col and 5 row table, and the string is in 1:1 and I want it in 5:5, what would the code look like?(I have done this in excel and access that is why I believe it is possible ... | ```
UPDATE TheTable
SET column5=(SELECT column1 FROM TheTable WHERE id=1)
WHERE id=5
``` | Database is not Excel, you cannot select value directly based on columnNo, rowNo. What's the use case for it, anyway?
PS. It can be done by some circus tricks and dynamic queries like described in <http://forums.mysql.com/read.php?10,286477,286489#msg-286489>, but I don't think it's worth the effort. You should consid... | How do I move a string from a specific column and row to a different column and row? | [
"",
"mysql",
"sql",
""
] |
I want to be able to update a table of the same schema using a "replace into" statement. In the end, I need to be able to update a large table with values that may have changed.
Here is the query I am using to start off:
```
REPLACE INTO table_name
(visual, inspection_status, inspector_name, gelpak_name, gelpak_locat... | As the [documentation](http://dev.mysql.com/doc/refman/5.0/en/replace.html) says:
> REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. | `REPLACE` does work much like an `INSERT` that just overwrites records that have the same `PRIMARY KEY` or `UNIQUE` index, however, beware.
Shlomi Noach writes about the problem with using `REPLACE INTO` [here](http://code.openark.org/blog/mysql/replace-into-think-twice):
> But weak hearted people as myself should be... | Replace Into Query Syntax | [
"",
"mysql",
"sql",
"database",
"replace",
""
] |
I'm on a query.
```
SELECT ttf.default_text
FROM test_template_field ttf, TEST t
WHERE ttf.schema_field_id = 2044
--HERE
AND ttf.test_template_id = t.test_template_id
AND t.workflow_node_id IN (
SELECT wn.workflow_node_id
FROM lims_sys.workflow_node wn, lims_sys.workflow_user wu
... | * Use [DBMS\_STATS](http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_stats.htm) to update the table statistics that Oracle uses to decide the execution plan
* If this doesn't help, you can use [optimizer hints](http://docs.oracle.com/cd/B19306_01/server.102/b14211/hintsref.htm) in the query to kick the query opt... | Check if you have got indexses on
test\_template\_field.schema\_field\_id,
test\_template\_field.test\_template\_id,
test.test\_template\_id,
lims\_sys.workflow\_node.workflow\_id,
wu.u\_external\_category,
wn.workflow\_node\_type\_id
Also try this query
```
SELECT ttf.default_text
FROM test_template_field ttf
J... | Oracle SELECT statement slow | [
"",
"sql",
"oracle",
"select",
""
] |
```
Delete From StudentTb Where StudentType in (1, 2) and StudentI not in
(
Select lg.StudentI From StudentLog lg
)
```
I tried to changed the above code to the following... But, I am not sure if it is correct or not.
```
Delete From StudentTb Where StudentType in (1, 2)
and Not Exists
(
Select ... | Not in and not exists do not always have the same meaning. I assume you want to convert because "not in" tends to be slow. Here is another way where the logic will always match.
```
Delete From StudentTb
Where StudentType in (1, 2)
and StudentI in
(
select StudentI
from StudentTb
except
Select StudentI From Student... | ```
Delete From StudentTb s
Where StudentType in (1, 2)
and Not Exists
(
Select *
From StudentLog
Where StudentI = s.StudentI
)
```
In a subquery, unqualified references to columns(which do not specify table name or alias) are first assumed to be in the table referenced in the ... | SQL, how do I convert to logic ('not in' to 'not exists') | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am trying to insert data into a SQL Server database by calling a stored procedure, but I am getting the error
> Procedure or function 'SHOWuser' expects parameter '@userID', which was not supplied.
My stored procedure is called `SHOWuser`. I have checked it thoroughly and no parameters is missing.
My code is:
```... | Your stored procedure expects 5 parameters as input
```
@userID int,
@userName varchar(50),
@password nvarchar(50),
@emailAddress nvarchar(50),
@preferenceName varchar(20)
```
So you should add all 5 parameters to this SP call:
```
cmd.CommandText = "SHOWuser";
cmd.Parameters.AddWithValue("@userID",userI... | In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :
```
cmd.CommandType = System.Data.CommandType.StoredProcedure;
```
This is obviously not the case in the question above, but exception description is not very clear in this case, so ... | Stored procedure or function expects parameter which is not supplied | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
My Situation:
I have an Employee field which I am getting through a SharePoint list.
The current value I am getting is this:
`EmployeeID;Employee Firstname Employee Lastname`
Say for example:
`43;Stacky Stackerflow`
What I Need is either the ID alone without the `;` or the First and Lastname,
but I have no way of ... | This is a Copy and paste from my answer here :[Split a single column of data with comma delimiters into multiple columns in SSIS](https://stackoverflow.com/questions/19653995/split-a-single-column-of-data-with-comma-delimiters-into-multiple-columns-in-ssi/19654637#19654637)
You can use the [Token](http://technet.micro... | Because this is tagged SQL, I'll answer using that syntax:
```
select left(Employee, charindex(';', Employee) - 1)
```
If you want this as an integer, then use:
```
select (case when isnumeric(left(Employee, charindex(';', Employee) - 1)) = 1
then cast(left(Employee, charindex(';', Employee) - 1) as int... | SSIS: Trim field for specific part of string | [
"",
"sql",
"string",
"sharepoint",
"ssis",
"expression",
""
] |
I have following two tables, one table is of person and another table is for storing various dynamic properties/information about the person.
```
Id | Persons PersonId | Field | Value
----+------------- ----------+--------+-----------
1 | Peter 1 | City | New... | ```
SELECT key1.PersonId
FROM KeyValue key1
INNER JOIN KeyValue key2 ON key1.PersonId = key2.PersonId
WHERE key1.[Field] = 'Age' and key1.[Value] > 25
AND key2.[Field] = 'City' and key2.[Value] = 'New York'
```
**Update**
I did some tests and INNER JOIN looks fast enough. Here result and test script
```
SET... | You can use the following structure:
```
select PersonId from
(
select PersonId from xxx where [Field] = 'Age' and [Value] > 25
union all
select PersonId from xxx where [Field] = 'City' and [Value] = 'New York'
) x
group by PersonId
having count(*) = 2
```
You can create one more query for the union for ... | Apply search criteria on dynamic field table without using grouping or pivoting | [
"",
"sql",
"sql-server",
""
] |
I want to move 1 million rows of data to another table. Im using query:
```
insert into Table1
select * from Table2;
```
in my PL/SQL function. But this way is too slow.
How can I do this with **Bulk Insert** method?
* Source and destination table has same structure.
* Tables have hash partition and 1 index. | Forget about bulk insert. Because the insert into select is the best bulk you can load.
The fastest would be to disable the indexes (mark them unusable) and do this in a SINGLE
insert:
```
insert /*+ append */ into TARGET
select COLS
from SOURCE;
commit;
```
and rebuild the indexes using UNRECOVERABLE (and maybe e... | USING Bulk Collect
Converting to collections and bulk processing can increase the volume and complexity of your code. If you need a serious boost in performance, however, that increase is well-justified.
Collections, an evolution of PL/SQL tables that allows us to manipulate many variables at once, as a unit. Collect... | Move large data between tables in oracle with bulk insert | [
"",
"sql",
"oracle",
"plsql",
"oracle11g",
"bulkinsert",
""
] |
I'm thinking about a SQL query that returns me all entries from a column whose first 5 characters match. Any ideas?
I'm thinking about entries where ANY first 5 characters match, not specific ones. E.g.
```
HelloA
HelloB
ThereC
ThereD
Something
```
would return the first four entries:
```
HelloA
HelloB
ThereC
ThereD... | Try this :
```
SELECT *
FROM YourTable
WHERE LEFT(stringColumn, 5) IN (
SELECT LEFT(stringColumn, 5)
FROM YOURTABLE
GROUP BY LEFT(stringColumn, 5)
HAVING COUNT(*) > 1
)
```
`SQLFIDDLE DEMO`
This selects the first 5 characters, groups by them and returns only the ones that happen more than once.
... | Sounds easy enough...
In SQL Server this would be something along the lines of
```
where Left(ColumnName,5) = '12345'
``` | Pattern matching SQL on first 5 characters | [
"",
"sql",
"pattern-matching",
"ansi-sql-92",
""
] |
I have this table:
```
CREATE TABLE [dbo].[Fruit](
[RecId] [int] IDENTITY(1,1) NOT NULL,
[Banana] [int] NULL,
[TextValue] [varchar](50) NULL
)
```
And the following piece of code:
```
DECLARE @FruitInput INT = NULL
SELECT * FROM Fruit WHERE Banana = @FruitInput
```
This record is in that table:
```
1|N... | It is because `Null is undefined`. Null neither equal nor not equal to anything. Please read more on **[MSDN](http://technet.microsoft.com/en-us/library/ms191504%28v=sql.105%29.aspx)**.
Null values can be checked with `is null` (or `is not null`), or `isnull()` *or* `coalesce()` functions depending on the requirement.... | NULL does not equal NULL, use IS NULL for null row checks:
`SELECT * FROM Fruit WHERE Banana IS NULL`
In this case because you have NULL in a variable, you can use the ISNULL operator:
`SELECT * FROM Fruit WHERE ISNULL(Banana, 0) = ISNULL(@FruitInput, 0)`
This will ensure you can check against whatever value NULL i... | Where is my banana? (SQL Query NULL issue) | [
"",
"sql",
"sql-server",
"null",
""
] |
I just found out a SQL Server bug (described [here](https://stackoverflow.com/questions/19819139/merge-into-throws-foreign-key-conflict)). Now I am wondering, if there is any possibility of forcing an `INSERT` statement without performing foreign key checks? Like disabling this checks server-wide for few minutes, or so... | **Drop Constraint**
```
ALTER TABLE Table_Name
DROP CONSTRAINT fk_ConstraintName
```
Drop the constraint once you have done the operation then create it again.
**Disable Constraint**
```
ALTER TABLE MyTable
NOCHECK CONSTRAINT fk_Constraint_Name
```
**Enable Constraint**
```
ALTER TABLE MyTable
CHECK CONSTRAINT ... | ```
ALTER TABLE [schema].[table] NOCHECK CONSTRAINT [constraint_name]
```
Then
```
ALTER TABLE [schema].[table] CHECK CONSTRAINT [constraint_name]
```
However, this results in your FK being not trusted, and when you re-enable the constraint it will take time to re-validate it. | Is there a way of forcing sql INSERT or disabling foreign key check? | [
"",
"sql",
"sql-server",
""
] |
I have an equation stored in my table. I am fetching one equation at a time and want to replace all the operators with any other character.
**Input String:** `(N_100-(6858)*(6858)*N_100/0_2)%N_35`
**Operators or patterns:** `(+, -, *, /, %, (, ))`
**Replacement character:** `~`
**Output String:** `~N_100~~6858~~~68... | I had created a `SPLIT` function to implement this because I need to implement this operation multiple time in `PROCEDURE`
**SPLIT FUNCTION**
```
create function [dbo].[Split](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @id... | I believe it is easier and more readable if you use a table to drive this.
```
declare @String varchar(max) = '(N_100-(6858)*(6858)*N_100/0_2)%N_35'
--table containing values to be replaced
create table #Replace
(
StringToReplace varchar(100) not null primary key clustered
,ReplacementString varchar(100) not... | Replace multiple characters from string without using any nested replace functions | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"replace",
""
] |
This cross join works fine:
```
select * from x, y
```
I am trying to run this query:
```
select abc.col1 from abc
(select * from x, y) abc
```
But I get this error message:
```
Msg 8156, Level 16, State 1, Line 2
The column 'col1' was specified multiple times for 'abc'.
```
Both tables x and y have the same colu... | ```
select abc.col1 from abc
(select * from x, y) abc
```
You are aliasing two tables with the same name. Try:
```
select abc.col1 from abc,
(select x.* from x, y) abc2
``` | you have to specify column name in inner query section.
something like this:
```
select abc.col1 from abc
(select x.col1,y.col1 from x, y) abc
``` | SQL Cross Join Query not working with variable | [
"",
"sql",
"sql-server",
"variables",
"cross-join",
""
] |
Can someone explain to me why when I perform a `LIKE` select in SQL (T-SQL) on a `varchar` column I can do the following:
```
SELECT *
FROM Table
WHERE Name LIKE 'Th%'
```
to get names beginning with `Th`, but when I do the same on a `datetime` column I need a `%` before the year, like:
```
SELECT *
FROM Table... | The DATETIME is converted to a VARCHAR before the comparison, and there definitely is no guarantee that the conversion will be in the pattern you mention. DATETIME is not stored internally as a VARCHAR but as a FLOAT. | You should stop wondering because the syntax is not useful.
```
SELECT *
FROM Table
WHERE Date LIKE '%2013%'
```
Will give you a full table scan because the date will be converted to a varchar when comparing. In other words, don't do it !
Use this syntax instead:
```
SELECT *
FROM Table
WHERE Date >= '2013-01-01T00... | SQL datetime LIKE select - why do I need an extra %? | [
"",
"sql",
"t-sql",
"datetime",
""
] |
I've read dozens of answers regarding CASE and am not sure that is what i need to be using here, it seems like it should work but its not:
```
Data:
OrderNum OrderLine PartNum
200011 1 ABC-1
200011 2 DEF-1
200012 1 XYZ-1
What I would like to return:
OrderNum Item#... | Try with grouping like
```
SELECT OrderHed.OrderNum,
(CASE WHEN SUM(ShipDtl.OrderLine) > 1 then 'MIXED' else MAX(ShipDtl.PartNum) end) as [Item#]
FROM dbo.OrderHed, dbo.ShipDtl
WHERE ShipDtl.Company = OrderHed.Company
AND ShipDtl.OrderNum = OrderHed.OrderNum
GROUP BY OrderHed.OrderNum
```
SQLFiddle Demo : <ht... | You didn't write which database engine you use, but if it is SQL 2005 and above, I'd think using the window function for COUNT will make things easier as you then do not need to group.
```
SELECT DISTINCT
OrderHed.OrderNum ,
CASE
WHEN COUNT(ShipDtl.OrderLine) OVER (PARTITION BY ShipDtl.Or... | SQL CASE WHEN to narrow results, change field | [
"",
"sql",
"case-when",
""
] |
I'm writing a stored procedure that looks something like this:
```
SELECT
Positions.PositionId
,Positions.Title
,Positions.Location
,Positions.Description
,Positions.MaximumSalary
,PositionsDepartments.Description Department
,PositionsSubDepartments.Description Subdepartment
,Positions... | You need to use a left join when an entry could be null
```
SELECT
Positions.[PositionId]
,Positions.[Title]
,Positions.[Location]
,Positions.[Description]
,Positions.[MaximumSalary]
,PositionsDepartments.[Description] Department
,PositionsSubDepartments.[Description] Subdepartment
,Pos... | ```
select Positions.PositionId, Positions.Title, Positions.Location,Positions.Description,Positions.MaximumSalary,
PositionsDepartments.Description Department, PositionsSubDepartments.Description Subdepartment, PositionsDepartments.DepartmentId DepartmentId, PositionsSubDepartments.SubDepartmentId SubdepartmentId,
@Th... | SQL if statement for null values in INNER JOINs | [
"",
"mysql",
"sql",
""
] |
So here's what my data table looks like:
```
TeamNum Round Points1 Points2
1 1 5 21
2 1 10 20
3 1 9 29
1 2 6 22
2 2 11 21
3 2 10 30
1 3 80 50
```
I also have a second table with ... | Use conditional aggregation
```
SELECT t.teamnumber, t.teamname,
SUM(CASE WHEN d.round = 1 THEN d.points1 + d.points2 ELSE 0 END) round1,
SUM(CASE WHEN d.round = 2 THEN d.points1 + d.points2 ELSE 0 END) round2,
SUM(CASE WHEN d.round = 3 THEN d.points1 + d.points2 ELSE 0 END) round3
FROM data d J... | No need to aggregate:
```
SELECT
t.teamnumber,
COALESCE(r1.points1 + r1.points2, 0) AS round1,
COALESCE(r2.points1 + r2.points2, 0) AS round2,
COALESCE(r3.points1 + r3.points2, 0) AS round3,
t.teamname
FROM teams t
LEFT JOIN data r1 ON r1.teamnumber = t.teamnumber AND r1.round = 1
LEFT JOIN data r2... | SQL consolidate data and turn them into columns | [
"",
"mysql",
"sql",
"database",
""
] |
What I've attempted and which returns incorrect data:
```
SELECT type, pid, MAX(distance) FROM table GROUP BY type
```
This retrieves every unique `type` and the correct corresponding maximum `distance` for each `type` from my database (there are a total of 26 different unique `type` values and this will never change... | This query gives the desired result.
```
SELECT t.type, t.pid, t.distance
FROM table t
INNER JOIN (SELECT type, MAX(distance) as distance FROM table GROUP BY type) as m
ON t.type = m.type and t.distance = m.distance
ORDER BY t.type
```
It will return all pid that have the same maximum distance for the ( not very prob... | You can do a `GROUP BY` query, them join it to the original table to get the right `pid`, like this:
```
SELECT x.type, t.pid, x.max_dist
FROM (
SELECT type, MAX(distance) as max_dist FROM table GROUP BY type
) as x
JOIN table t ON x.max_dist=t.distance AND x.type=t.type
```
[Demo on sqlfiddle](http://www.sqlfidd... | Retrieving Maximum Of One Column For Each Unique Value From Another | [
"",
"mysql",
"sql",
""
] |

I have a table in database which is already has the data, but now I added new column called `Vol_Age` and it has `NULL` value. I want that column filled by calculating Age, the data comes from `Vol_Date_of_Birth` column, I need a query that calculate... | Keep in mind that since you added the column to the database, any values within that column will retain their value. As time goes on, you will need to keep updateding the values within the database.
Another approach would be to remove the column and make it a computed column instead. This way, the age is caculated at ... | Try using the DateDiff function:
```
SELECT DATEDIFF(year,GETDATE(),Vol_Age)
``` | Calculate the age and Insert it to an already column via SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
"sql-server-2012",
""
] |
I have run into a problem when I have tried to select data from more than 1 table and I was wondering if anyone could help me. The tables are linked and I'm trying to select only things with a certain id. I have had success with queries with 1 table but with 2 tables it kicked an error my way:
> Query to get data from... | Does Recipe\_ID appear in both Recipe and Ingredients\_Needed?
IF it does then you need to do something like this:
```
SELECT * FROM Recipe, Ingredients_Needed WHERE Recipe.Recipe_ID = ....
```
As a side note, use correct join syntax not an implicit join ie:
```
SELECT r.*, n.*
FROM Recipe r
INNER JOIN Ingredients_... | Specify the table:
```
WHERE table.Recipe_ID=
``` | where clause is ambiguous | [
"",
"mysql",
"sql",
""
] |
I have a query against a large number of big tables (rows and columns) with a number of joins, however one of tables has some duplicate rows of data causing issues for my query. Since this is a read only realtime feed from another department I can't fix that data, however I am trying to prevent issues in my query from ... | Turns out I was doing it wrong, I needed to perform a nested select first of just the important columns, and do a distinct select off that to prevent trash columns of 'unique' data from corrupting my good data. The following appears to have resolved the issue... but I will try on the full dataset later.
```
SELECT DIS... | `distinct` is **not** a function. It always operates on *all* columns of the select list.
Your problem is a typical "greatest N per group" problem which can easily be solved using a window function:
```
select ...
from (
select IDNo,
FirstName,
LastName,
....,
row_number() over (... | SQL Left Join first match only | [
"",
"sql",
"sql-server",
"t-sql",
"join",
"greatest-n-per-group",
""
] |
I am using MIN function in mysql to return the smallest value of a column - lets call it price, however i also wish to display various other columns for this particular row with the smallest value for price. So far i have the following:
```
SELECT underlying,volatility FROM shares
where (id,price) IN (
SELECT id,M... | i think i have solved the problem, it takes a while to execute so i will start by adding a new index :
```
SELECT underlying,volatility,price FROM shares
where (id,price) IN (
SELECT id,MIN(price) FROM shares
where DATE(issueDate) >= DATE(NOW())
group by id
) order by price asc limit 1;
``` | Having clause will do the trick, please check my solution
```
select volatility,underlying, min(price) as min_price from shares
where DATE(issueDate) >= DATE(NOW())
group by issueDate
having min_price = min(price);
```
[fiddle example](http://sqlfiddle.com/#!2/3b5ae/3) | I can't get mysql to return last row when using the aggregate MIN | [
"",
"mysql",
"sql",
"greatest-n-per-group",
""
] |
I checked this question asked before
[How to add Sysadmin login to SQL Server?](https://stackoverflow.com/questions/14814798/how-to-add-sysadmin-login-to-sql-server)
I tried all the solutions mentioned but I don't have the same options
this is the output for the first solution
 VALUES ('1','Phone call: 1.80','1.8');
```
in Oracle SQL Developer. Ive had it running but when I close it, then reopen it I get this error:
```
Error starting at line 1 in command:
INSERT INTO BOOKING_EXTRAS (BOOKING_ID, EXTRAS_, EXTRA... | You need to either clear the tables or insert new information, a database doesn't want duplicate rows because that makes it impossible to find the correct rows later. | In addition, if that **BOOKING\_ID** (currently serves as primary key if I guess right) doesn't actually mean something for you, you can set it as AUTO INCREMENT in your schema, then afterwards you don't need to insert a value for BOOKING\_ID, the system will automatically find a value which is not duplicate for you. T... | Insert statement attempted to include a duplicate key | [
"",
"sql",
"database",
"oracle",
"syntax",
"syntax-error",
""
] |
I have this query:
```
SELECT p.[PostingID]
,[EmployerID]
,[JobTitle]
,pin.[IndustryID]
FROM [Posting] p
INNER JOIN [City] c
ON p.CityID = c.CityID
LEFT OUTER JOIN PostingIndustry pin
ON p.PostingID = pin.PostingID
WHERE (c.CityID = @CityId OR @CityId IS NULL)
AND (p... | What about selecting only the row with the smallest IndustryId:
```
SELECT [PostingID]
,[EmployerID]
,[JobTitle]
,MIN(pin.[IndustryID])
FROM [Posting] p
INNER JOIN [City] c
ON p.CityID = c.CityID
LEFT OUTER JOIN PostingIndustry pin
ON p.PostingID = pin.PostingID
WHERE (... | Try using a group by clause at the end
Use `MAX(IndustryId)`.
Then also
```
GROUP BY PostingId,EmployerId,Jobtitle
``` | SQL query select only one row from multiple rows | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I'm trying to get all participants that have more than 1 record in the table where at lease one of those records has IsCurrent = 0 and IsActive = 1
This is what I have so far, but it's not working:
```
SELECT ParticipantId
FROM Contact
WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
Gro... | You can use [EXISTS](http://technet.microsoft.com/en-us/library/ms188336.aspx):
```
SELECT ParticipantId
FROM Contact
WHERE EXISTS
( SELECT 1
FROM Contact c2
WHERE c2.ParticipantID = c.ParticipantId
AND ContactTypeId = 1
GROUP BY ParticipantID
... | Use it as a subquery and join to it:
```
select * from
(
SELECT ParticipantId
FROM Contact
WHERE (IsCurrent = 0 AND IsActive = 1 AND ContactTypeId = 1)
Group by ParticipantId
Having COUNT(ParticipantId) > 1
) base
inner join Contact c on c.ParticipantId = base.ParticipantID
WHERE (IsCurrent = 0 ... | sql select records having count > 1 where at lease one record has value | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table in this form (this is just the partial view, the table contains more than 100 columns).
```
LOAN NUMBER DOCUMENT_TYPE DOCUMENT_ID
992452533663 Voters ID XPD0355636
992452533663 Pan card CHXPS5522D
992452533663 Drivers licence DL... | If you are using Oracle 10g, you can use the `DECODE` function to pivot the rows into columns:
```
CREATE TABLE doc_tab (
loan_number VARCHAR2(20),
document_type VARCHAR2(20),
document_id VARCHAR2(20)
);
INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533... | You can do it with a [`pivot` query](http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html), like this:
```
select * from (
select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
from my_table t
)
pivot
(
MIN(DOCUMENT_ID)
for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)
```
Here i... | How to convert Rows to Columns in Oracle? | [
"",
"sql",
"oracle",
"pivot",
""
] |
I need to output 3 null columns in my SQL statement, i'm using SQL developer Oracle 11g
For example:
```
SELECT
c.CID,
c.CName,
null,
null,
null,
r.RegionID,
r.RegionName
FROM
Regions r
INNER JOIN Branch b ON b.RegionID = r.RegionID
INNER JOIN Countries c ON c.CID = b.CID;
```
So in the scri... | Well, you can do it just the way you presented...:
```
SELECT
c.CID,
c.CName,
CAST(null AS VARCHAR2(1)) AS Continent,
null AS hemisphere,
null AS something,
r.RegionID,
r.RegionName
FROM
Regions r
INNER JOIN Branch b ON b.RegionID = r.RegionID
INNER JOIN Countries c ON c.CID = b.CID;
``` | Actually, that should work.
```
SELECT
c.CID,
c.CName,
null AS country,
null AS Region,
null AS hemisphere,
r.RegionID,
r.RegionName
FROM
Regions r
INNER JOIN Branch b ON b.RegionID = r.RegionID
INNER JOIN Countries c ON c.CID = b.CID;
-- Or, if you don't have any tables yet:
SELECT
NULL AS... | Selecting null columns for script output in SQL Developer | [
"",
"sql",
"database",
"oracle11g",
""
] |
I have a problem with the following SQL. Why on the earth minus of 2 exactly same queries would return non-empty result? I have tried "UNION ALL" instead of UNION, I have tried many other things, none of which worked. PLease advise.
```
SELECT y.segment1 po_num, fad.seq_num seq, fdst.short_text st
FR... | Use parentheses. Right now, you're doing `((set1 UNION set2) MINUS set1) UNION set2` while you meant to do `(set1 UNION set2) MINUS (set1 UNION set2)`.
In other words, you're uniting set1 and set2, removing set1 from that and uniting set2 with that, while you probably meant to take a union of set1 and set2 and remove ... | The problem is that, firstly, you do a UNION of the first two queries, then, you do a MINUS of the third and then you UNION the result with the fourth query. | Minus (except) of 2 same queries return non-empty resultset | [
"",
"sql",
"oracle",
"except",
""
] |
I'm using sqlcmd to export a query result with two columns to csv. The simple query is:
```
SELECT DISTINCT
CustomerGuid, CustomerPassword
FROM
ServiceOrder
ORDER BY
CustomerGuid
```
When I open the exported csv in Excel both customer and password are on the same column. Is it possible to split them into ... | The problem is that you are using `,` instead of `;` as the line delimiter. Try:
`SQLCMD -S . -d BAS -Q "SQL STATEMENT" -s ";" -o "c:\data.csv"`
:) | Actually, this is more of an Excel question and it's already answered in [superuser](https://superuser.com/questions/291445/how-do-you-change-default-delimiter-in-the-text-import-in-excel). The default separator when you open a CSV file is locale dependent. In locales where `,` is a decimal separator, the default is `;... | Export SQL query result to CSV | [
"",
"sql",
"sql-server",
"excel",
"sqlcmd",
""
] |
Using Postgresql 9.2
What select statement would be used to find all `numeric` results that end with `.00`
Say, from this example:
```
Trans Amt
|-------|
-57059.44
-239.00
-100.61
-181.33
-100.00
```
I would only want to see the `-100.00` and `-239.00` | Try
`SELECT * from TABLE where TRANS_AMT = floor(TRANS_AMT);` | May be
```
select * from Table1 where TransAmt = TransAmt::int
```
**`sql fiddle demo`** | Using Regular expressions with Numeric value | [
"",
"sql",
"postgresql",
""
] |
i have created the next db file -
```
String sql = ""
+ "CREATE TABLE "+ Constants.TABLE_NAME + " ("
+ Constants.NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Constants.NAME_PERSON + " TEXT"
+ ")";
db.execSQL(sql);
```
Now what I would lik... | you can add this in your DB and call the function passing "to be searched key" as an argument
```
public boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_INFO, new String[] { KEY_TITLE}, KEY_TITLE + "=?",
new String[... | Take more example on this:
[AndroidSQLite](http://www.vogella.com/articles/AndroidSQLite/article.html)
[AndroidSQLite with multi tables](http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/) | how to check if a value already exist in db, and if so how to get the id of that row? android sql | [
"",
"android",
"sql",
"database",
""
] |
I've got a one-to-many relationship with these two tables:
```
p2c {
parent_id,
child_id
}
child {
child_id, -- pk
count1,
count2
}
```
If I do this:
```
select distinct parent_id from p2c
join child on p2c.child_id = child.child_id
where count1 = count2
```
I get the parents where one of the ... | You can use GROUP BY/HAVING as follows:
```
select parent_id
from p2c
join child on p2c.child_id = child.child_id
group by parent_id
having count(case when count1 = count2 then 1 end) = count(*);
```
This basically counts rows where `count1 = count2` and only returns `parent_id`s where this count is the... | Use a derived table first , to get the count of rows and rows where they match:
```
select
*
from
pc2
join
(
select
child_id,
count1,
count2,
count(child_id) as NUM_ROWS,
count(case when count1 = count2 then 1 else null) as NUM_MATCHES
from child
group by child_Id
... | One to many relationship needs all of the many records to match a condition | [
"",
"sql",
""
] |
I'm trying to compile the stored procedure:
```
create
procedure checkFroud2(code IN varchar2, p_recordset OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_recordset FOR
if code='C' then
select * from emp
//dbms_output.putline('this is if block')
else if code='F' then
dbms_output.putline('this is else block')
else
dbms_output.pu... | ```
CREATE
PROCEDURE checkFroud2(
code IN VARCHAR2,
p_recordset OUT SYS_REFCURSOR)
AS
BEGIN
IF code='C' THEN
dbms_output.put_line('this is if block');
OPEN p_recordset FOR
SELECT * FROM emp;
ELSIF code='F' THEN
--you can open p_recordset with dummy as
/*op... | ```
The correct code is as follows:
create procedure checkFroud2(code IN varchar2, p_recordset OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_recordset FOR
if code='C' then
select * from emp
//dbms_output.putline('this is if block');
elsif code='F' then
dbms_output.putline('this is else block');
else
dbms_output.putline('last e... | IF else condition in sql stored procedure | [
"",
"sql",
"oracle",
""
] |
I have three entities:
Cue(id, name)
Reaction(id, name)
Freqs(id, cue\_id FK, reaction\_id FK, some\_other\_data)
I want to count number of (cue, reaction) pairs like (cue.name, reaction.name, count)
I already wrote a query
```
SELECT
a.cue_id,
a.reaction_id,
Count(*) as freq
FROM
rdb_freqs a
JOIN rdb_re... | ```
SELECT distinct
c.name cue_name,
b.name reaction_name,
(SELECT
Count(*)
FROM
rdb_freqs a1
where
a1.cue_id = a.cue_id and
a1.reaction_id = a.reaction_id
) as count
FROM
rdb_freqs a
inner JOIN rdb_reaction b ON a.reaction_id = b.id
inner JOIN rdb_cue c ON a.cue_id = c.id
order by c... | ```
SELECT
c.name as cue_name,
b.name as reacion_name,
Count(*) as freq
FROM
rdb_freqs a
JOIN rdb_reaction b ON a.cue_id=b.id
JOIN rdb_cue c ON a.reaction_id=c.id
GROUP BY c.name, b.name
ORDER BY freq DESC;
``` | Select from Many-to-Many with GroupBy | [
"",
"sql",
"postgresql",
"many-to-many",
""
] |
Good Day,
So I'm stuck with a SQL query in which the table I'm querying has multiple sequential columns, such as
```
Property1,
Property2,
Property3,
Property4,
Property5
..etc
```
Now there are about 64 columns descending in the same naming convention.
They are varchar of type and marked by a single "Y" or "N" stat... | Try this:
```
select
CASE WHEN QryGroup1 = 'Y' then 'QryGroup1'
WHEN QryGroup2 = 'Y' then 'QryGroup2'
WHEN QryGroup3 = 'Y' then 'QryGroup3'
WHEN QryGroup10 = 'Y' then 'QryGroup10'
else ''
end as [SelectedBP]
from OCRD
``` | The basic idea is to concatenate all fields in one string and then find the index of the first occurrence of `Y` and form a field label as `PROPERTY`+`FIRST OCCURRENCE INDEX`.
If `Y` is not found then `PROPERTY0` appears in this query you can handle this with CASE statement for example.
[SQLFiddle demo](http://sqlfidd... | SQL Select the first Column to match criteria of Many columns in a single row | [
"",
"sql",
"sql-server",
"sql-server-2008",
"multiple-columns",
""
] |
i have the following query for inserting values into my Customer table:
```
INSERT INTO customer(Booking_id,First_name,Last_name,Phone,Address,Town,Postcode,email)
VAlUES
(1,'Elroy','Craddock',01497 3139773','36 Yaffingale Gate','Tadley','RG78 2AB','e.craddock@yautia.co.uk')
```
after running it writes
```
Error st... | This is your query:
```
INSERT INTO customer (Booking_id, First_name, Last_name, Phone, Address, Town, Post code, email) VALUES( 1551 ,' Leonard ',' Babbs ', 01959 8159688 ,' 46 Zoophagy Green ',' Choppington ',' NE41 5DB ',' l.babbs@sommelier.co.uk ')
```
Your problem is here: `01959 8159688`. This... | The problem is with `01959 8159688`.
Assuming this is a phone number, and you want to keep the space in order to separate the area code from the rest of the number, you should surround it with single quotes: `'01959 8159688'` - otherwise, it's interpreted as two unrelated numeric literals. | Need help finding syntax in SQL developer | [
"",
"sql",
"database",
"oracle",
"syntax-error",
""
] |
I am trying to insert new information into an already existing table. This is my code which is not working:
```
INSERT INTO customer (cNo, cName, street, city, county, discount)
VALUES (10, Tom, Long Street, Short city, Wide County, 2);
```
Where am I going wwrong? | You are not specifying your strings properly it should be:
```
INSERT INTO customer (cNo, cName, street, city, county, discount)
VALUES (10, 'Tom', 'Long Street', 'Short city', 'Wide County', 2);
``` | You must use quotes for string values:
```
INSERT INTO customer (cNo, cName, street, city, county, discount)
VALUES (10, 'Tom', 'Long Street', 'Short city', 'Wide County', 2);
``` | Inserting information into a table on SQL | [
"",
"sql",
"ms-access",
""
] |
If I have table t like this:
```
id date_from date_to n_n n_d i_s ...
591 2014-04-26 2014-05-03 1 NULL 1 ...
595 2014-04-26 2014-05-03 1 NULL 1 ...
```
And I have a query like this:
```
SELECT id
FROM t
WHERE ROW(date_from, date_to, n_n, n_d, i_s) =
(SELECT date_... | That is because of `NULL` comparison. Normally, `NULL` can't be handled with usual equality comparison operators. There are such things as `IS NULL` for it. But in your case, use [<=>](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to) for your query to get proper results:
```
SELECT i... | It does not work because one column contains `null`. That compare results in `unknown` which is `false`. That is why you don't get a result. | Row query for finding ids of similar rows | [
"",
"mysql",
"sql",
""
] |
```
create Table dealing_record(
dealing_record_id int NOT NULL,
Transaction_number Varchar (6) NOT NULL UNIQUE,
Number_of_shares Number NOT NULL,
Amount Number (7,2) NOT NULL,
Stamp_duty Varchar(6) NOT NULL,
commission Varchar(6) NOT NULL,
Date_time SYSDATE NOT NULL,
PRIMARY KEY(dealing_record_id));
```
outcome
... | This line:
```
Date_time SYSDATE NOT NULL,
```
should be
```
Date_time date NOT NULL default SYSDATE,
```
Sysdate is a value, not a datatype. | `SYSDATE` is not a data type. You probably mean
```
Date_time DATE NOT NULL,
``` | issues with sysdate in sqlplus | [
"",
"sql",
"sqlplus",
""
] |
I have a working query that is grouping data by hardware model and a result, but the problem is there are many *"results"*. I have tried to reduce that down to *"if result = 0 then keep as 0, else set it to 1"*. This generally works, but I end up having:
```
day | name | type | case | count
---------... | Your query would work already - except that you are running into naming conflicts or just confusing the **output column** (the `CASE` expression) with **source column** `result`, which has different content.
```
...
GROUP BY model.name, attempt.type, attempt.result
...
```
You need to `GROUP BY` your `CASE` expressio... | can you please try this:
replace the case statement with the below one
```
Sum(CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END) as Count,
``` | GROUP BY + CASE statement | [
"",
"sql",
"postgresql",
"group-by",
"case",
"aggregate-functions",
""
] |
So this is my current situation.
I have a Table 'Test' with following attributes:
* Id
* PatientID (FK)
* Result
* Type
I need to count how many patients have done a test from a specific type (it's a 1 - \* relationship between Patient and Test).
I solved it like this:
```
SELECT COUNT(*)
FROM Test
WHERE (Type =... | Answering your question:
> I need to Count how many How many patients have done a test from a
> specific type (it's a 1 - \* relationship between Patient and Test).
This is the solution:
```
SELECT COUNT(DISTINCT PatientID) FROM Test WHERE Type = 'GDS'
```
For example, if you have:
```
ID | PatiantID | Type
1 | 7... | Is this homework?
You are searching for the [HAVING](http://www.w3schools.com/sql/sql_having.asp) clause, that permits you to filter an aggregate result:
```
SELECT PatientID
FROM Test
WHERE Type = 'GDS'
GROUP BY PatientID
HAVING COUNT(*) = n
``` | how to Group by a new Select statement | [
"",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.